2
0

cryptolib.js 417 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469
  1. /*
  2. * Copyright 2018 Scytl Secure Electronic Voting SA
  3. *
  4. * All rights reserved
  5. *
  6. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7. */
  8. /*
  9. * Copyright 2018 Scytl Secure Electronic Voting SA
  10. *
  11. * All rights reserved
  12. *
  13. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  14. */
  15. /**
  16. * @global
  17. * @description This object describes the configuration scheme for this
  18. * cryptographic library. The following modules are considered:
  19. * <ul>
  20. * <li> Asymmetric
  21. * <li> Primitives
  22. * <li> Stores
  23. * <li> Symmetric
  24. * <li> Digital Envelope
  25. * </ul>
  26. * @readonly
  27. * @property {object} asymmetric.keypair - Policies for generating keypairs.
  28. * @property {object} asymmetric.keypair.encryption - Policies for generating
  29. * encryption keypairs.
  30. * @property {object} asymmetric.keypair.encryption.algorithm - Algorithm.
  31. * @property {string} asymmetric.keypair.encryption.algorithm.RSA - RSA
  32. * algorithm.
  33. * @property {object} asymmetric.keypair.encryption.provider - Provider.
  34. * @property {string} asymmetric.keypair.encryption.provider.FORGE - Forge
  35. * provider.
  36. * @property {object} asymmetric.keypair.encryption.keyLength - Key length.
  37. * @property {number} asymmetric.keypair.encryption.keyLength.KL_2048 - 2048
  38. * bits.
  39. * @property {number} asymmetric.keypair.encryption.keyLength.KL_3072 - 3072
  40. * bits.
  41. * @property {number} asymmetric.keypair.encryption.keyLength.KL_4096 - 4096
  42. * bits.
  43. * @property {object} asymmetric.keypair.encryption.publicExponent - Public
  44. * exponent for generating encryption keypairs.
  45. * @property {number} asymmetric.keypair.encryption.publicExponent.F4 - 65537.
  46. *
  47. * @property {object} asymmetric.signer - Policies for signing and verifying
  48. * data.
  49. * @property {object} asymmetric.signer.algorithm - Algorithm.
  50. * @property {string} asymmetric.signer.algorithm.RSA - RSA algorithm.
  51. * @property {object} asymmetric.signer.provider - Provider.
  52. * @property {string} asymmetric.signer.provider.FORGE - Forge provider.
  53. * @property {object} asymmetric.signer.hash - Hash algorithm.
  54. * @property {string} asymmetric.signer.hash.SHA256 - SHA-256 algorithm.
  55. * @property {object} asymmetric.signer.padding - Padding scheme.
  56. * @property {object} asymmetric.signer.padding.PSS - PSS padding scheme.
  57. * @property {string} asymmetric.signer.padding.PSS.name - PSS.
  58. * @property {object} asymmetric.signer.padding.PSS.hash - Hash for the PSS
  59. * padding scheme.
  60. * @property {string} asymmetric.signer.padding.PSS.hash.SHA256 - SHA-256
  61. * algorithm.
  62. * @property {object} asymmetric.signer.padding.PSS.mask - Mask generating
  63. * function for the PSS padding scheme.
  64. * @property {object} asymmetric.signer.padding.PSS.mask.MGF1 - MGF1 for the PSS
  65. * padding scheme.
  66. * @property {string} asymmetric.signer.padding.PSS.mask.MGF1.name - MGF1.
  67. * @property {object} asymmetric.signer.padding.PSS.mask.MGF1.hash - Hash
  68. * algorithm for the MGF1 for the PSS padding scheme.
  69. * @property {string} asymmetric.signer.padding.PSS.mask.MGF1.hash.SHA256 -
  70. * SHA-256 algorithm.
  71. * @property {object} asymmetric.signer.padding.PSS.saltLengthBytes - Salt
  72. * length for the PSS padding scheme.
  73. * @property {number} asymmetric.signer.padding.PSS.saltLengthBytes.SL_32 - 32
  74. * bytes.
  75. * @property {object} asymmetric.signer.publicExponent - Public exponent.
  76. * @property {number} asymmetric.signer.publicExponent.F4 - 65537.
  77. * @property {object} primitives.securerandom - Policies for generating
  78. * securerandom.
  79. * @property {object} primitives.securerandom.provider - Provider.
  80. * @property {string} primitives.securerandom.provider.SCYTL - Scytl provider.
  81. * @property {object} primitives.messagedigest - Policies for generating message
  82. * digests.
  83. * @property {object} primitives.messagedigest.algorithm - Algorithm.
  84. * @property {string} primitives.messagedigest.algorithm.SHA256 - SHA-256
  85. * algorithm.
  86. * @property {object} primitives.messagedigest.provider - Provider.
  87. * @property {string} primitives.messagedigest.provider.FORGE - Forge provider.
  88. * @property {object} symmetric.secretkey - Policies to generate secret keys.
  89. * @property {number} symmetric.secretkey.length - 128 bits.
  90. * @property {object} symmetric.cipher - Policies to encrypt and decrypt
  91. * symmetrically.
  92. * @property {object} symmetric.cipher.algorithm - Algorithm.
  93. * @property {object} symmetric.cipher.algorithm.AES128_GCM - AES128-GCM
  94. * algorithm.
  95. * @property {string} symmetric.cipher.algorithm.AES128_GCM.name - AES128-GCM.
  96. * @property {number} symmetric.cipher.algorithm.AES128_GCM.keyLengthBytes - 16
  97. * bytes.
  98. * @property {number} symmetric.cipher.algorithm.AES128_GCM.tagLengthBytes - 16
  99. * bytes.
  100. * @property {object} symmetric.cipher.provider - Provider.
  101. * @property {object} symmetric.cipher.provider.FORGE - Forge provider.
  102. * @property {object} symmetric.cipher.initializationVectorLengthBytes -
  103. * Initialization vector length.
  104. * @property {number} symmetric.cipher.initializationVectorLengthBytes.IV_12 -
  105. * 12 bytes.
  106. */
  107. var Config = {
  108. homomorphic: {cipher: {secureRandom: {provider: {SCYTL: 'Scytl'}}}},
  109. asymmetric: {
  110. keypair: {
  111. encryption: {
  112. algorithm: {RSA: 'RSA'},
  113. provider: {FORGE: 'Forge'},
  114. keyLength: {KL_2048: 2048, KL_3072: 3072, KL_4096: 4096},
  115. publicExponent: {F4: 65537}
  116. },
  117. secureRandom: {provider: {SCYTL: 'Scytl'}}
  118. },
  119. signer: {
  120. algorithm: {RSA: 'RSA'},
  121. provider: {FORGE: 'Forge'},
  122. hash: {SHA256: 'SHA256'},
  123. padding: {
  124. PSS: {
  125. name: 'PSS',
  126. hash: {SHA256: 'SHA256'},
  127. mask: {MGF1: {name: 'MGF1', hash: {SHA256: 'SHA256'}}},
  128. saltLengthBytes: {SL_32: 32}
  129. }
  130. },
  131. publicExponent: {F4: 65537},
  132. secureRandom: {provider: {SCYTL: 'Scytl'}}
  133. },
  134. cipher: {
  135. algorithm: {
  136. RSA_OAEP: {
  137. name: 'RSA-OAEP',
  138. hash: 'SHA256',
  139. mask: {MGF1: {name: 'MGF1', hash: 'SHA1'}}
  140. },
  141. RSA_KEM: {
  142. name: 'RSA-KEM',
  143. secretKeyLengthBytes: {KL_16: 16, KL_24: 24, KL_32: 32},
  144. ivLengthBytes: {IVL_12: 12, IVL_16: 16, IVL_32: 32, IVL_64: 64},
  145. tagLengthBytes: {TL_12: 12, TL_16: 16, TL_32: 32, TL_64: 64},
  146. deriver: {
  147. name: {KDF1: 'kdf1', KDF2: 'kdf2', MGF1: 'mgf1'},
  148. messagedigest: {algorithm: {SHA256: 'SHA256'}}
  149. },
  150. cipher: {AESGCM: 'AES-GCM'}
  151. }
  152. },
  153. provider: {FORGE: 'Forge'},
  154. secureRandom: {provider: {SCYTL: 'Scytl'}}
  155. }
  156. },
  157. primitives: {
  158. secureRandom: {provider: {SCYTL: 'Scytl'}},
  159. messagedigest: {
  160. algorithm: {SHA256: 'SHA256', SHA512_224: 'SHA512/224'},
  161. provider: {FORGE: 'Forge'}
  162. },
  163. derivation: {
  164. pbkdf: {
  165. provider: {FORGE: 'Forge'},
  166. hash: {SHA256: 'SHA256'},
  167. saltLengthBytes: {SL_20: 20, SL_32: 32},
  168. keyLengthBytes: {KL_16: 16, KL_32: 32},
  169. iterations: {
  170. I_1: 1,
  171. I_8000: 8000,
  172. I_16000: 16000,
  173. I_32000: 32000,
  174. I_64000: 64000
  175. }
  176. }
  177. }
  178. },
  179. stores: {},
  180. symmetric: {
  181. secretkey: {
  182. encryption: {lengthBytes: {SK_16: 16}},
  183. mac: {lengthBytes: {SK_32: 32}},
  184. secureRandom: {provider: {SCYTL: 'Scytl'}}
  185. },
  186. cipher: {
  187. provider: {FORGE: 'Forge'},
  188. algorithm: {
  189. AES128_GCM: {name: 'AES-GCM', keyLengthBytes: 16, tagLengthBytes: 16}
  190. },
  191. initializationVectorLengthBytes: {IV_12: 12},
  192. secureRandom: {provider: {SCYTL: 'Scytl'}}
  193. },
  194. mac: {hash: {SHA256: 'SHA256'}, provider: {FORGE: 'Forge'}}
  195. },
  196. proofs: {
  197. secureRandom: {provider: {SCYTL: 'Scytl'}},
  198. messagedigest: {
  199. algorithm: {SHA256: 'SHA256', SHA512_224: 'SHA512/224'},
  200. provider: {FORGE: 'Forge'}
  201. },
  202. charset: {UTF8: 'UTF-8'}
  203. },
  204. digitalenvelope: {
  205. symmetric: {
  206. secretkey: {
  207. encryption: {lengthBytes: {SK_16: 16}},
  208. mac: {lengthBytes: {SK_32: 32}},
  209. secureRandom: {provider: {SCYTL: 'Scytl'}}
  210. },
  211. cipher: {
  212. provider: {FORGE: 'Forge'},
  213. algorithm: {
  214. AES128_GCM:
  215. {name: 'AES-GCM', keyLengthBytes: 16, tagLengthBytes: 16}
  216. },
  217. initializationVectorLengthBytes: {IV_12: 12},
  218. secureRandom: {provider: {SCYTL: 'Scytl'}}
  219. },
  220. mac: {hash: {SHA256: 'SHA256'}, provider: {FORGE: 'Forge'}}
  221. },
  222. asymmetric: {
  223. cipher: {
  224. algorithm: {
  225. RSA_OAEP: {
  226. name: 'RSA-OAEP',
  227. hash: 'SHA256',
  228. mask: {MGF1: {name: 'MGF1', hash: 'SHA1'}}
  229. },
  230. RSA_KEM: {
  231. name: 'RSA-KEM',
  232. secretKeyLengthBytes: {KL_16: 16, KL_24: 24, KL_32: 32},
  233. ivLengthBytes: {IVL_12: 12, IVL_16: 16, IVL_32: 32, IVL_64: 64},
  234. tagLengthBytes: {TL_12: 12, TL_16: 16, TL_32: 32, TL_64: 64},
  235. deriver: {
  236. name: {KDF1: 'kdf1', KDF2: 'kdf2', MGF1: 'mgf1'},
  237. messagedigest: {algorithm: {SHA256: 'SHA256'}}
  238. },
  239. cipher: {AESGCM: 'AES-GCM'}
  240. }
  241. },
  242. provider: {FORGE: 'Forge'},
  243. secureRandom: {provider: {SCYTL: 'Scytl'}}
  244. }
  245. }
  246. }
  247. };
  248. if (Object.freeze) {
  249. /**
  250. * Freezes an object and all its contents.
  251. * @param {Object} target the object to freeze.
  252. */
  253. var recursiveFreeze = function(target) {
  254. 'use strict';
  255. // Get all property names
  256. var propNames = Object.getOwnPropertyNames(target);
  257. // Freeze the object's properties.
  258. propNames.forEach(function(name) {
  259. var property = target[name];
  260. // Freeze the properties' properties.
  261. if (typeof property === 'object' && property !== null) {
  262. recursiveFreeze(property);
  263. }
  264. });
  265. // Freeze the object itself.
  266. return Object.freeze(target);
  267. };
  268. // Lock down the configuration
  269. recursiveFreeze(Config);
  270. }
  271. var cryptolibPolicies;
  272. /**
  273. * @global
  274. * @function cryptolib
  275. *
  276. * @description Core of the library, this module is used to sandbox the
  277. * requested modules.
  278. *
  279. * @example // how to load all modules cryptolib('*', function(box) { // any
  280. * module can be used from here. //
  281. * box.examplemodule.service.getExample(); });
  282. *
  283. *
  284. * @param modules
  285. * {...modules} modules to be loaded. '*' or none to load all the
  286. * modules.
  287. * @param function
  288. * {cryptolibSandbox} a closure for the cryptolib object.
  289. * @tutorial workers
  290. */
  291. function cryptolib() {
  292. 'use strict';
  293. /* Class to keep the references to polices and prng. */
  294. function Cryptolib(modules, callback) {
  295. function getAllModules(parent) {
  296. var modules = [];
  297. for (var module in parent) {
  298. if (parent.hasOwnProperty(module)) {
  299. modules.push(module);
  300. }
  301. }
  302. return modules;
  303. }
  304. function loadModules(box, modules, parentModule) {
  305. if (!modules || modules.toString() === '*'.toString()) {
  306. modules = getAllModules(parentModule);
  307. }
  308. for (var i = 0; i < modules.length; i += 1) {
  309. var firstDotIndex = modules[i].indexOf('.');
  310. if (firstDotIndex > -1) {
  311. var subModule = modules[i].substr(firstDotIndex + 1);
  312. var root = modules[i].substr(0, firstDotIndex);
  313. loadModules(box, [subModule], parentModule[root]);
  314. } else if (typeof parentModule[modules[i]] === 'function') {
  315. parentModule[modules[i]](box);
  316. } else if (typeof parentModule[modules[i]] === 'object') {
  317. loadModules(box, '*', parentModule[modules[i]]);
  318. }
  319. }
  320. }
  321. this.policies = callback.policies || cryptolibPolicies;
  322. cryptolibPolicies = cryptolibPolicies || this.policies;
  323. this.prng = callback.prng || cryptoPRNG.getPRNG();
  324. loadModules(this, modules, cryptolib.modules);
  325. callback(this);
  326. }
  327. Cryptolib.prototype = {
  328. getKeys: function(obj) {
  329. var keys = [];
  330. for (var key in obj) {
  331. if (typeof key !== 'undefined') {
  332. keys.push(key);
  333. }
  334. }
  335. return keys;
  336. },
  337. getModuleNames: function() {
  338. var moduleNames = '';
  339. for (var module in cryptolib.modules) {
  340. if (typeof module !== 'undefined') {
  341. if (moduleNames.length > 0) {
  342. moduleNames += ', ';
  343. }
  344. moduleNames += module;
  345. }
  346. }
  347. return '[' + moduleNames + ']';
  348. },
  349. forge: forge, // redefines forge global variable
  350. sjcl: sjcl, // redefines sjcl global variable
  351. // Constants.
  352. /** @constant */
  353. NUMBER_OF_BITS_PER_BYTE: 8,
  354. /** @constant */
  355. MAXIMUM_LENGTH_TO_GENERATE_DATA: 512,
  356. /** @constant */
  357. BASE_2_RADIX: 2,
  358. /** @constant */
  359. BASE_10_RADIX: 10,
  360. /** @constant */
  361. BASE_16_RADIX: 16,
  362. /** @constant */
  363. EPOCH_TIME_LENGTH: 10,
  364. /** @constant */
  365. RSA_LINE_LENGTH: 64,
  366. /** @constant */
  367. SHA_256_LENGTH: 32,
  368. /** @constant */
  369. HMAC_SHA256_KEY_LENGTH: 32,
  370. /** @constant */
  371. AES_KEY_LENGTH: 16,
  372. /** @constant */
  373. AES_CBC_IV_LENGTH: 16,
  374. /** @constant */
  375. DES3_KEY_LENGTH: 24,
  376. /** @constant */
  377. DES3_CBC_IV_LENGTH: 8,
  378. EQUALS: ' = ',
  379. NEWLINE: '\n',
  380. CRYPTO_SPEC_DELIM: '/',
  381. /** @constant */
  382. SHA_256: 'SHA256',
  383. /** @constant */
  384. RSA_ECB_PKCS1PADDING: 'RSA/ECB/PKCS1PADDING',
  385. /** @constant */
  386. RSA_ECB_OAEP_WITH_SHA256_AND_MGF1PADDING:
  387. 'RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING',
  388. /** @constant */
  389. FORGE_RSA_OAEP: 'RSA-OAEP',
  390. /** @constant */
  391. FORGE_RSAES_PKCS1_V1_5: 'RSAES-PKCS1-V1_5',
  392. /** @constant */
  393. MINIMUM_PRIME_CERTAINTY_LEVEL: 80,
  394. /** @constant */
  395. SHORT_EXPONENT_BIT_LENGTH: 256,
  396. /** @constant */
  397. EXPONENTIATION_PROOF_AUXILIARY_DATA: 'ExponentiationProof',
  398. /** @constant */
  399. PLAINTEXT_PROOF_AUXILIARY_DATA: 'PlaintextProof',
  400. /** @constant */
  401. SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA:
  402. 'SimplePlaintextEqualityProof',
  403. /** @constant */
  404. PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA: 'PlaintextEqualityProof',
  405. /** @constant */
  406. PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA:
  407. 'PlaintextExponentEqualityProof'
  408. };
  409. var args = Array.prototype.slice.call(arguments);
  410. var callback = args.pop();
  411. var modules = (args[0] && typeof args[0] === 'string') ? args : args[0];
  412. return new Cryptolib(modules, callback);
  413. }
  414. cryptolib.modules = {};
  415. /*
  416. * Copyright 2018 Scytl Secure Electronic Voting SA
  417. *
  418. * All rights reserved
  419. *
  420. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  421. */
  422. ////////////////////////////////////////////////
  423. //
  424. // Functionalities added to JavaScript types
  425. //
  426. ////////////////////////////////////////////////
  427. /**
  428. * An equals method for arrays.
  429. *
  430. * @param array
  431. * the array to which this array should be compared.
  432. * @param strict
  433. * a boolean value which specifies whether or not the elements must
  434. * be in the same order in both arrays. This parameter is optional,
  435. * if it is not supplied, then a default value of 'true' is assigned
  436. * to it.
  437. */
  438. Array.prototype.equals = function(array, strict) {
  439. 'use strict';
  440. if (!array) {
  441. return false;
  442. }
  443. if (arguments.length === 1) {
  444. strict = true;
  445. }
  446. if (this.length !== array.length) {
  447. return false;
  448. }
  449. for (var i = 0; i < this.length; i++) {
  450. if (this[i] instanceof Array && array[i] instanceof Array) {
  451. if (!this[i].equals(array[i], strict)) {
  452. return false;
  453. }
  454. } else if (strict && (!this[i].equals(array[i]))) {
  455. return false;
  456. } else if (!strict) {
  457. return this.sort().equals(array.sort(), true);
  458. }
  459. }
  460. return true;
  461. };
  462. /**
  463. * Allows all of the elements of one array to be added into another array.
  464. */
  465. Array.prototype.addAll = function() {
  466. 'use strict';
  467. for (var a = 0; a < arguments.length; a++) {
  468. var arr = arguments[a];
  469. for (var i = 0; i < arr.length; i++) {
  470. this.push(arr[i]);
  471. }
  472. }
  473. };
  474. /*
  475. * Copyright 2018 Scytl Secure Electronic Voting SA
  476. *
  477. * All rights reserved
  478. *
  479. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  480. */
  481. cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
  482. /**
  483. * @namespace asymmetric/cipher
  484. */
  485. cryptolib.modules.asymmetric.cipher = function(box) {
  486. 'use strict';
  487. box.asymmetric = box.asymmetric || {};
  488. box.asymmetric.cipher = {};
  489. /**
  490. * A module that holds asymmetric cipher functionalities.
  491. *
  492. * @exports asymmetric/cipher/factory
  493. */
  494. box.asymmetric.cipher.factory = {};
  495. var policies = {
  496. cipher: {
  497. algorithm: box.policies.asymmetric.cipher.algorithm,
  498. secretKeyLengthBytes: box.policies.asymmetric.cipher.secretKeyLengthBytes,
  499. ivLengthBytes: box.policies.asymmetric.cipher.ivLengthBytes,
  500. tagLengthBytes: box.policies.asymmetric.cipher.tagLengthBytes,
  501. deriver: box.policies.asymmetric.cipher.deriver,
  502. hash: box.policies.asymmetric.cipher.hash,
  503. symmetricCipher: box.policies.asymmetric.cipher.symmetricCipher,
  504. provider: box.policies.asymmetric.cipher.provider
  505. }
  506. };
  507. var utils, converters, exceptions, randomFactory;
  508. var f = function(box) {
  509. utils = box.commons.utils;
  510. converters = new box.commons.utils.Converters();
  511. exceptions = box.commons.exceptions;
  512. randomFactory =
  513. new box.primitives.securerandom.factory.SecureRandomFactory();
  514. };
  515. f.policies = {
  516. primitives: {
  517. secureRandom:
  518. {provider: box.policies.asymmetric.cipher.secureRandom.provider}
  519. }
  520. };
  521. cryptolib('commons', 'primitives.securerandom', f);
  522. /** @class */
  523. box.asymmetric.cipher.factory.AsymmetricCipherFactory = function() {};
  524. box.asymmetric.cipher.factory.AsymmetricCipherFactory.prototype = {
  525. /**
  526. * @function Gets an asymmetric cipher.
  527. * @returns {asymmetric/cipher.CryptoForgeAsymmetricCipher}
  528. */
  529. getCryptoAsymmetricCipher: function() {
  530. try {
  531. if (policies.cipher.provider ===
  532. Config.asymmetric.cipher.provider.FORGE) {
  533. var secureRandomBytes = randomFactory.getCryptoRandomBytes();
  534. return this.getCryptoForgeAsymmetricCipher(secureRandomBytes);
  535. } else {
  536. throw new exceptions.CryptoLibException(
  537. 'No suitable provider for the asymmetric cipher was provided.');
  538. }
  539. } catch (error) {
  540. throw new exceptions.CryptoLibException(
  541. 'A CryptoAsymmetricCipher could not be obtained.', error);
  542. }
  543. },
  544. /**
  545. * @function Gets a Forge asymmetric cipher.
  546. * @param secureRandom
  547. * {CryptoScytlRandomBytes} a source of random bytes.
  548. * @returns {asymmetric/cipher.CryptoForgeAsymmetricCipher}
  549. */
  550. getCryptoForgeAsymmetricCipher: function(secureRandom) {
  551. return new CryptoForgeAsymmetricCipher(secureRandom);
  552. }
  553. };
  554. /**
  555. * Defines a Forge asymmetric cipher
  556. *
  557. * @class
  558. * @param secureRandomBytes
  559. * {CryptoScytlRandomBytes} a source of random bytes.
  560. * @memberof asymmetric/cipher
  561. */
  562. function CryptoForgeAsymmetricCipher(secureRandomBytes) {
  563. if (!secureRandomBytes) {
  564. throw new exceptions.CryptoLibException(
  565. 'The received PRNG was not valid');
  566. }
  567. this.bitOperators = new utils.BitOperators();
  568. this.secureRandomBytes = secureRandomBytes;
  569. // We would like to use the SCYTL PRNG directly in the ciphers that are
  570. // created. However it is currently not possible to pass a PRNG to the
  571. // Forge library when creating or using a cipher. However, in some cases,
  572. // it is possible to pass a seed (created using the SCYTL PRNG) to FORGE
  573. // that is then used to seed the FORGE internal PRNG.
  574. this.encodingSeedLength = 32;
  575. try {
  576. if ((policies.cipher.algorithm.name !==
  577. Config.asymmetric.cipher.algorithm.RSA_OAEP.name) &&
  578. (policies.cipher.algorithm.name !==
  579. Config.asymmetric.cipher.algorithm.RSA_KEM.name)) {
  580. throw new exceptions.CryptoLibException(
  581. 'The specified algorithm is not supported.');
  582. }
  583. } catch (error) {
  584. throw new exceptions.CryptoLibException(
  585. 'CryptoForgeAsymmetricCipher could not be created.', error);
  586. }
  587. /**
  588. * Parses the four parts of the data that is produced by the encrypt
  589. * function, and that is received by the decrypt function.
  590. * <p>
  591. * We know the length of three of these parts, and we know the total
  592. * length of the data, therefore we can parse out all four of the parts.
  593. */
  594. this._parseParts = function(privateKey, encryptedData) {
  595. var ivLengthBytes = policies.cipher.ivLengthBytes;
  596. var tagLengthBytes = policies.cipher.tagLengthBytes;
  597. var encapsulationLengthBytes = privateKey.n.bitLength() / 8;
  598. var totalLength = encryptedData.length;
  599. var totalKnownLength =
  600. encapsulationLengthBytes + ivLengthBytes + tagLengthBytes;
  601. var encryptedDataLength = totalLength - totalKnownLength;
  602. var startIndexOfSecondPart = encapsulationLengthBytes;
  603. var startIndexOfThirdPart = startIndexOfSecondPart + ivLengthBytes;
  604. var startIndexOfFourthPart = startIndexOfThirdPart + encryptedDataLength;
  605. var encapsulation =
  606. this.bitOperators.extract(encryptedData, 0, startIndexOfSecondPart);
  607. var iv = this.bitOperators.extract(
  608. encryptedData, startIndexOfSecondPart, startIndexOfThirdPart);
  609. var data = this.bitOperators.extract(
  610. encryptedData, startIndexOfThirdPart, startIndexOfFourthPart);
  611. var tag =
  612. this.bitOperators.extract(encryptedData, startIndexOfFourthPart);
  613. return {encapsulation: encapsulation, iv: iv, data: data, tag: tag};
  614. };
  615. this._validateInputs = function(keyPem, data) {
  616. if (!keyPem) {
  617. throw new exceptions.CryptoLibException(
  618. 'The received key was not initialized.');
  619. }
  620. if (!data) {
  621. throw new exceptions.CryptoLibException(
  622. 'The received data was not initialized.');
  623. }
  624. };
  625. // Note: at the moment, the options that are being used with the RSA_OAEP
  626. // algorithm are hardcoded (for encrypting and decrypting). This could be
  627. // improved so that these are read from the properties file. Doing this will
  628. // mean any that existing properties files (used by consumers of the
  629. // library) will become invalid (if the consumer uses RSA_OAEP) as they wont
  630. // have the mandatory new properties.
  631. this._getRsaOaepHash = function() {
  632. return box.forge.md.sha256.create();
  633. };
  634. //
  635. this._getRsaOaepMaskHash = function() {
  636. // For interoperability purposes, the MGF1 hash function must
  637. // remain as SHA-1.
  638. return box.forge.md.sha1.create();
  639. };
  640. this._getRsaOaepEncodingOptions = function() {
  641. var encodingOptions = {
  642. md: this._getRsaOaepHash(),
  643. mgf1: {md: this._getRsaOaepMaskHash()},
  644. seed: this.secureRandomBytes.nextRandom(this.encodingSeedLength)
  645. };
  646. return encodingOptions;
  647. };
  648. this._getRsaOaepDecodingOptions = function() {
  649. var decodingOptions = {
  650. md: this._getRsaOaepHash(),
  651. mgf1: {md: this._getRsaOaepMaskHash()}
  652. };
  653. return decodingOptions;
  654. };
  655. this._determineAndCreateHash = function(requestedHash) {
  656. if (requestedHash ===
  657. Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.messagedigest
  658. .algorithm.SHA256) {
  659. return forge.md.sha256.create();
  660. } else {
  661. throw new exceptions.CryptoLibException(
  662. 'Unsupported hash function specified.');
  663. }
  664. };
  665. this._determineAndCreateDeriver = function(requestedDeriver) {
  666. var hash = this._determineAndCreateHash(policies.cipher.hash);
  667. if (requestedDeriver ===
  668. Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.KDF1) {
  669. return new forge.kem.kdf1(hash);
  670. } else if (
  671. requestedDeriver ===
  672. Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.KDF2) {
  673. return new forge.kem.kdf2(hash);
  674. } else if (
  675. requestedDeriver ===
  676. Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.MGF1) {
  677. return new forge.mgf.mgf1.create(hash);
  678. } else {
  679. throw new exceptions.CryptoLibException(
  680. 'Unsupported deriver function specified.');
  681. }
  682. };
  683. }
  684. CryptoForgeAsymmetricCipher.prototype = {
  685. /**
  686. * Encrypts some data.
  687. * <p>
  688. * If the algorithm is RSA-KEM, then the output from this function will
  689. * be the base64 encoding of the following data:
  690. * <p>
  691. * [Encapsulation][IV][Encrypted Data][Tag]
  692. *
  693. * @function
  694. * @param publicKeyPem
  695. * {string} public key, as string in PEM format.
  696. * @param dataBase64
  697. * {string} data to be encrypted, as string in Base64 encoded
  698. * format.
  699. * @returns encrypted data, as string in Base 64 encoded format..
  700. */
  701. encrypt: function(publicKeyPem, dataBase64) {
  702. this._validateInputs(publicKeyPem, dataBase64);
  703. try {
  704. var publicKey = box.forge.pki.publicKeyFromPem(publicKeyPem);
  705. var data = converters.base64Decode(dataBase64);
  706. var output;
  707. if (policies.cipher.algorithm.name ===
  708. Config.asymmetric.cipher.algorithm.RSA_OAEP.name) {
  709. var encodingOptions = this._getRsaOaepEncodingOptions();
  710. output = publicKey.encrypt(
  711. data, policies.cipher.algorithm.name, encodingOptions);
  712. } else if (
  713. policies.cipher.algorithm.name ===
  714. Config.asymmetric.cipher.algorithm.RSA_KEM.name) {
  715. var secretKeyLengthBytes = policies.cipher.secretKeyLengthBytes;
  716. var ivLengthBytes = policies.cipher.ivLengthBytes;
  717. var symmetricCipher = policies.cipher.symmetricCipher;
  718. var deriver =
  719. this._determineAndCreateDeriver(policies.cipher.deriver);
  720. // generate and encapsulate secret key
  721. var kem = forge.kem.rsa.create(deriver);
  722. var result = kem.encrypt(publicKey, secretKeyLengthBytes);
  723. var iv = forge.random.getBytesSync(ivLengthBytes);
  724. var cipher = forge.cipher.createCipher(symmetricCipher, result.key);
  725. cipher.start({iv: iv});
  726. cipher.update(forge.util.createBuffer(data));
  727. cipher.finish();
  728. var encryptedData = cipher.output.getBytes();
  729. var tag = cipher.mode.tag.getBytes();
  730. output = result.encapsulation.toString() + iv.toString() +
  731. encryptedData.toString() + tag.toString();
  732. } else {
  733. throw new exceptions.CryptoLibException(
  734. 'The specified algorithm is not supported.');
  735. }
  736. return converters.base64Encode(output);
  737. } catch (error) {
  738. throw new exceptions.CryptoLibException(
  739. 'CryptoForgeAsymmetricCipher, data could not be encrypted.', error);
  740. }
  741. },
  742. /**
  743. * Decrypts some encrypted data.
  744. *
  745. * @function
  746. * @param privateKeyPem
  747. * {string} private key, as string in PEM format.
  748. * @param encryptedDataB64
  749. * {string} encrypted data, as string in Base64 encoded
  750. * format.
  751. * @returns decrypted data, as string in Base64 encoded format.
  752. */
  753. decrypt: function(privateKeyPem, encryptedDataBase64) {
  754. this._validateInputs(privateKeyPem, encryptedDataBase64);
  755. try {
  756. var privateKey = box.forge.pki.privateKeyFromPem(privateKeyPem);
  757. var encryptedData = converters.base64Decode(encryptedDataBase64);
  758. var decryptedData;
  759. if (policies.cipher.algorithm.name ===
  760. Config.asymmetric.cipher.algorithm.RSA_OAEP.name) {
  761. var decodingOptions = this._getRsaOaepDecodingOptions();
  762. decryptedData = privateKey.decrypt(
  763. encryptedData, policies.cipher.algorithm.name, decodingOptions);
  764. } else if (
  765. policies.cipher.algorithm.name ===
  766. Config.asymmetric.cipher.algorithm.RSA_KEM.name) {
  767. var symmetricCipher = policies.cipher.symmetricCipher;
  768. var secretKeyLengthBytes = policies.cipher.secretKeyLengthBytes;
  769. var encryptedDataParts = this._parseParts(privateKey, encryptedData);
  770. var deriver =
  771. this._determineAndCreateDeriver(policies.cipher.deriver);
  772. // decrypt encapsulated secret key
  773. var kem = forge.kem.rsa.create(deriver);
  774. var key = kem.decrypt(
  775. privateKey, encryptedDataParts.encapsulation,
  776. secretKeyLengthBytes);
  777. // decrypt some bytes
  778. var decipher = forge.cipher.createDecipher(symmetricCipher, key);
  779. decipher.start(
  780. {iv: encryptedDataParts.iv, tag: encryptedDataParts.tag});
  781. decipher.update(forge.util.createBuffer(encryptedDataParts.data));
  782. var result = decipher.finish();
  783. // result will be false if there was a failure
  784. if (result) {
  785. decryptedData = decipher.output.getBytes();
  786. } else {
  787. throw new exceptions.CryptoLibException(
  788. 'Error while decrypting data.');
  789. }
  790. } else {
  791. throw new exceptions.CryptoLibException(
  792. 'The specified algorithm is not supported.');
  793. }
  794. return converters.base64Encode(decryptedData);
  795. } catch (error) {
  796. throw new exceptions.CryptoLibException(
  797. 'CryptoForgeAsymmetricCipher, data could not be decrypted.', error);
  798. }
  799. }
  800. };
  801. };
  802. /*
  803. * Copyright 2018 Scytl Secure Electronic Voting SA
  804. *
  805. * All rights reserved
  806. *
  807. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  808. */
  809. cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
  810. /** @namespace asymmetric/keypair */
  811. cryptolib.modules.asymmetric.keypair = function(box) {
  812. 'use strict';
  813. box.asymmetric = box.asymmetric || {};
  814. box.asymmetric.keypair = {};
  815. /**
  816. * A module that holds certificates functionalities.
  817. *
  818. * @exports asymmetric/keypair/factory
  819. */
  820. box.asymmetric.keypair.factory = {};
  821. var policies = {
  822. encryption: {
  823. algorithm: box.policies.asymmetric.keypair.encryption.algorithm,
  824. provider: box.policies.asymmetric.keypair.encryption.provider,
  825. keyLength: box.policies.asymmetric.keypair.encryption.keyLength,
  826. publicExponent: box.policies.asymmetric.keypair.encryption.publicExponent
  827. }
  828. };
  829. var exceptions, randomFactory;
  830. var f = function(box) {
  831. exceptions = box.commons.exceptions;
  832. randomFactory =
  833. new box.primitives.securerandom.factory.SecureRandomFactory();
  834. };
  835. f.policies = {
  836. primitives: {
  837. secureRandom:
  838. {provider: box.policies.asymmetric.keypair.secureRandom.provider}
  839. }
  840. };
  841. cryptolib('commons.exceptions', 'primitives.securerandom', f);
  842. /**
  843. * A factory class for generating
  844. * {@link asymmetric.keypair.CryptoForgeKeyPairGenerator} objects.
  845. *
  846. * @class
  847. */
  848. box.asymmetric.keypair.factory.KeyPairGeneratorFactory = function() {};
  849. box.asymmetric.keypair.factory.KeyPairGeneratorFactory.prototype = {
  850. /**
  851. * @function
  852. * @returns CryptoForgeKeyPairGenerator
  853. */
  854. getEncryptionCryptoKeyPairGenerator: function() {
  855. var secureRandom;
  856. try {
  857. if (policies.encryption.provider ===
  858. Config.asymmetric.keypair.encryption.provider.FORGE) {
  859. secureRandom = randomFactory.getCryptoRandomBytes();
  860. return this.getCryptoForgeKeyPairGenerator(secureRandom);
  861. } else {
  862. throw new exceptions.CryptoLibException(
  863. 'No suitable provider was provided.');
  864. }
  865. } catch (error) {
  866. throw new exceptions.CryptoLibException(
  867. 'An encryption CryptoKeyPairGenerator could not be obtained.',
  868. error);
  869. }
  870. },
  871. getCryptoForgeKeyPairGenerator: function(secureRandom) {
  872. return new CryptoForgeKeyPairGenerator(secureRandom);
  873. }
  874. };
  875. /**
  876. * Defines an encryption key pair generator for the FORGE provider.
  877. *
  878. * @class
  879. * @memberof asymmetric/keypair
  880. */
  881. function CryptoForgeKeyPairGenerator(secureRandom) {
  882. this.secureRandom = secureRandom;
  883. }
  884. CryptoForgeKeyPairGenerator.prototype = {
  885. /**
  886. * Generates an encryption key pair.
  887. *
  888. * @returns {asymmetric/keypair.KeyPair} an encryption key pair.
  889. */
  890. generate: function() {
  891. try {
  892. if (policies.encryption.algorithm ===
  893. Config.asymmetric.keypair.encryption.algorithm.RSA) {
  894. var options = {prng: this.secureRandom};
  895. var keys = forge.pki.rsa.generateKeyPair(
  896. policies.encryption.keyLength, policies.encryption.publicExponent,
  897. options);
  898. var forgePublicKey = keys.publicKey;
  899. var forgePrivateKey = keys.privateKey;
  900. var publicKeyPem = forge.pki.publicKeyToPem(forgePublicKey);
  901. var privateKeyPem = forge.pki.privateKeyToPem(forgePrivateKey);
  902. var publicKey = new PublicKey(
  903. policies.encryption.algorithm, forgePublicKey.n, forgePublicKey.e,
  904. publicKeyPem);
  905. var privateKey = new PrivateKey(
  906. policies.encryption.algorithm, forgePrivateKey.n,
  907. forgePrivateKey.e, forgePrivateKey.d, forgePrivateKey.p,
  908. forgePrivateKey.q, forgePrivateKey.dP, forgePrivateKey.dQ,
  909. forgePrivateKey.qInv, privateKeyPem);
  910. return new KeyPair(publicKey, privateKey);
  911. } else {
  912. throw new exceptions.CryptoLibException(
  913. 'The given algorithm is not supported.');
  914. }
  915. } catch (error) {
  916. throw new exceptions.CryptoLibException(
  917. 'Encryption key pair could not be generated.', error);
  918. }
  919. }
  920. };
  921. /**
  922. * Container class for an encryption key pair.
  923. *
  924. * @class
  925. * @param publicKey
  926. * public key of the encryption key pair.
  927. * @param privateKey
  928. * private key of the encryption key pair.
  929. * @memberof asymmetric/keypair
  930. */
  931. function KeyPair(publicKey, privateKey) {
  932. /**
  933. * Retrieves the public key of the encryption key pair.
  934. *
  935. * @function
  936. * @returns PrivateKey Public key of encryption key pair.
  937. */
  938. var getPublicKey = function() {
  939. return publicKey;
  940. };
  941. /**
  942. * Retrieves the private key of the encryption key pair.
  943. *
  944. * @function
  945. * @returns PrivateKey Private key of encryption key pair.
  946. */
  947. var getPrivateKey = function() {
  948. return privateKey;
  949. };
  950. return {getPublicKey: getPublicKey, getPrivateKey: getPrivateKey};
  951. }
  952. /**
  953. * @class PrivateKey
  954. * @memberof asymmetric/keypair
  955. */
  956. function PrivateKey(algorithm, n, e, d, p, q, dP, dQ, qInv, pem) {
  957. /**
  958. * @function
  959. * @returns {string}
  960. * @memberof asymmetric/keypair.PrivateKey
  961. */
  962. var getAlgorithm = function() {
  963. return algorithm;
  964. };
  965. /**
  966. * @function
  967. * @memberof asymmetric/keypair.PrivateKey
  968. */
  969. var getModulus = function() {
  970. return n;
  971. };
  972. /**
  973. * @function
  974. * @memberof asymmetric/keypair.PrivateKey
  975. */
  976. var getPublicExponent = function() {
  977. return e;
  978. };
  979. /**
  980. * @function
  981. * @memberof asymmetric/keypair.PrivateKey
  982. */
  983. var getPrivateExponent = function() {
  984. return d;
  985. };
  986. /**
  987. * @function
  988. * @memberof asymmetric/keypair.PrivateKey
  989. */
  990. var getPrime1 = function() {
  991. return p;
  992. };
  993. /**
  994. * @function
  995. * @memberof asymmetric/keypair.PrivateKey
  996. */
  997. var getPrime2 = function() {
  998. return q;
  999. };
  1000. /**
  1001. * @function
  1002. * @memberof asymmetric/keypair.PrivateKey
  1003. */
  1004. var getExponent1 = function() {
  1005. return dP;
  1006. };
  1007. /**
  1008. * @function
  1009. * @memberof asymmetric/keypair.PrivateKey
  1010. */
  1011. var getExponent2 = function() {
  1012. return dQ;
  1013. };
  1014. /**
  1015. * @function
  1016. * @memberof asymmetric/keypair.PrivateKey
  1017. */
  1018. var getCoefficient = function() {
  1019. return qInv;
  1020. };
  1021. /**
  1022. * @function
  1023. * @memberof asymmetric/keypair.PrivateKey
  1024. */
  1025. var getPem = function() {
  1026. return pem;
  1027. };
  1028. return {
  1029. getAlgorithm: getAlgorithm,
  1030. getModulus: getModulus,
  1031. getPublicExponent: getPublicExponent,
  1032. getPrivateExponent: getPrivateExponent,
  1033. getPrime1: getPrime1,
  1034. getPrime2: getPrime2,
  1035. getExponent1: getExponent1,
  1036. getExponent2: getExponent2,
  1037. getCoefficient: getCoefficient,
  1038. getPem: getPem
  1039. };
  1040. }
  1041. /** @class PublicKey */
  1042. function PublicKey(algorithm, n, e, pem) {
  1043. /**
  1044. * @function
  1045. * @memberof asymmetric/keypair.PublicKey
  1046. */
  1047. var getAlgorithm = function() {
  1048. return algorithm;
  1049. };
  1050. /**
  1051. * @function
  1052. * @memberof asymmetric/keypair.PublicKey
  1053. */
  1054. var getModulus = function() {
  1055. return n;
  1056. };
  1057. /**
  1058. * @function
  1059. * @memberof asymmetric/keypair.PublicKey
  1060. */
  1061. var getPublicExponent = function() {
  1062. return e;
  1063. };
  1064. /**
  1065. * @function
  1066. * @memberof asymmetric/keypair.PublicKey
  1067. */
  1068. var getPem = function() {
  1069. return pem;
  1070. };
  1071. return {
  1072. getAlgorithm: getAlgorithm,
  1073. getModulus: getModulus,
  1074. getPublicExponent: getPublicExponent,
  1075. getPem: getPem
  1076. };
  1077. }
  1078. };
  1079. /*
  1080. * Copyright 2018 Scytl Secure Electronic Voting SA
  1081. *
  1082. * All rights reserved
  1083. *
  1084. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  1085. */
  1086. cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
  1087. cryptolib.modules.asymmetric.service = function(box) {
  1088. 'use strict';
  1089. box.asymmetric = box.asymmetric || {};
  1090. /**
  1091. * A module that holds certificates functionalities.
  1092. * @exports asymmetric/service
  1093. */
  1094. box.asymmetric.service = {};
  1095. var keypairGeneratorFactory, signerFactory, xmlSignerFactory,
  1096. cipherFactory;
  1097. cryptolib(
  1098. 'asymmetric.signer', 'asymmetric.xmlsigner', 'asymmetric.keypair',
  1099. 'asymmetric.cipher', 'commons.exceptions', function(box) {
  1100. keypairGeneratorFactory =
  1101. new box.asymmetric.keypair.factory.KeyPairGeneratorFactory();
  1102. signerFactory = new box.asymmetric.signer.factory.SignerFactory();
  1103. xmlSignerFactory =
  1104. new box.asymmetric.xmlsigner.factory.XmlSignerFactory();
  1105. cipherFactory =
  1106. new box.asymmetric.cipher.factory.AsymmetricCipherFactory();
  1107. });
  1108. /**
  1109. * Generates a {@link asymmetric/keypair.KeyPair} to be used for encrypt data.
  1110. * @function
  1111. * @returns {asymmetric/keypair.KeyPair} it can be used for encrypt data.
  1112. */
  1113. box.asymmetric.service.getKeyPairForEncryption = function() {
  1114. var cryptoKeyPairGenerator =
  1115. keypairGeneratorFactory.getEncryptionCryptoKeyPairGenerator();
  1116. return cryptoKeyPairGenerator.generate();
  1117. };
  1118. /**
  1119. * Encrypts the given plain text using the given
  1120. * public key.
  1121. * @function
  1122. * @param publicKeyPem
  1123. * {String} public key, as string in PEM format.
  1124. * @param dataBase64
  1125. * {String} data to encrypt, as a string in Base64 encoded
  1126. * format.
  1127. * @return encrypted data in Base64 encoded format.
  1128. */
  1129. box.asymmetric.service.encrypt = function(publicKeyPem, dataBase64) {
  1130. var cipher = cipherFactory.getCryptoAsymmetricCipher();
  1131. return cipher.encrypt(publicKeyPem, dataBase64);
  1132. };
  1133. /**
  1134. * Decrypts the given cipher text with the given
  1135. * private key.
  1136. * @function
  1137. * @param privateKeyPem
  1138. * {String} private key, as string in PEM format.
  1139. * @param encryptedDataBase64
  1140. * {String} data to decrypt, as a string in Base64 encoded
  1141. * format.
  1142. * @return a string in Base64 encoded format.
  1143. */
  1144. box.asymmetric.service.decrypt = function(
  1145. privateKeyPem, encryptedDataBase64) {
  1146. var cipher = cipherFactory.getCryptoAsymmetricCipher();
  1147. return cipher.decrypt(privateKeyPem, encryptedDataBase64);
  1148. };
  1149. /**
  1150. * Signs the given message using the given private key.
  1151. * @function
  1152. * @param privateKeyPem
  1153. * {String} private key, as string in PEM format.
  1154. * @param arrayDataBase64
  1155. * {String} data to sign, as an array of string in Base64 encoded
  1156. * format.
  1157. * @return signature, in Base64 encoded format.
  1158. */
  1159. box.asymmetric.service.sign = function(privateKeyPem, ArrayDataBase64) {
  1160. var cryptoSigner = signerFactory.getCryptoSigner();
  1161. return cryptoSigner.sign(privateKeyPem, ArrayDataBase64);
  1162. };
  1163. /**
  1164. * Verifies that the given signature is indeed the signature of the given
  1165. * bytes, using the given public key.
  1166. * @function
  1167. * @param signatureB64
  1168. * {String} signature, as string in Base64 encoded format.
  1169. * @param publicKeyPem
  1170. * {String} public key, as string in PEM format.
  1171. * @param arrayDataBase64
  1172. * {String} data that was signed, as an array of string in Base64
  1173. * encoded format.
  1174. *
  1175. * @return boolean indicating whether signature verification was successful.
  1176. */
  1177. box.asymmetric.service.verifySignature = function(
  1178. signatureBase64, publicKeyPem, arrayDataBase64) {
  1179. var cryptoSigner = signerFactory.getCryptoSigner();
  1180. return cryptoSigner.verify(signatureBase64, publicKeyPem, arrayDataBase64);
  1181. };
  1182. /**
  1183. * Verifies the signature of some data that is in XML format.
  1184. * @function
  1185. * @param publicKey
  1186. * {Object} Public key.
  1187. * @param signedXml
  1188. * {string} XML with selfcontained signature, to verify
  1189. * @param signatureParentNode
  1190. * {string} Node where the signature is
  1191. *
  1192. * @return boolean indicating whether signature verification was successful.
  1193. */
  1194. box.asymmetric.service.verifyXmlSignature = function(
  1195. publicKey, signedXml, signatureParentNode) {
  1196. var cryptoXmlSigner = xmlSignerFactory.getCryptoXmlSigner();
  1197. return cryptoXmlSigner.verify(publicKey, signedXml, signatureParentNode);
  1198. };
  1199. };
  1200. /*
  1201. * Copyright 2018 Scytl Secure Electronic Voting SA
  1202. *
  1203. * All rights reserved
  1204. *
  1205. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  1206. */
  1207. cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
  1208. /** @namespace asymmetric/signer */
  1209. cryptolib.modules.asymmetric.signer = function(box) {
  1210. 'use strict';
  1211. box.asymmetric = box.asymmetric || {};
  1212. box.asymmetric.signer = {};
  1213. /**
  1214. * A module that holds asymmetric signature functionalities.
  1215. *
  1216. * @exports asymmetric/signer/factory
  1217. */
  1218. box.asymmetric.signer.factory = {};
  1219. var policies = {
  1220. algorithm: box.policies.asymmetric.signer.algorithm,
  1221. provider: box.policies.asymmetric.signer.provider,
  1222. hash: box.policies.asymmetric.signer.hash,
  1223. padding: box.policies.asymmetric.signer.padding,
  1224. publicExponent: box.policies.asymmetric.signer.publicExponent
  1225. };
  1226. var converters, exceptions, randomFactory;
  1227. var f = function(box) {
  1228. converters = new box.commons.utils.Converters();
  1229. exceptions = box.commons.exceptions;
  1230. randomFactory =
  1231. new box.primitives.securerandom.factory.SecureRandomFactory();
  1232. };
  1233. f.policies = {
  1234. primitives: {
  1235. secureRandom:
  1236. {provider: box.policies.asymmetric.signer.secureRandom.provider}
  1237. }
  1238. };
  1239. cryptolib('commons', 'primitives.securerandom', f);
  1240. /**
  1241. * A factory class for creating a digital signer.
  1242. *
  1243. * @class
  1244. */
  1245. box.asymmetric.signer.factory.SignerFactory = function() {};
  1246. box.asymmetric.signer.factory.SignerFactory.prototype = {
  1247. getCryptoSigner: function() {
  1248. try {
  1249. if (policies.provider === Config.asymmetric.signer.provider.FORGE) {
  1250. var secureRandom = randomFactory.getCryptoRandomBytes();
  1251. return this.getCryptoForgeSigner(secureRandom);
  1252. } else {
  1253. throw new exceptions.CryptoLibException(
  1254. 'No suitable provider for the signer was provided.');
  1255. }
  1256. } catch (error) {
  1257. throw new exceptions.CryptoLibException(
  1258. 'A CryptoSigner could not be obtained.', error);
  1259. }
  1260. },
  1261. /**
  1262. * @function
  1263. * @return {asymmetric/signer.CryptoForgeSigner}
  1264. */
  1265. getCryptoForgeSigner: function(secureRandom) {
  1266. return new CryptoForgeSigner(secureRandom);
  1267. }
  1268. };
  1269. /**
  1270. * A digital signer.
  1271. *
  1272. * @class
  1273. * @memberof asymmetric/signer
  1274. * @param secureRandom
  1275. */
  1276. function CryptoForgeSigner(secureRandom) {
  1277. this.digester = null;
  1278. this.secureRandom = secureRandom;
  1279. try {
  1280. if (policies.algorithm !== Config.asymmetric.signer.algorithm.RSA) {
  1281. throw new exceptions.CryptoLibException(
  1282. 'The given algorithm is not supported');
  1283. }
  1284. if (policies.hash === Config.asymmetric.signer.hash.SHA256) {
  1285. this.digester = forge.md.sha256.create();
  1286. } else {
  1287. var errorMessage = 'Message digester type \'' + policies.hash +
  1288. '\' not recognized by signer.';
  1289. throw new exceptions.CryptoLibException(errorMessage);
  1290. }
  1291. if (typeof(policies.padding) !== 'undefined' &&
  1292. policies.padding.PSS.name === Config.asymmetric.signer.padding.PSS.name) {
  1293. var paddingHash;
  1294. if (policies.padding.PSS.hash ===
  1295. Config.asymmetric.signer.padding.PSS.hash.SHA256) {
  1296. paddingHash = forge.md.sha256.create();
  1297. }
  1298. var paddingMgf;
  1299. if (policies.padding.PSS.mask.MGF1.name ===
  1300. Config.asymmetric.signer.padding.PSS.mask.MGF1.name &&
  1301. policies.padding.PSS.mask.MGF1.hash ===
  1302. Config.asymmetric.signer.padding.PSS.mask.MGF1.hash.SHA256) {
  1303. var mgfHash = forge.md.sha256.create();
  1304. paddingMgf = forge.mgf.mgf1.create(mgfHash);
  1305. }
  1306. this.padding = forge.pss.create({
  1307. md: paddingHash,
  1308. mgf: paddingMgf,
  1309. saltLength: policies.padding.PSS.saltLengthBytes,
  1310. prng: this.secureRandom
  1311. });
  1312. }
  1313. } catch (error) {
  1314. throw new exceptions.CryptoLibException(
  1315. 'CryptoForgeSigner could not be created.', error);
  1316. }
  1317. }
  1318. CryptoForgeSigner.prototype = {
  1319. /**
  1320. * Digitally signs some data.
  1321. *
  1322. * @function
  1323. * @param privateKeyPem
  1324. * Private key, as string in PEM format.
  1325. * @param arrayDataBase64
  1326. * Data to sign, as an array of string in Base64 encoded
  1327. * format.
  1328. * @returns signature, in Base64 encoded format.
  1329. */
  1330. sign: function(privateKeyPem, arrayDataBase64) {
  1331. try {
  1332. var privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
  1333. if (privateKey.e.toString() !== policies.publicExponent.toString()) {
  1334. throw new exceptions.CryptoLibException(
  1335. 'Private key has not been generated with the required exponent : ' +
  1336. policies.publicExponent);
  1337. }
  1338. if (!arrayDataBase64 || arrayDataBase64.length < 1) {
  1339. throw new exceptions.CryptoLibException(
  1340. 'The array of data in Base64 should contain at least one element.');
  1341. }
  1342. this.digester.start();
  1343. var dataB64;
  1344. var data;
  1345. for (var i = 0; i < arrayDataBase64.length; i++) {
  1346. dataB64 = arrayDataBase64[i];
  1347. if (dataB64 === undefined || dataB64 === null) {
  1348. throw new exceptions.CryptoLibException(
  1349. 'The input data contained an element that was not defined or empty.');
  1350. }
  1351. data = converters.base64Decode(dataB64);
  1352. this.digester.update(data);
  1353. }
  1354. var signature = privateKey.sign(this.digester, this.padding);
  1355. return converters.base64Encode(signature);
  1356. } catch (error) {
  1357. throw new exceptions.CryptoLibException(
  1358. 'Signature could not be generated.', error);
  1359. }
  1360. },
  1361. /**
  1362. * Verifies the digital signature of some data.
  1363. *
  1364. * @function
  1365. *
  1366. * @param signatureB64
  1367. * Signature, as string in Base64 encoded format.
  1368. * @param publicKeyPem
  1369. * Public key, as string in PEM format.
  1370. * @param arrayDataBase64
  1371. * Data that was signed, as an array of string in Base64
  1372. * encoded format.
  1373. *
  1374. * @returns boolean indicating whether signature verification was
  1375. * successful.
  1376. */
  1377. verify: function(signatureB64, publicKeyPem, arrayDataBase64) {
  1378. try {
  1379. var publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
  1380. if (publicKey.e.toString() !== policies.publicExponent.toString()) {
  1381. throw new exceptions.CryptoLibException(
  1382. 'Public key has not been generated with the required exponent : ' +
  1383. policies.publicExponent);
  1384. }
  1385. if (!arrayDataBase64 || arrayDataBase64.length < 1) {
  1386. throw new exceptions.CryptoLibException(
  1387. 'The array of data in Base64 should contain at least one element.');
  1388. }
  1389. this.digester.start();
  1390. var dataB64;
  1391. for (var i = 0; i < arrayDataBase64.length; i++) {
  1392. dataB64 = arrayDataBase64[i];
  1393. if (dataB64 === undefined || dataB64 === null) {
  1394. throw new exceptions.CryptoLibException(
  1395. 'The input data contained an element that was not defined or empty.');
  1396. }
  1397. var data = converters.base64Decode(dataB64);
  1398. this.digester.update(data);
  1399. }
  1400. var signature = converters.base64Decode(signatureB64);
  1401. return publicKey.verify(
  1402. this.digester.digest().getBytes(), signature, this.padding);
  1403. } catch (error) {
  1404. throw new exceptions.CryptoLibException(
  1405. 'Signature could not be verified.', error);
  1406. }
  1407. }
  1408. };
  1409. };
  1410. /*
  1411. * Copyright 2018 Scytl Secure Electronic Voting SA
  1412. *
  1413. * All rights reserved
  1414. *
  1415. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  1416. */
  1417. cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
  1418. /**
  1419. * Defines the asymmetric signers.
  1420. *
  1421. * @namespace asymmetric/xmlsigner
  1422. */
  1423. cryptolib.modules.asymmetric.xmlsigner = function(box) {
  1424. 'use strict';
  1425. box.asymmetric = box.asymmetric || {};
  1426. box.asymmetric.xmlsigner = {};
  1427. /**
  1428. * A module that holds certificates functionalities.
  1429. *
  1430. * @exports asymmetric/xmlsigner/factory
  1431. */
  1432. box.asymmetric.xmlsigner.factory = {};
  1433. var policies = {
  1434. algorithm: box.policies.asymmetric.signer.algorithm,
  1435. provider: box.policies.asymmetric.signer.provider,
  1436. hash: box.policies.asymmetric.signer.hash
  1437. };
  1438. var utils, exceptions, converters, parsers, stringUtils;
  1439. var f = function(box) {
  1440. exceptions = box.commons.exceptions;
  1441. utils = box.commons.utils;
  1442. converters = new box.commons.utils.Converters();
  1443. parsers = new utils.Parsers();
  1444. stringUtils = new utils.StringUtils();
  1445. };
  1446. cryptolib('commons', f);
  1447. /**
  1448. * A factory class for creating an XML digital signature verifier.
  1449. *
  1450. * @class
  1451. */
  1452. box.asymmetric.xmlsigner.factory.XmlSignerFactory = function() {};
  1453. box.asymmetric.xmlsigner.factory.XmlSignerFactory.prototype = {
  1454. /**
  1455. * Gets a {@link asymmetric/xmlsigner.CryptoForgeXmlSigner}.
  1456. *
  1457. * @function
  1458. * @return {asymmetric/xmlsigner.CryptoForgeXmlSigner}
  1459. */
  1460. getCryptoXmlSigner: function() {
  1461. try {
  1462. if (policies.provider === Config.asymmetric.signer.provider.FORGE) {
  1463. return new CryptoForgeXmlSigner();
  1464. } else {
  1465. throw new exceptions.CryptoLibException(
  1466. 'No suitable provider for the signer was provided.');
  1467. }
  1468. } catch (error) {
  1469. throw new exceptions.CryptoLibException(
  1470. 'A CryptoXmlSigner could not be obtained.', error);
  1471. }
  1472. }
  1473. };
  1474. /**
  1475. * Holds xml signature properties.
  1476. *
  1477. * @class
  1478. * @memberof asymmetric/xmlsigner
  1479. */
  1480. function XmlSignature(signatureNode) {
  1481. // go through all the nodes to load all relevant information
  1482. var signedInfoNode;
  1483. var signatureValueNode;
  1484. var canonicalizationMethodNode;
  1485. var signatureMethodNode;
  1486. var referenceNode;
  1487. var digestMethodNode;
  1488. var digestValueNode;
  1489. var transformsNode;
  1490. try {
  1491. signedInfoNode = new utils.XPath(signatureNode.getXml(), 'SignedInfo');
  1492. signatureValueNode =
  1493. new utils.XPath(signatureNode.getXml(), 'SignatureValue');
  1494. canonicalizationMethodNode =
  1495. new utils.XPath(signedInfoNode.getXml(), 'CanonicalizationMethod');
  1496. signatureMethodNode =
  1497. new utils.XPath(signedInfoNode.getXml(), 'SignatureMethod');
  1498. referenceNode = new utils.XPath(signedInfoNode.getXml(), 'Reference');
  1499. digestMethodNode =
  1500. new utils.XPath(referenceNode.getXml(), 'DigestMethod');
  1501. digestValueNode = new utils.XPath(referenceNode.getXml(), 'DigestValue');
  1502. transformsNode = new utils.XPath(referenceNode.getXml(), 'Transforms');
  1503. } catch (error) {
  1504. throw new exceptions.CryptoLibException(
  1505. 'Could not parse signed XML file', error);
  1506. }
  1507. // there are signatures without key, so we ignore them
  1508. var rsaKeyValueNode;
  1509. var modulusNode;
  1510. var exponentNode;
  1511. try {
  1512. rsaKeyValueNode = new utils.XPath(
  1513. signatureNode.getXml(), 'KeyInfo/KeyValue/RSAKeyValue');
  1514. modulusNode = new utils.XPath(rsaKeyValueNode.getXml(), 'Modulus');
  1515. exponentNode = new utils.XPath(rsaKeyValueNode.getXml(), 'Exponent');
  1516. } catch (error) {
  1517. // ignore if this part fails
  1518. }
  1519. // build the object structure
  1520. /** @property {object} */
  1521. this.info = {
  1522. method: signatureMethodNode.getAttribute('Algorithm'),
  1523. value: signatureValueNode.getValue(),
  1524. meta: signatureNode.getAttribute('xmlns')
  1525. };
  1526. /** @property {object} */
  1527. this.canonicalization = {
  1528. method: canonicalizationMethodNode.getAttribute('Algorithm')
  1529. };
  1530. /** @property {object} */
  1531. this.reference = {
  1532. uri: referenceNode.getAttribute('URI'),
  1533. transforms: [],
  1534. digest: {
  1535. method: digestMethodNode.getAttribute('Algorithm'),
  1536. value: digestValueNode.getValue()
  1537. }
  1538. };
  1539. /** @property {object} */
  1540. this.rsakey = {
  1541. modulus: modulusNode ? modulusNode.getValue() : '',
  1542. exponent: exponentNode ? exponentNode.getValue() : ''
  1543. };
  1544. // update the transforms references
  1545. var transforms = transformsNode.getChildren();
  1546. for (var i = 0; i < transforms.length; i++) {
  1547. if (transforms[i].nodeType === Node.ELEMENT_NODE) {
  1548. var transformNode = new utils.XPath(transforms[i]);
  1549. this.reference.transforms.push(transformNode.getAttribute('Algorithm'));
  1550. }
  1551. }
  1552. }
  1553. /**
  1554. * @class
  1555. * @memberof asymmetric/xmlsigner
  1556. */
  1557. function ExclusiveCanonicalization() {}
  1558. /**
  1559. * Sorts the attributes
  1560. *
  1561. * @function
  1562. * @param xmlNode
  1563. * xml node, as a DOM.
  1564. */
  1565. ExclusiveCanonicalization.prototype.sortAttributes = function(xmlNode) {
  1566. // gather all attributes and remove them
  1567. var list = [];
  1568. var attr;
  1569. if (xmlNode.attributes) {
  1570. for (var i = 0; i < xmlNode.attributes.length; i++) {
  1571. attr = xmlNode.attributes[i];
  1572. list.push({id: attr.name, val: xmlNode.getAttribute(attr.name)});
  1573. xmlNode.removeAttribute(attr.name);
  1574. i--;
  1575. }
  1576. }
  1577. // sort the attributes
  1578. list.sort(function(a, b) {
  1579. if (a.id < b.id) {
  1580. return -1;
  1581. }
  1582. if (a.id > b.id) {
  1583. return 1;
  1584. }
  1585. return 0;
  1586. });
  1587. // reinsert the attributes
  1588. for (var j = 0; j < list.length; j++) {
  1589. attr = list[j];
  1590. xmlNode.setAttribute(attr.id, attr.val);
  1591. }
  1592. };
  1593. /**
  1594. * Inits the process of canonicalization.
  1595. *
  1596. * @function
  1597. * @param xmlNode
  1598. * xml node, as a DOM.
  1599. *
  1600. * @return xml node processed, as DOM.
  1601. */
  1602. ExclusiveCanonicalization.prototype.process = function(xml) {
  1603. // traverse the tree through all the children
  1604. for (var i = 0; i < xml.childNodes.length; i++) {
  1605. var child = xml.childNodes[i];
  1606. if (child.nodeType === Node.ELEMENT_NODE) {
  1607. this.process(child);
  1608. }
  1609. // if are comments or other stuff, remove them
  1610. else if (child.nodeType !== Node.TEXT_NODE) {
  1611. child.parentNode.removeChild(child);
  1612. --i;
  1613. }
  1614. }
  1615. // sort the attributes
  1616. this.sortAttributes(xml);
  1617. // return the final object
  1618. return xml;
  1619. };
  1620. /**
  1621. * An xml signer.
  1622. *
  1623. * @class
  1624. * @memberof asymmetric/xmlsigner
  1625. */
  1626. function CryptoForgeXmlSigner() {}
  1627. CryptoForgeXmlSigner.prototype = {
  1628. /**
  1629. * Verifies the digital signature of a selfsigned xml.
  1630. *
  1631. * @function
  1632. * @param publicKey
  1633. * Public key, as an object.
  1634. * @param signedXml
  1635. * XML data, as a string
  1636. * @param signatureParentNode
  1637. * The node where the signature is, as a string.
  1638. *
  1639. * @returns Boolean indicating whether signature verification was
  1640. * successful.
  1641. */
  1642. verify: function(publicKey, signedXml, signatureParentNode) {
  1643. // clean the comments in the xml
  1644. signedXml = this._removeXmlStringComments(signedXml);
  1645. // loads the text to an xml
  1646. var xml = parsers.xmlFromString(signedXml);
  1647. // loads the xml signature structure to json
  1648. var signature = this._loadSignature(xml, signatureParentNode);
  1649. // check all the algorithms are the expected ones
  1650. this._verifyAlgorithmsInSignature(signature);
  1651. // check the public key is the expected one
  1652. this._verifyPublicKeyInSignature(signature, publicKey);
  1653. // check the references are well encoded
  1654. this._validateReferences(signature, signedXml);
  1655. // validates the signatures are right
  1656. this._validateSignature(signature, publicKey);
  1657. // if not exception raised, all went good
  1658. return true;
  1659. },
  1660. /**
  1661. * Gets the XML signature node from the main XML node
  1662. *
  1663. * @function
  1664. * @private
  1665. * @param xml
  1666. * XML where the signature is, as a Document Object
  1667. * @param signatureParentNode
  1668. * The node where the signature is, as a string.
  1669. *
  1670. * @returns Object with the DOM node of the signature and and the
  1671. * signature in json.
  1672. */
  1673. _loadSignature: function(xml, signatureParentNode) {
  1674. // access to the node where the signature is, and take the methods
  1675. try {
  1676. // get the signature node
  1677. var xmlNode = new utils.XPath(xml, signatureParentNode);
  1678. // create signature object to load the data from the signature
  1679. var data = new XmlSignature(xmlNode);
  1680. // return the main object
  1681. return {xmlNode: xmlNode, data: data};
  1682. } catch (error) {
  1683. throw new exceptions.CryptoLibException(
  1684. 'Could not load the signature from the XML', error);
  1685. }
  1686. },
  1687. /**
  1688. * Verifies that the method algorithms in the EML and the properties
  1689. * match.
  1690. *
  1691. * @function
  1692. * @private
  1693. * @param signature
  1694. * Signature, as a Javascript Object
  1695. */
  1696. _verifyAlgorithmsInSignature: function(signature) {
  1697. try {
  1698. if (signature.data.canonicalization.method !==
  1699. 'http://www.w3.org/2001/10/xml-exc-c14n#') {
  1700. throw new exceptions.CryptoLibException(
  1701. 'Invalid canonicalization algorithm');
  1702. }
  1703. if (!stringUtils.containsSubString(
  1704. signature.data.info.method, policies.algorithm) &&
  1705. !stringUtils.containsSubString(
  1706. signature.data.info.method, policies.hash)) {
  1707. throw new exceptions.CryptoLibException(
  1708. 'Invalid signature algorithm');
  1709. }
  1710. if (!stringUtils.containsSubString(
  1711. signature.data.reference.digest.method, policies.hash)) {
  1712. throw new exceptions.CryptoLibException('Invalid digest algorithm');
  1713. }
  1714. } catch (error) {
  1715. throw new exceptions.CryptoLibException(
  1716. 'Could not verify the data in the XML.', error);
  1717. }
  1718. },
  1719. /**
  1720. * Verifies the public key is the same than the one in the EML.
  1721. *
  1722. * @function
  1723. * @private
  1724. * @param signature
  1725. * Signature, as a Javascript Object
  1726. * @param publicKey
  1727. * Public key, as an object.
  1728. */
  1729. _verifyPublicKeyInSignature: function(signature, publicKey) {
  1730. // it has no key
  1731. if (!signature.data.rsakey.exponent || !signature.data.rsakey.modulus) {
  1732. return;
  1733. }
  1734. // if it has key, we validate it
  1735. try {
  1736. var signatureExponent =
  1737. converters.base64ToBigInteger(signature.data.rsakey.exponent);
  1738. var signatureModulus =
  1739. converters.base64ToBigInteger(signature.data.rsakey.modulus);
  1740. if (publicKey.e.compareTo(signatureExponent) !== 0 ||
  1741. publicKey.n.compareTo(signatureModulus) !== 0) {
  1742. throw new exceptions.CryptoLibException('Invalid public key');
  1743. }
  1744. } catch (error) {
  1745. throw new exceptions.CryptoLibException(
  1746. 'Could not verify the data in the XML.', error);
  1747. }
  1748. },
  1749. /**
  1750. * Verifies the references of a selfsigned xml.
  1751. *
  1752. * @function
  1753. * @private
  1754. * @param signature
  1755. * Signature, as a Javascript Object
  1756. */
  1757. _validateReferences: function(signature, xmlString) {
  1758. try {
  1759. var xmlCanonString;
  1760. // The canonicalization transformations are performed here.
  1761. // Due to differences in the behaviour of Internet Explorer,
  1762. // these transformations must be applied manually in the case
  1763. // of that browser. For all other browsers, the transformations
  1764. // are performed by applying a canonicalization algorithm.
  1765. if (parsers.isIE()) {
  1766. xmlCanonString = this._removeXmlStringHeader(xmlString);
  1767. xmlCanonString = this._removeXmlStringSelfClosingTags(xmlCanonString);
  1768. xmlCanonString = this._removeXmlStringSignature(xmlCanonString);
  1769. xmlCanonString = this._removeXmlStringFirstCharacter(xmlCanonString);
  1770. } else {
  1771. var xmlCanon = null;
  1772. // apply all transforms to the xml
  1773. for (var i = 0; i < signature.data.reference.transforms.length; i++) {
  1774. // get the algorithm name
  1775. var algorithm = signature.data.reference.transforms[i];
  1776. // consume it if it exists
  1777. if (algorithm in this._transformAlgorithmMap) {
  1778. xmlCanon = this._transformAlgorithmMap[algorithm](
  1779. signature.xmlNode.getXml());
  1780. }
  1781. }
  1782. xmlCanon = this._removeXmlHeader(xmlCanon);
  1783. xmlCanonString = parsers.xmlToString(xmlCanon, true);
  1784. }
  1785. var digester =
  1786. this._getHashMethod(signature.data.reference.digest.method);
  1787. digester.start();
  1788. digester.update(
  1789. parsers.removeCarriageReturnChars(xmlCanonString), 'utf8');
  1790. var messageDigest = digester.digest();
  1791. // check if the result is valid
  1792. var encodedMessage = forge.util.encode64(messageDigest.getBytes());
  1793. if (encodedMessage !== signature.data.reference.digest.value) {
  1794. throw new exceptions.CryptoLibException(
  1795. 'Invalid reference: \'' + encodedMessage +
  1796. '\' when was expected \'' +
  1797. signature.data.reference.digest.value + '\'');
  1798. }
  1799. } catch (error) {
  1800. throw new exceptions.CryptoLibException(
  1801. 'Could not validate references.', error);
  1802. }
  1803. },
  1804. /**
  1805. * Verifies the digital signature of a selfsigned xml.
  1806. *
  1807. * @function
  1808. * @private
  1809. * @param signature
  1810. * Signature, as a Javascript Object
  1811. * @param publicKey
  1812. * Public key, as an object.
  1813. */
  1814. _validateSignature: function(signature, publicKey) {
  1815. try {
  1816. var signedInfoNode =
  1817. new utils.XPath(signature.xmlNode.getXml(), '/SignedInfo');
  1818. var algorithm = signature.data.canonicalization.method;
  1819. var xmlCanon = null;
  1820. if (algorithm in this._transformAlgorithmMap) {
  1821. xmlCanon =
  1822. this._transformAlgorithmMap[algorithm](signedInfoNode.getXml());
  1823. }
  1824. var digester = this._getHashMethod(signature.data.info.method);
  1825. digester.start();
  1826. digester.update(parsers.xmlToString(xmlCanon, true), 'utf8');
  1827. var signatureValue = forge.util.decode64(signature.data.info.value);
  1828. var result =
  1829. publicKey.verify(digester.digest().getBytes(), signatureValue);
  1830. if (!result) {
  1831. throw new exceptions.CryptoLibException(
  1832. 'Could not validate the signature.');
  1833. }
  1834. } catch (error) {
  1835. throw new exceptions.CryptoLibException(
  1836. 'Could not validate signatures.', error);
  1837. }
  1838. },
  1839. /**
  1840. * Creates the hash method
  1841. *
  1842. * @function
  1843. * @private
  1844. * @param method
  1845. * method type, as string.
  1846. *
  1847. * @return Object, the disgester of that method.
  1848. */
  1849. _getHashMethod: function(method) {
  1850. if (stringUtils.containsSubString(method, 'sha256')) {
  1851. return forge.md.sha256.create();
  1852. }
  1853. },
  1854. /**
  1855. * Map with all tarnsform algorithms
  1856. *
  1857. * @function
  1858. * @private
  1859. */
  1860. _transformAlgorithmMap: {
  1861. /**
  1862. * Removes the signature from a signed XML
  1863. *
  1864. * @param xmlSignature
  1865. * the xml signature, as DOM.
  1866. *
  1867. * @return the XML top document, as DOM
  1868. */
  1869. 'http://www.w3.org/2000/09/xmldsig#enveloped-signature': function(
  1870. xmlSignature) {
  1871. var topElement = xmlSignature;
  1872. // get the top document
  1873. while (topElement.parentNode) {
  1874. topElement = topElement.parentNode;
  1875. }
  1876. // remove the signature from the node
  1877. xmlSignature.parentNode.removeChild(xmlSignature);
  1878. return topElement;
  1879. },
  1880. /**
  1881. * c14n the XML
  1882. *
  1883. * @param xmlNode
  1884. * the xml node, as DOM.
  1885. *
  1886. * @return the XML top document, as DOM
  1887. */
  1888. 'http://www.w3.org/2001/10/xml-exc-c14n#': function(xmlNode) {
  1889. var transform = new ExclusiveCanonicalization();
  1890. return transform.process(xmlNode);
  1891. }
  1892. },
  1893. /**
  1894. * Removes the comments in the xml
  1895. *
  1896. * @function
  1897. * @private
  1898. * @param xml
  1899. * the xml, as string.
  1900. *
  1901. * @return {string} the xml without comments
  1902. */
  1903. _removeXmlStringComments: function(xml) {
  1904. return xml.replace(/<!--[\s\S]*?-->/g, '');
  1905. },
  1906. /**
  1907. * Removes the header in the xml structure. <?xml version="1.0"
  1908. * encoding="UTF-8"?>
  1909. *
  1910. * @function
  1911. * @private
  1912. * @param {object}
  1913. * xmlDocument the xml, as DOM.
  1914. *
  1915. * @returns {object} the xml, as DOM without the header
  1916. */
  1917. _removeXmlHeader: function(xmlDocument) {
  1918. return xmlDocument.documentElement ? xmlDocument.documentElement :
  1919. xmlDocument;
  1920. },
  1921. /**
  1922. * Removes the header in the XML string.
  1923. *
  1924. * @param xmlString
  1925. * the xml, as a string.
  1926. *
  1927. * @return the xml string without the header
  1928. */
  1929. _removeXmlStringHeader: function(xmlString) {
  1930. return parsers.removeXmlHeaderFromString(xmlString);
  1931. },
  1932. /**
  1933. * Removes the signature node in the XML string.
  1934. *
  1935. * @param xmlString
  1936. * the xml, as a string.
  1937. *
  1938. * @return the xml string without the signature tag
  1939. */
  1940. _removeXmlStringSignature: function(xmlString) {
  1941. return parsers.removeXmlSignature(xmlString);
  1942. },
  1943. /**
  1944. * Converts any self-closing tags to opening and closing tags, within an
  1945. * XML string.
  1946. *
  1947. * @param xmlString
  1948. * the xml, as a string.
  1949. *
  1950. * @return the xml string with self-closing tags converted to opening
  1951. * and closing tags
  1952. */
  1953. _removeXmlStringSelfClosingTags: function(xmlString) {
  1954. return parsers.xmlRemoveSelfClosingTags(xmlString);
  1955. },
  1956. /**
  1957. * Removes the first character from an XML string if that character is
  1958. * not the expected initial character.
  1959. *
  1960. * @param xmlString
  1961. * the xml, as a string.
  1962. *
  1963. * @return the xml string with the initial character removed if it is
  1964. * not wanted
  1965. */
  1966. _removeXmlStringFirstCharacter: function(xmlString) {
  1967. if (xmlString[0] !== '<') {
  1968. return xmlString.slice(1, xmlString.length);
  1969. } else {
  1970. return xmlString;
  1971. }
  1972. }
  1973. };
  1974. };
  1975. /*
  1976. * Copyright 2018 Scytl Secure Electronic Voting SA
  1977. *
  1978. * All rights reserved
  1979. *
  1980. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  1981. */
  1982. /** @namespace certificates */
  1983. cryptolib.modules.certificates = function(box) {
  1984. 'use strict';
  1985. if (box.certificates) {
  1986. return;
  1987. }
  1988. box.certificates = {};
  1989. /**
  1990. * Provides an API that can be used to perform operations with certificates.
  1991. *
  1992. * @exports certificates/service
  1993. */
  1994. box.certificates.service = {};
  1995. var converters;
  1996. var exceptions;
  1997. cryptolib('commons', function(box) {
  1998. converters = new box.commons.utils.Converters();
  1999. exceptions = box.commons.exceptions;
  2000. });
  2001. /**
  2002. * Loads a certificate in pem format.
  2003. *
  2004. * @function
  2005. * @param {string}
  2006. * certificatePem certificate as string in PEM format.
  2007. * @returns {certificates.box.certificates.CryptoX509Certificate} the
  2008. * certificate.
  2009. */
  2010. box.certificates.service.load = function(certificatePem) {
  2011. return new box.certificates.CryptoX509Certificate(certificatePem);
  2012. };
  2013. /**
  2014. * Provides methods to access X509 certificate data.
  2015. *
  2016. * @class
  2017. * @param certificatePem
  2018. * certificate as string in PEM format.
  2019. * @memberof certificates
  2020. */
  2021. box.certificates.CryptoX509Certificate = function(certificatePem) {
  2022. /** @property {object} certificate the certificate. * */
  2023. this.certificate = forge.pki.certificateFromPem(certificatePem, true);
  2024. };
  2025. box.certificates.CryptoX509Certificate.prototype = {
  2026. /**
  2027. * Retrieves the public key of the certificate.
  2028. *
  2029. * @function
  2030. * @returns public key, as string in PEM format.
  2031. * @memberof certificates.box.certificates.CryptoX509Certificate
  2032. */
  2033. getPublicKey: function() {
  2034. var publicKey = this.certificate.publicKey;
  2035. if (publicKey !== null) {
  2036. return forge.pki.publicKeyToPem(publicKey);
  2037. } else {
  2038. throw new exceptions.CryptoLibException(
  2039. 'Could not find public key in certificate.');
  2040. }
  2041. },
  2042. /**
  2043. * Retrieves the start time of the certificate's validity.
  2044. *
  2045. * @function
  2046. * @returns start time of certificate validity, as Date object.
  2047. * @memberof certificates.box.certificates.CryptoX509Certificate
  2048. */
  2049. getNotBefore: function() {
  2050. var notBeforeField = this.certificate.validity.notBefore;
  2051. if (notBeforeField !== null) {
  2052. return notBeforeField;
  2053. } else {
  2054. throw new exceptions.CryptoLibException(
  2055. 'Could not find validity start time in certificate.');
  2056. }
  2057. },
  2058. /**
  2059. * Retrieves the end time of the certificate's validity.
  2060. *
  2061. * @function
  2062. * @returns end time of certificate validity, as Date object.
  2063. * @memberof certificates.box.certificates.CryptoX509Certificate
  2064. */
  2065. getNotAfter: function() {
  2066. var notAfterField = this.certificate.validity.notAfter;
  2067. if (notAfterField !== null) {
  2068. return notAfterField;
  2069. } else {
  2070. throw new exceptions.CryptoLibException(
  2071. 'Could not find validity end time in certificate.');
  2072. }
  2073. },
  2074. /**
  2075. * Retrieves the serial number of the certificate.
  2076. *
  2077. * @function
  2078. * @returns serial number of certificate, as hexadecimal string.
  2079. * @memberof certificates.box.certificates.CryptoX509Certificate
  2080. */
  2081. getSerialNumber: function() {
  2082. var serialNumber = this.certificate.serialNumber;
  2083. if (serialNumber !== null) {
  2084. return serialNumber;
  2085. } else {
  2086. return '';
  2087. }
  2088. },
  2089. /**
  2090. * Retrieves the issuer common name of the certificate.
  2091. *
  2092. * @function
  2093. * @returns issuer common name of certificate, as string.
  2094. * @memberof certificates.box.certificates.CryptoX509Certificate
  2095. */
  2096. getIssuerCN: function() {
  2097. var issuerCNField =
  2098. this.certificate.issuer.getField({name: 'commonName'});
  2099. if (issuerCNField !== null) {
  2100. return issuerCNField.value;
  2101. } else {
  2102. return '';
  2103. }
  2104. },
  2105. /**
  2106. * Retrieves the issuer organizational unit of the certificate.
  2107. *
  2108. * @function
  2109. * @returns issuer organizational unit of certificate, as string.
  2110. * @memberof certificates.box.certificates.CryptoX509Certificate
  2111. */
  2112. getIssuerOrgUnit: function() {
  2113. var orgUnitField = this.certificate.issuer.getField({shortName: 'OU'});
  2114. if (orgUnitField !== null) {
  2115. return orgUnitField.value;
  2116. } else {
  2117. return '';
  2118. }
  2119. },
  2120. /**
  2121. * Retrieves the issuer organization name of the certificate.
  2122. *
  2123. * @function
  2124. * @returns Issuer organization name of certificate, as string.
  2125. * @memberof certificates.box.certificates.CryptoX509Certificate
  2126. */
  2127. getIssuerOrg: function() {
  2128. var orgNameField =
  2129. this.certificate.issuer.getField({name: 'organizationName'});
  2130. if (orgNameField !== null) {
  2131. return orgNameField.value;
  2132. } else {
  2133. return '';
  2134. }
  2135. },
  2136. /**
  2137. * Retrieves the issuer locality name of the certificate.
  2138. *
  2139. * @function
  2140. * @returns Locality name of certificate, as string.
  2141. * @memberof certificates.box.certificates.CryptoX509Certificate
  2142. */
  2143. getIssuerLocality: function() {
  2144. var localityField =
  2145. this.certificate.issuer.getField({name: 'localityName'});
  2146. if (localityField !== null) {
  2147. return localityField.value;
  2148. } else {
  2149. return '';
  2150. }
  2151. },
  2152. /**
  2153. * Retrieves the issuer country name of the certificate.
  2154. *
  2155. * @function
  2156. * @returns Issuer country name of certificate, as string.
  2157. * @memberof certificates.box.certificates.CryptoX509Certificate
  2158. */
  2159. getIssuerCountry: function() {
  2160. var countryField =
  2161. this.certificate.issuer.getField({name: 'countryName'});
  2162. if (countryField !== null) {
  2163. return countryField.value;
  2164. } else {
  2165. return '';
  2166. }
  2167. },
  2168. /**
  2169. * Retrieves the subject common name of the certificate.
  2170. *
  2171. * @function
  2172. * @returns Subject common name of certificate, as string.
  2173. * @memberof certificates.box.certificates.CryptoX509Certificate
  2174. */
  2175. getSubjectCN: function() {
  2176. var subjectCNField =
  2177. this.certificate.subject.getField({name: 'commonName'});
  2178. if (subjectCNField !== null) {
  2179. return subjectCNField.value;
  2180. } else {
  2181. return '';
  2182. }
  2183. },
  2184. /**
  2185. * Retrieves the subject organizational unit of the certificate.
  2186. *
  2187. * @function
  2188. * @returns Subject organizational unit of certificate, as string.
  2189. * @memberof certificates.box.certificates.CryptoX509Certificate
  2190. */
  2191. getSubjectOrgUnit: function() {
  2192. var orgUnitField = this.certificate.subject.getField({shortName: 'OU'});
  2193. if (orgUnitField !== null) {
  2194. return orgUnitField.value;
  2195. } else {
  2196. return '';
  2197. }
  2198. },
  2199. /**
  2200. * Retrieves the subject organization name of the certificate.
  2201. *
  2202. * @function
  2203. * @return Subject organization name of certificate, as string.
  2204. * @memberof certificates.box.certificates.CryptoX509Certificate
  2205. */
  2206. getSubjectOrg: function() {
  2207. var organizationNameField =
  2208. this.certificate.subject.getField({name: 'organizationName'});
  2209. if (organizationNameField !== null) {
  2210. return organizationNameField.value;
  2211. } else {
  2212. return '';
  2213. }
  2214. },
  2215. /**
  2216. * Retrieves the subject locality name of the certificate.
  2217. *
  2218. * @function
  2219. * @returns Subject locality name of certificate, as string.
  2220. * @memberof certificates.box.certificates.CryptoX509Certificate
  2221. */
  2222. getSubjectLocality: function() {
  2223. var localityField =
  2224. this.certificate.subject.getField({name: 'localityName'});
  2225. if (localityField !== null) {
  2226. return localityField.value;
  2227. } else {
  2228. return '';
  2229. }
  2230. },
  2231. /**
  2232. * Retrieves the subject country name of the certificate.
  2233. *
  2234. * @function
  2235. * @returns Subject country name of certificate, as string.
  2236. * @memberof certificates.box.certificates.CryptoX509Certificate
  2237. */
  2238. getSubjectCountry: function() {
  2239. var countryField =
  2240. this.certificate.subject.getField({name: 'countryName'});
  2241. if (countryField !== null) {
  2242. return countryField.value;
  2243. } else {
  2244. return '';
  2245. }
  2246. },
  2247. /**
  2248. * Retrieves the key usage extension of the certificate.
  2249. *
  2250. * @function
  2251. * @return KeyUsageExtension key usage extension, as KeyUsageExtension
  2252. * object.
  2253. * @memberof certificates.box.certificates.CryptoX509Certificate
  2254. */
  2255. getKeyUsageExtension: function() {
  2256. var keyUsageExt = this.certificate.getExtension({name: 'keyUsage'});
  2257. if (keyUsageExt !== null) {
  2258. var keyUsageMap = {};
  2259. keyUsageMap.digitalSignature = keyUsageExt.digitalSignature;
  2260. keyUsageMap.nonRepudiation = keyUsageExt.nonRepudiation;
  2261. keyUsageMap.keyEncipherment = keyUsageExt.keyEncipherment;
  2262. keyUsageMap.dataEncipherment = keyUsageExt.dataEncipherment;
  2263. keyUsageMap.keyAgreement = keyUsageExt.keyAgreement;
  2264. keyUsageMap.keyCertSign = keyUsageExt.keyCertSign;
  2265. keyUsageMap.crlSign = keyUsageExt.cRLSign;
  2266. keyUsageMap.encipherOnly = keyUsageExt.encipherOnly;
  2267. keyUsageMap.decipherOnly = keyUsageExt.decipherOnly;
  2268. return new box.certificates.KeyUsageExtension(keyUsageMap);
  2269. } else {
  2270. return null;
  2271. }
  2272. },
  2273. /**
  2274. * Retrieves the basic constraints of the certificate.
  2275. *
  2276. * @function
  2277. * @returns map containing the basic constraints.
  2278. * @memberof certificates.box.certificates.CryptoX509Certificate
  2279. */
  2280. getBasicConstraints: function() {
  2281. var basicConstraints =
  2282. this.certificate.getExtension({name: 'basicConstraints'});
  2283. if (basicConstraints !== null) {
  2284. var basicConstraintsMap = {};
  2285. basicConstraintsMap.ca = basicConstraints.cA;
  2286. return basicConstraintsMap;
  2287. } else {
  2288. return null;
  2289. }
  2290. },
  2291. /**
  2292. * Retrieves the digital signature of the certificate.
  2293. *
  2294. * @function
  2295. * @returns digital signature of certificate, as string in Base64
  2296. * encoded format.
  2297. * @memberof certificates.box.certificates.CryptoX509Certificate
  2298. */
  2299. getSignature: function() {
  2300. var signature = this.certificate.signature;
  2301. if (signature !== null) {
  2302. var signatureB64 =
  2303. converters.base64Encode(signature, box.RSA_LINE_LENGTH);
  2304. if (signatureB64 !== null) {
  2305. return signatureB64;
  2306. } else {
  2307. throw new exceptions.CryptoLibException(
  2308. 'Base64 encoding of signature is null.');
  2309. }
  2310. } else {
  2311. throw new exceptions.CryptoLibException('Signature is null.');
  2312. }
  2313. },
  2314. /**
  2315. * Verifies the digital signature of the certificate provided as input,
  2316. * using this certificate's public key.
  2317. *
  2318. * @function
  2319. * @param certificatePem
  2320. * certificate whose signature is to be verified, as string
  2321. * in PEM format.
  2322. * @returns boolean indicating whether signature was verified.
  2323. * @memberof certificates.box.certificates.CryptoX509Certificate
  2324. */
  2325. verify: function(certificatePem) {
  2326. var certificate = forge.pki.certificateFromPem(certificatePem);
  2327. if (certificate !== null) {
  2328. return this.certificate.verify(certificate);
  2329. } else {
  2330. throw new exceptions.CryptoLibException('Certificate is null.');
  2331. }
  2332. },
  2333. /**
  2334. * Retrieves the certificate, in PEM format.
  2335. *
  2336. * @function
  2337. * @returns certificate, as string in PEM format
  2338. * @memberof certificates.box.certificates.CryptoX509Certificate
  2339. */
  2340. toPem: function() {
  2341. if (this.certificate !== null) {
  2342. return forge.pki.certificateToPem(
  2343. this.certificate, box.RSA_LINE_LENGTH);
  2344. } else {
  2345. throw new exceptions.CryptoLibException('Certificate is null.');
  2346. }
  2347. }
  2348. };
  2349. /**
  2350. * Container class for the key usage extension flags of a digital
  2351. * certificate.
  2352. *
  2353. * @class
  2354. * @param keyUsageMap
  2355. * map containing name-value pairs of key usage extension flags.
  2356. * @memberof certificates
  2357. */
  2358. box.certificates.KeyUsageExtension = function(keyUsageMap) {
  2359. this.keyUsageMap = keyUsageMap;
  2360. };
  2361. box.certificates.KeyUsageExtension.prototype = {
  2362. /**
  2363. * Retrieves the digital signature flag of the key usage extension.
  2364. *
  2365. * @function
  2366. * @returns boolean indicating whether digital signature flag is set.
  2367. * @memberof certificates.box.certificates.KeyUsageExtension
  2368. */
  2369. digitalSignature: function() {
  2370. return this.keyUsageMap.digitalSignature;
  2371. },
  2372. /**
  2373. * Retrieves the non-repudiation flag of the key usage extension.
  2374. *
  2375. * @function
  2376. * @return boolean indicating whether non-repudiation flag is set.
  2377. * @memberof certificates.box.certificates.KeyUsageExtension
  2378. */
  2379. nonRepudiation: function() {
  2380. return this.keyUsageMap.nonRepudiation;
  2381. },
  2382. /**
  2383. * Retrieves the key encipherment flag of the key usage extension.
  2384. *
  2385. * @function
  2386. * @returns boolean indicating whether key encipherment flag is set.
  2387. * @memberof certificates.box.certificates.KeyUsageExtension
  2388. */
  2389. keyEncipherment: function() {
  2390. return this.keyUsageMap.keyEncipherment;
  2391. },
  2392. /**
  2393. * Retrieves the data encipherment flag of the key usage extension.
  2394. *
  2395. * @function
  2396. * @returns boolean indicating whether data encipherment flag is set.
  2397. * @memberof certificates.box.certificates.KeyUsageExtension
  2398. */
  2399. dataEncipherment: function() {
  2400. return this.keyUsageMap.dataEncipherment;
  2401. },
  2402. /**
  2403. * Retrieves the key agreement flag of the key usage extension.
  2404. *
  2405. * @function
  2406. * @returns boolean indicating whether key agreement flag is set.
  2407. * @memberof certificates.box.certificates.KeyUsageExtension
  2408. */
  2409. keyAgreement: function() {
  2410. return this.keyUsageMap.keyAgreement;
  2411. },
  2412. /**
  2413. * Retrieves the key certificate sign flag of the key usage extension.
  2414. *
  2415. * @function
  2416. * @returns Boolean indicating whether key certificate sign flag is set.
  2417. * @memberof certificates.box.certificates.KeyUsageExtension
  2418. */
  2419. keyCertSign: function() {
  2420. return this.keyUsageMap.keyCertSign;
  2421. },
  2422. /**
  2423. * Retrieves the CRL sign flag of the key usage extension.
  2424. *
  2425. * @function
  2426. * @returns boolean indicating whether CRL sign flag is set.
  2427. * @memberof certificates.box.certificates.KeyUsageExtension
  2428. */
  2429. crlSign: function() {
  2430. return this.keyUsageMap.crlSign;
  2431. },
  2432. /**
  2433. * Retrieves the encipher only flag of the key usage extension.
  2434. *
  2435. * @function
  2436. * @returns boolean indicating whether encipher only flag is set.
  2437. * @memberof certificates.box.certificates.KeyUsageExtension
  2438. */
  2439. encipherOnly: function() {
  2440. return this.keyUsageMap.encipherOnly;
  2441. },
  2442. /**
  2443. * Retrieves the decipher only flag of the key usage extension.
  2444. *
  2445. * @function
  2446. * @returns boolean indicating whether decipher only flag is set.
  2447. * @memberof certificates.box.certificates.KeyUsageExtension
  2448. */
  2449. decipherOnly: function() {
  2450. return this.keyUsageMap.decipherOnly;
  2451. },
  2452. /**
  2453. * Retrieves the CA flag of the key usage extension.
  2454. *
  2455. * @function
  2456. * @return boolean indicating whether CA flag is set.
  2457. * @memberof certificates.box.certificates.KeyUsageExtension
  2458. */
  2459. ca: function() {
  2460. return this.keyUsageMap.ca;
  2461. }
  2462. };
  2463. /**
  2464. * Class that validates the content of a CryptoX509Certificate.
  2465. *
  2466. * @class
  2467. * @param validationData
  2468. * @param {string}
  2469. * validationData.subject
  2470. * @param {string}
  2471. * validationData.subject.commonName
  2472. * @param {string}
  2473. * validationData.subject.organization
  2474. * @param {string}
  2475. * validationData.subject.organizationUnit
  2476. * @param {string}
  2477. * validationData.subject.country
  2478. * @param {string}
  2479. * validationData.issuer
  2480. * @param {string}
  2481. * validationData.issuer.commonName
  2482. * @param {string}
  2483. * validationData.issuer.organization
  2484. * @param {string}
  2485. * validationData.issuer.organizationUnit
  2486. * @param {string}
  2487. * validationData.issuer.country
  2488. * @param {string}
  2489. * validationData.time
  2490. * @param {string}
  2491. * validationData.keytype CA, Sign or Encryption
  2492. * @param {string}
  2493. * validationData.caCertificatePem
  2494. * @memberof certificates
  2495. */
  2496. box.certificates.CryptoX509CertificateValidator = function(validationData) {
  2497. var parseIsoDate = function(isoDate) {
  2498. var dateChunks = isoDate.split(/\D/);
  2499. return new Date(Date.UTC(
  2500. +dateChunks[0], --dateChunks[1], +dateChunks[2], +dateChunks[5],
  2501. +dateChunks[6], +dateChunks[7], 0));
  2502. };
  2503. /**
  2504. * Validates the content of the X.509 certificate.
  2505. *
  2506. * @function
  2507. * @param certificatePem
  2508. * certificate as string in PEM format.
  2509. * @return an array containing the errors type, if any.
  2510. */
  2511. this.validate = function(x509CertificatePem) {
  2512. var cryptoX509Certificate =
  2513. new box.certificates.CryptoX509Certificate(x509CertificatePem);
  2514. var failedValidations = [];
  2515. var validateSubject = function(subject) {
  2516. if (subject.commonName !== cryptoX509Certificate.getSubjectCN() ||
  2517. subject.organization !== cryptoX509Certificate.getSubjectOrg() ||
  2518. subject.organizationUnit !==
  2519. cryptoX509Certificate.getSubjectOrgUnit() ||
  2520. subject.country !== cryptoX509Certificate.getSubjectCountry()) {
  2521. failedValidations.push('SUBJECT');
  2522. }
  2523. };
  2524. var validateIssuer = function(issuer) {
  2525. if (issuer.commonName !== cryptoX509Certificate.getIssuerCN() ||
  2526. issuer.organization !== cryptoX509Certificate.getIssuerOrg() ||
  2527. issuer.organizationUnit !==
  2528. cryptoX509Certificate.getIssuerOrgUnit() ||
  2529. issuer.country !== cryptoX509Certificate.getIssuerCountry()) {
  2530. failedValidations.push('ISSUER');
  2531. }
  2532. };
  2533. var validateTime = function(isoDate) {
  2534. var time = parseIsoDate(isoDate);
  2535. if (time.toString() === 'Invalid Date' ||
  2536. time - cryptoX509Certificate.getNotBefore() < 0 ||
  2537. time - cryptoX509Certificate.getNotAfter() > 0) {
  2538. failedValidations.push('TIME');
  2539. }
  2540. };
  2541. var areBasicConstraintsValid = function(keyType) {
  2542. var returnValue = true;
  2543. var basicConstraints = cryptoX509Certificate.getBasicConstraints();
  2544. if (keyType === 'CA' &&
  2545. (!basicConstraints || basicConstraints.ca !== true)) {
  2546. returnValue = false;
  2547. }
  2548. return returnValue;
  2549. };
  2550. var isKeyUsageValid = function(keyType) {
  2551. var returnValue = true;
  2552. var keyUsageExtension = cryptoX509Certificate.getKeyUsageExtension();
  2553. if (!keyUsageExtension) {
  2554. return false;
  2555. }
  2556. switch (keyType) {
  2557. case 'CA':
  2558. if (keyUsageExtension.keyCertSign() !== true ||
  2559. keyUsageExtension.crlSign() !== true) {
  2560. returnValue = false;
  2561. }
  2562. break;
  2563. case 'Sign':
  2564. if (keyUsageExtension.digitalSignature() !== true ||
  2565. keyUsageExtension.nonRepudiation() !== true) {
  2566. returnValue = false;
  2567. }
  2568. break;
  2569. case 'Encryption':
  2570. if (keyUsageExtension.keyEncipherment() !== true ||
  2571. keyUsageExtension.dataEncipherment() !== true) {
  2572. returnValue = false;
  2573. }
  2574. break;
  2575. default:
  2576. returnValue = false;
  2577. }
  2578. return returnValue;
  2579. };
  2580. var validateKeyType = function(keyType) {
  2581. if (!areBasicConstraintsValid(keyType) || !isKeyUsageValid(keyType)) {
  2582. failedValidations.push('KEY_TYPE');
  2583. }
  2584. };
  2585. var validateSignature = function(caCertificatePem) {
  2586. var caCryptoX509Certificate =
  2587. new box.certificates.CryptoX509Certificate(caCertificatePem);
  2588. if (caCryptoX509Certificate === null) {
  2589. failedValidations.push('SIGNATURE');
  2590. throw new exceptions.CryptoLibException('CA certificate is null.');
  2591. }
  2592. try {
  2593. if (!caCryptoX509Certificate.verify(x509CertificatePem)) {
  2594. failedValidations.push('SIGNATURE');
  2595. }
  2596. } catch (error) {
  2597. failedValidations.push('SIGNATURE');
  2598. throw new exceptions.CryptoLibException(
  2599. 'Signature verification process failed.');
  2600. }
  2601. };
  2602. if (validationData.subject) {
  2603. validateSubject(validationData.subject);
  2604. }
  2605. if (validationData.issuer) {
  2606. validateIssuer(validationData.issuer);
  2607. }
  2608. if (validationData.time) {
  2609. validateTime(validationData.time);
  2610. }
  2611. if (validationData.keyType) {
  2612. validateKeyType(validationData.keyType);
  2613. }
  2614. if (validationData.caCertificatePem) {
  2615. validateSignature(validationData.caCertificatePem);
  2616. }
  2617. return failedValidations;
  2618. };
  2619. };
  2620. /**
  2621. * Class that validates the content of a CryptoX509Certificate.
  2622. *
  2623. * @function
  2624. * @param validationData
  2625. * {json}
  2626. * @param {string}
  2627. * validationData.subject the subject data.
  2628. * @param {string}
  2629. * validationData.subject.commonName
  2630. * @param {string}
  2631. * validationData.subject.organization
  2632. * @param {string}
  2633. * validationData.subject.organizationUnit
  2634. * @param {string}
  2635. * validationData.subject.country
  2636. * @param {string}
  2637. * validationData.issuer the issuer data.
  2638. * @param {string}
  2639. * validationData.issuer.commonName
  2640. * @param {string}
  2641. * validationData.issuer.organization
  2642. * @param {string}
  2643. * validationData.issuer.organizationUnit
  2644. * @param {string}
  2645. * validationData.issuer.country
  2646. * @param {string}
  2647. * validationData.time time to be checked.
  2648. * @param {string}
  2649. * validationData.keyType CA, Sign or Encryption.
  2650. * @param {string}
  2651. * validationData.caCertificatePem
  2652. * @param certificate
  2653. * certificate as string in PEM format.
  2654. * @returns {Array} an array that contains the error types occurred, if any.
  2655. */
  2656. box.certificates.service.validateCertificate = function(
  2657. validationData, certificate) {
  2658. if (validationData === null) {
  2659. throw new exceptions.CryptoLibException('Validation data is null.');
  2660. }
  2661. if (Object.getOwnPropertyNames(validationData).length) {
  2662. throw new exceptions.CryptoLibException('Validation data is empty.');
  2663. }
  2664. if (certificate === null) {
  2665. throw new exceptions.CryptoLibException('Certificate is null.');
  2666. }
  2667. return (new box.certificates.CryptoX509CertificateValidator(validationData))
  2668. .validate(certificate);
  2669. };
  2670. /**
  2671. * Validates the certificate information provided to the constructor. The
  2672. * validation process loops through all certificates, starting with the leaf
  2673. * certificate, until it reaches the trusted certificate. For each
  2674. * certificate, except the trusted certificate, it checks that the following
  2675. * conditions hold:
  2676. * <ul>
  2677. * <li>Subject DN is that expected for given certificate.</li>
  2678. * <li>Issuer DN is same as subject DN of next certificate in chain.</li>
  2679. * <li>Key type is that expected: "signing" or "encryption" for leaf
  2680. * certificate and "CA" for rest of certificates in chain.</li>
  2681. * <li>Signature can be verified with public key of next certificate in
  2682. * chain.</li>
  2683. * <li>Starting time is earlier than ending time.</li>
  2684. * <li>Starting time is equal to or later than starting time of next
  2685. * certificate in chain.</li>
  2686. * <li>Ending time is equal to or earlier than ending time of next
  2687. * certificate in chain.</li>
  2688. * </ul>
  2689. * In addition, if a non-null value is provided to the constructor for the
  2690. * time reference, it will be checked whether this time reference is within
  2691. * the dates of validity of the leaf certificate. After the validation
  2692. * process has completed, a list of strings will be returned. If this list
  2693. * is empty, then the validation was successful. Otherwise, the list will
  2694. * contain string identifiers for each type of validation that failed.
  2695. *
  2696. * @function
  2697. * @param {json}
  2698. * chain certificate chain.
  2699. * @param {json}
  2700. * chain.leaf leaf certificate.
  2701. * @param {string}
  2702. * chain.leaf.pem X.509 certificate.
  2703. * @param {string}
  2704. * chain.leaf.keyType keyType.
  2705. * @param {string}
  2706. * chain.leaf.subject subject.
  2707. * @param {string}
  2708. * chain.leaf.time time reference (Optional). Only mandatory if
  2709. * the 'Time' validation is going to be performed.
  2710. * @param {json}
  2711. * chain.certificates chain of certificates.
  2712. * @param {Array}
  2713. * chain.certificates.pems list of X.509 Certificates as string
  2714. * in pem format. The list starts by the one closer to the root.
  2715. * @param {Array}
  2716. * chain.certificates.subjects list of subjects
  2717. * @param {Array}
  2718. * chain.root X.509 trusted Certificate.
  2719. * @returns {Array} a two dimension array where the first dimension is the
  2720. * index of the element starting by 1 -leaf certificate - and the
  2721. * second dimension holds the error types.
  2722. */
  2723. box.certificates.service.validateX509CertificateChain = function(chain) {
  2724. var validateDateRange = function(certificate, failedValidation) {
  2725. if (certificate.getNotBefore() > certificate.getNotAfter()) {
  2726. failedValidation.push('VALIDITY_PERIOD');
  2727. }
  2728. };
  2729. var validateNotBefore = function(
  2730. notBefore, previousNotBefore, failedValidation) {
  2731. if (notBefore < previousNotBefore) {
  2732. failedValidation.push('NOT_BEFORE');
  2733. }
  2734. };
  2735. var validateNotAfter = function(
  2736. notAfter, previousNotAfter, failedValidation) {
  2737. if (notAfter > previousNotAfter) {
  2738. failedValidation.push('NOT_AFTER');
  2739. }
  2740. };
  2741. var validateLeafCertificate = function(
  2742. issuer, signature, previousNotBefore, previousNotAfter) {
  2743. var validationData = {
  2744. subject: chain.leaf.subject,
  2745. issuer: issuer,
  2746. keyType: chain.leaf.keyType,
  2747. caCertificatePem: signature
  2748. };
  2749. if (chain.leaf.time) {
  2750. validationData.time = chain.leaf.time;
  2751. }
  2752. var certificateValidator =
  2753. new box.certificates.CryptoX509CertificateValidator(validationData);
  2754. var failedValidations = certificateValidator.validate(chain.leaf.pem);
  2755. var certificate =
  2756. new box.certificates.CryptoX509Certificate(chain.leaf.pem);
  2757. validateDateRange(certificate, failedValidations);
  2758. validateNotBefore(
  2759. certificate.getNotBefore(), previousNotBefore, failedValidations);
  2760. validateNotAfter(
  2761. certificate.getNotAfter(), previousNotAfter, failedValidations);
  2762. return failedValidations;
  2763. };
  2764. var rootCertificate =
  2765. new box.certificates.CryptoX509Certificate(chain.root);
  2766. var issuer = {
  2767. commonName: rootCertificate.getSubjectCN(),
  2768. organization: rootCertificate.getSubjectOrg(),
  2769. organizationUnit: rootCertificate.getSubjectOrgUnit(),
  2770. country: rootCertificate.getSubjectCountry()
  2771. };
  2772. var signature = chain.root;
  2773. var failedValidation = [];
  2774. var previousNotBefore = rootCertificate.getNotBefore();
  2775. var previousNotAfter = rootCertificate.getNotAfter();
  2776. var certificateValidator;
  2777. chain.certificates.pems.reverse();
  2778. chain.certificates.subjects.reverse();
  2779. for (var i = 0; i < chain.certificates.pems.length; i++) {
  2780. var certificate = new box.certificates.CryptoX509Certificate(
  2781. chain.certificates.pems[i]);
  2782. var validationData = {
  2783. subject: chain.certificates.subjects[i],
  2784. issuer: issuer,
  2785. keyType: 'CA',
  2786. signature: signature
  2787. };
  2788. certificateValidator =
  2789. new box.certificates.CryptoX509CertificateValidator(validationData);
  2790. failedValidation[i] =
  2791. certificateValidator.validate(chain.certificates.pems[i]);
  2792. validateDateRange(certificate, failedValidation[i]);
  2793. validateNotBefore(
  2794. certificate.getNotBefore(), previousNotBefore, failedValidation[i]);
  2795. validateNotAfter(
  2796. certificate.getNotAfter(), previousNotAfter, failedValidation[i]);
  2797. issuer = {
  2798. commonName: certificate.getSubjectCN(),
  2799. organization: certificate.getSubjectOrg(),
  2800. organizationUnit: certificate.getSubjectOrgUnit(),
  2801. country: certificate.getSubjectCountry()
  2802. };
  2803. signature = chain.certificates.pems[i];
  2804. previousNotBefore = certificate.getNotBefore();
  2805. previousNotAfter = certificate.getNotAfter();
  2806. }
  2807. failedValidation.push(validateLeafCertificate(
  2808. issuer, signature, previousNotBefore, previousNotAfter));
  2809. failedValidation.reverse();
  2810. return failedValidation;
  2811. };
  2812. /**
  2813. * Flattens failed validations to a one dimensional array to a one
  2814. * dimensional array.
  2815. *
  2816. * @function
  2817. * @param {array}
  2818. * failedValidations a two-dimensional failed validations array.
  2819. * @returns {array} a flat array in which each element contains the error
  2820. * type message piped with the index of the element, i.e.
  2821. * ERROR_<element index>.
  2822. */
  2823. box.certificates.service.flattenFailedValidations = function(
  2824. failedValidations) {
  2825. var flattenFailedValidations = Array();
  2826. for (var i = 0; i < failedValidations.length; i++) {
  2827. if (failedValidations[i] !== undefined) {
  2828. for (var j = 0; j < failedValidations[i].length; j++) {
  2829. flattenFailedValidations.push(
  2830. failedValidations[i][j].toLowerCase() + '_' + (i));
  2831. }
  2832. }
  2833. }
  2834. return flattenFailedValidations;
  2835. };
  2836. };
  2837. cryptolib.modules.certificates.service = cryptolib.modules.certificates;
  2838. /*
  2839. * Copyright 2018 Scytl Secure Electronic Voting SA
  2840. *
  2841. * All rights reserved
  2842. *
  2843. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  2844. */
  2845. cryptolib.modules.commons = cryptolib.modules.commons || {};
  2846. /**
  2847. * Defines our exception wrapper.
  2848. *
  2849. * @param message.
  2850. * The string to use in the error description.
  2851. */
  2852. cryptolib.modules.commons.exceptions = function(box) {
  2853. 'use strict';
  2854. box.commons = box.commons || {};
  2855. box.commons.exceptions = {};
  2856. box.commons.exceptions.CryptoLibException = function(
  2857. customMessage, originalMessage) {
  2858. this.customMessage = customMessage;
  2859. this.originalMessage = originalMessage;
  2860. };
  2861. box.commons.exceptions.CryptoLibException.prototype = {
  2862. /**
  2863. * Returns the exception message.
  2864. *
  2865. * @return {string} The message.
  2866. */
  2867. toString: function() {
  2868. var errorMessage = 'ERROR: ';
  2869. if (typeof this.originalMessage !== 'undefined') {
  2870. errorMessage += this.customMessage +
  2871. '. Original Error Message: ' + this.originalMessage;
  2872. } else {
  2873. errorMessage += this.customMessage;
  2874. }
  2875. return errorMessage;
  2876. }
  2877. };
  2878. };
  2879. /*
  2880. * Copyright 2018 Scytl Secure Electronic Voting SA
  2881. *
  2882. * All rights reserved
  2883. *
  2884. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  2885. */
  2886. cryptolib.modules.commons = cryptolib.modules.commons || {};
  2887. /**
  2888. * @namespace commons/mathematical
  2889. */
  2890. cryptolib.modules.commons.mathematical = function(box) {
  2891. 'use strict';
  2892. box.commons = box.commons || {};
  2893. /**
  2894. * A module the defines mathematical groups, elements, and operations that
  2895. * can be performed
  2896. *
  2897. * @exports commons/mathematical
  2898. */
  2899. box.commons.mathematical = {};
  2900. var BigInteger = box.forge.jsbn.BigInteger;
  2901. var exceptions;
  2902. var converters;
  2903. cryptolib('commons.exceptions', 'commons.utils', function(box) {
  2904. exceptions = box.commons.exceptions;
  2905. converters = new box.commons.utils.Converters();
  2906. });
  2907. /**
  2908. * Given p and Zp representing 'Integers (mod p)' group, a Zp subgroup is a
  2909. * group where the elements are a subset of elements from Zp.
  2910. *
  2911. * The order of the subgroup is q, that is the number of elements. Both Zp
  2912. * and the ZpSubgroup are finite cyclic groups, it means that all elements
  2913. * can be generated exponentiating a special group element called generator.
  2914. *
  2915. * When the p and q are related with the restriction p = 2q + 1 the subgroup
  2916. * is also defined as 'Quadratic Residue'.
  2917. *
  2918. * @class
  2919. * @param valueG
  2920. * {forge.jsbn.BigInteger} The generator of the subgroup, as a
  2921. * BigInteger. This value must be a group element different from
  2922. * one.
  2923. * @param valueP
  2924. * {forge.jsbn.BigInteger} The modulus, as a BigInteger.
  2925. * @param valueQ
  2926. * {forge.jsbn.BigInteger} The order of the subgroup, as a
  2927. * BigInteger.
  2928. *
  2929. * @throws CryptoLibException
  2930. * if 0 < q < p restriction is not accomplished
  2931. * @throws CryptoLibException
  2932. * if subgroup generator is nor between 2 and p-1
  2933. *
  2934. */
  2935. box.commons.mathematical.ZpSubgroup = function(valueG, valueP, valueQ) {
  2936. if ((typeof valueG === 'undefined') || (typeof valueP === 'undefined') ||
  2937. (typeof valueQ === 'undefined')) {
  2938. throw new exceptions.CryptoLibException(
  2939. 'The given parameters should be initialized');
  2940. }
  2941. if ((BigInteger.ONE.compareTo(valueG) >= 0) ||
  2942. (valueP.compareTo(valueG) <= 0)) {
  2943. throw new exceptions.CryptoLibException(
  2944. 'The generator should be between 2 and p-1');
  2945. }
  2946. if ((BigInteger.ZERO.compareTo(valueQ) >= 0) ||
  2947. (valueP.compareTo(valueQ) <= 0)) {
  2948. throw new exceptions.CryptoLibException(
  2949. 'The relationship between the values of the p and q parameters should be such that 0 < q < p');
  2950. }
  2951. var _p = valueP;
  2952. var _q = valueQ;
  2953. var generator = new box.commons.mathematical.ZpGroupElement(valueG, _p, _q);
  2954. var identity =
  2955. new box.commons.mathematical.ZpGroupElement(BigInteger.ONE, _p, _q);
  2956. /**
  2957. * @function
  2958. * @returns the identity element of the group.
  2959. */
  2960. this.getIdentity = function() {
  2961. return identity;
  2962. };
  2963. /**
  2964. * @function
  2965. * @returns the q parameter (the order of the group).
  2966. */
  2967. this.getQ = function() {
  2968. return _q;
  2969. };
  2970. /**
  2971. * @function
  2972. * @returns the p parameter (the modulus of the group).
  2973. */
  2974. this.getP = function() {
  2975. return _p;
  2976. };
  2977. /**
  2978. * @function
  2979. * @returns {box.commons.mathematical.ZpGroupElement} the generator
  2980. * element of the group.
  2981. */
  2982. this.getGenerator = function() {
  2983. return generator;
  2984. };
  2985. };
  2986. box.commons.mathematical.ZpSubgroup.prototype = {
  2987. /**
  2988. * Checks whether a given element is a member of this MathematicalGroup.
  2989. *
  2990. * An element is a member of the group if:
  2991. * <ul>
  2992. * <li><code>element</code> has an integer value between
  2993. * <code>1</code> and <code>p-1</code>:
  2994. * <code>(0 < element < p)</code></li>
  2995. * <li><code>element<sup>q</sup> mod p = 1</code></li>
  2996. * </ul>
  2997. *
  2998. * @function
  2999. * @param element
  3000. * {ZpGroupElement} the element whose group membership should
  3001. * be checked.
  3002. * @returns true if the given element is member of the group, otherwise
  3003. * false.
  3004. */
  3005. isGroupMember: function(element) {
  3006. if (typeof element !== 'undefined' &&
  3007. element.getP().equals(this.getP())) {
  3008. var modPow = element.getElementValue().modPow(this.getQ(), this.getP());
  3009. return BigInteger.ONE.equals(modPow);
  3010. } else {
  3011. return false;
  3012. }
  3013. },
  3014. /**
  3015. * Check if this group is equal to the received group.
  3016. *
  3017. * @function
  3018. * @param group
  3019. * {ZpSubgroup} the group which should be checked against
  3020. * this group for equality.
  3021. * @returns true if the given group has the same <code>q</code>, the
  3022. * same <code>p</code>, and the same <code>generator</code>.
  3023. */
  3024. equals: function(group) {
  3025. if (typeof group !== 'undefined' &&
  3026. group.getGenerator().equals(this.getGenerator()) &&
  3027. group.getQ().equals(this.getQ()) &&
  3028. group.getP().equals(this.getP())) {
  3029. return true;
  3030. } else {
  3031. return false;
  3032. }
  3033. },
  3034. /**
  3035. * Check if this group is a quadratic residue group, which is defined
  3036. * such that p = 2q + 1.
  3037. *
  3038. * @function
  3039. * @returns true if the given group is a quadratic residue group.
  3040. */
  3041. isQuadraticResidueGroup: function() {
  3042. return this.getP().equals(
  3043. new BigInteger('2').multiply(this.getQ()).add(BigInteger.ONE));
  3044. },
  3045. /**
  3046. * Displays a string representation of this mathematical group JSON.
  3047. * <p>
  3048. * Note: in order to permit interoperability between libraries, this
  3049. * representation should match the equivalent representation in Java.
  3050. *
  3051. * @function
  3052. * @returns a string representation of this mathematical group JSON.
  3053. */
  3054. stringify: function() {
  3055. return JSON.stringify({
  3056. zpSubgroup: {
  3057. p: converters.base64FromBigInteger(this.getP()),
  3058. q: converters.base64FromBigInteger(this.getQ()),
  3059. g: converters.base64FromBigInteger(
  3060. this.getGenerator().getElementValue())
  3061. }
  3062. });
  3063. }
  3064. };
  3065. /**
  3066. * Class representing elements of a Zp group.
  3067. *
  3068. * <p>
  3069. * Note: This constructor does not check whether the given value is a valid
  3070. * member of the subgroup. To check subgroup membership the function
  3071. * <code>zpSubgroup.isGroupMember(groupElement)</code> can be called,
  3072. * however this is a computationally expensive operation.
  3073. *
  3074. * @class
  3075. * @param value
  3076. * {forge.jsbn.BigInteger} Value of the element (not null). The
  3077. * value must be between <code>[1..p-1]</code>
  3078. * @param groupP
  3079. * {forge.jsbn.BigInteger} The p parameter, as a BigInteger.
  3080. * @param groupQ
  3081. * {forge.jsbn.BigInteger} The q parameter, as a BigInteger.
  3082. * @throws CryptoLibException
  3083. * if there are any problems with the inputs.
  3084. */
  3085. box.commons.mathematical.ZpGroupElement = function(value, groupP, groupQ) {
  3086. if ((typeof value === 'undefined')) {
  3087. throw new exceptions.CryptoLibException(
  3088. 'The received value is not the expected object');
  3089. }
  3090. if ((BigInteger.ZERO.compareTo(value) >= 0) ||
  3091. (groupP.compareTo(value) <= 0)) {
  3092. throw new exceptions.CryptoLibException(
  3093. 'The value of the element should be between 1 and p-1. P: ' + groupP +
  3094. ', value: ' + value);
  3095. }
  3096. if ((BigInteger.ZERO.compareTo(groupQ) >= 0) ||
  3097. (groupP.compareTo(groupQ) <= 0)) {
  3098. throw new exceptions.CryptoLibException(
  3099. 'The relationship between the values of the p and q parameters should hold that 0 < q < p');
  3100. }
  3101. var v = value;
  3102. var p = groupP;
  3103. var q = groupQ;
  3104. /**
  3105. * Performs a basic check to verify if this element belongs to the same
  3106. * group as <code>element</code> by checking if the p and q parameters
  3107. * of both are equal.
  3108. * <p>
  3109. * Note: this function does NOT perform the mathematical operation
  3110. * needed to actually confirm that a value is an element of a group,
  3111. * which involves modular exponentiation and is very computationally
  3112. * costly. Instead, this function simply examines the p and q parameters
  3113. * that are stored within both elements.
  3114. *
  3115. * @function
  3116. * @param element
  3117. * {ZpGroupElement} element to by multiplied with this
  3118. * element.
  3119. * @throws CryptoLibException
  3120. * if the p and q parameters of the group that the received
  3121. * element belongs to are not equal to the p and q
  3122. * parameters of this element.
  3123. */
  3124. this._validateReceivedElementIsFromSameGroup = function(element) {
  3125. if (typeof element === 'undefined') {
  3126. throw new exceptions.CryptoLibException(
  3127. 'The received value is not the expected object');
  3128. }
  3129. if ((!this.getP().equals(element.getP())) ||
  3130. (!this.getQ().equals(element.getQ()))) {
  3131. throw new exceptions.CryptoLibException(
  3132. 'Operations can only be performed on group elements which are members of the same Zp subgroup');
  3133. }
  3134. };
  3135. /**
  3136. * Performs a basic check to verify if this element belongs to the same
  3137. * group as <code>exponent</code> by checking if the p and q
  3138. * parameters of both are equal.
  3139. * <p>
  3140. * Note: this function does NOT perform the mathematical operation
  3141. * needed to actually confirm that an exponent belongs to a particular
  3142. * group, which would involve confirming the following:
  3143. * <p>
  3144. * <code>0 >= exponent value <= p-1</code>
  3145. *
  3146. * @function
  3147. * @param exponent
  3148. * {Exponent} element to by multiplied with this element.
  3149. * @throws CryptoLibException
  3150. * if p and q parameters of the group that the received
  3151. * element belongs to are not equal to the p and q
  3152. * parameters of this element.
  3153. */
  3154. this._validateReceivedExponent = function(exponent) {
  3155. if (typeof exponent === 'undefined') {
  3156. throw new exceptions.CryptoLibException(
  3157. 'The received value is not the expected object');
  3158. }
  3159. if (!this.getQ().equals(exponent.getQ())) {
  3160. throw new exceptions.CryptoLibException(
  3161. 'The exponent should have the same q as this Zp group element');
  3162. }
  3163. };
  3164. /**
  3165. * @function
  3166. * @returns The value of this element.
  3167. */
  3168. this.getElementValue = function() {
  3169. return v;
  3170. };
  3171. /**
  3172. * @function
  3173. * @returns The p parameter of the mathematical group to which this
  3174. * element belongs.
  3175. */
  3176. this.getP = function() {
  3177. return p;
  3178. };
  3179. /**
  3180. * @function
  3181. * @returns The q parameter of the mathematical group to which this
  3182. * element belongs.
  3183. */
  3184. this.getQ = function() {
  3185. return q;
  3186. };
  3187. };
  3188. box.commons.mathematical.ZpGroupElement.prototype = {
  3189. /**
  3190. * Multiple this element by the received element. The operation is
  3191. * performed mod p. Performs a basic check to confirm that this element
  3192. * and the received element belong to the same group.
  3193. *
  3194. * @function
  3195. * @param element
  3196. * {ZpGroupElement} element to by multiplied with this
  3197. * element.
  3198. * @returns <code>(this * element) mod p</code>, as a ZpGroupElement.
  3199. * @throws CryptoLibException
  3200. * if the p and q parameters of the group that the received
  3201. * element belongs to are not equal to the p and q
  3202. * parameters of this element.
  3203. */
  3204. multiply: function(element) {
  3205. this._validateReceivedElementIsFromSameGroup(element);
  3206. var result = this.getElementValue()
  3207. .multiply(element.getElementValue())
  3208. .mod(this.getP());
  3209. return new box.commons.mathematical.ZpGroupElement(
  3210. result, this.getP(), this.getQ());
  3211. },
  3212. /**
  3213. * Exponentiate this element to the received exponent.
  3214. *
  3215. * @function
  3216. * @param exponent
  3217. * {Exponent} the exponent used to raise the value of the
  3218. * group element.
  3219. * @returns <code>(this<sup>exponent</sup>) mod p</code>, as a
  3220. * ZpGroupElement.
  3221. * @throws CryptoLibException
  3222. * if the p and q parameters of the group that the received
  3223. * exponent belongs to are not equal to the p and q
  3224. * parameters of this element.
  3225. */
  3226. exponentiate: function(exponent) {
  3227. this._validateReceivedExponent(exponent);
  3228. var result =
  3229. this.getElementValue().modPow(exponent.getValue(), this.getP());
  3230. return new box.commons.mathematical.ZpGroupElement(
  3231. result, this.getP(), this.getQ());
  3232. },
  3233. /**
  3234. * Get the inverse of this element, mod p.
  3235. *
  3236. * @function
  3237. * @returns the inverse of this element mod p, as a ZpGroupElement.
  3238. */
  3239. invert: function() {
  3240. var result = this.getElementValue().modInverse(this.getP());
  3241. return new box.commons.mathematical.ZpGroupElement(
  3242. result, this.getP(), this.getQ());
  3243. },
  3244. /**
  3245. * Check if this element is equal to the received element.
  3246. * <p>
  3247. * Elements are considered equal if:
  3248. * <ul>
  3249. * <li>They have the same value.</li>
  3250. * <li>They belong to the same group (which is confirmed here by
  3251. * checking if their p and q parameters are equal).</li>
  3252. * </ul>
  3253. *
  3254. * @function
  3255. * @param element
  3256. * {ZpGroupElement} the element which should be checked
  3257. * against this element for equality.
  3258. * @returns true if the given group element has the same <code>v</code>,
  3259. * the same <code>p</code> and the same <code>q</code>.
  3260. */
  3261. equals: function(element) {
  3262. if (typeof element !== 'undefined' &&
  3263. element.getElementValue().equals(this.getElementValue()) &&
  3264. element.getP().equals(this.getP()) &&
  3265. element.getQ().equals(this.getQ())) {
  3266. return true;
  3267. } else {
  3268. return false;
  3269. }
  3270. },
  3271. /**
  3272. * Displays a string representation of this Zp group element JSON.
  3273. * <p>
  3274. * Note: in order to permit interoperability between libraries, this
  3275. * representation should match the equivalent representation in Java.
  3276. *
  3277. * @function
  3278. * @returns a string representation of Zp group element JSON.
  3279. */
  3280. stringify: function() {
  3281. return JSON.stringify({
  3282. zpGroupElement: {
  3283. p: converters.base64FromBigInteger(this.getP()),
  3284. q: converters.base64FromBigInteger(this.getQ()),
  3285. value: converters.base64FromBigInteger(this.getElementValue())
  3286. }
  3287. });
  3288. }
  3289. };
  3290. /**
  3291. * Represents an exponent for a particular mathematical group.
  3292. * <p>
  3293. * The value of an exponent must be within the range [0..q-1]. If the
  3294. * received value is not within this range, then the value that will be
  3295. * assigned to the created Exponent will be calculated as follows:
  3296. * <p>
  3297. * <code>value = value mod q</code>
  3298. *
  3299. * @class
  3300. *
  3301. * @param q
  3302. * {forge.jsbn.BigInteger} the order of the mathematical group
  3303. * for which this is an exponent.
  3304. * @param exponentValue
  3305. * {forge.jsbn.BigInteger} the value of the exponent.
  3306. * @throws CryptoLibException
  3307. * if there are any problems with the inputs.
  3308. */
  3309. box.commons.mathematical.Exponent = function(valueQ, exponentValue) {
  3310. if (valueQ === 'undefined' || valueQ.compareTo(BigInteger.ZERO) === 0) {
  3311. throw new exceptions.CryptoLibException(
  3312. 'Q (the order of the group) cannot be null or zero');
  3313. }
  3314. var _q = valueQ;
  3315. /**
  3316. * Gets the value to set for this Exponent. This value has to be a
  3317. * number between <code>0</code> and <code>q-1</code> (inclusive),
  3318. * so if it is less than <code>0</code> or greater than
  3319. * <code>q-1</code>, then <code>mod q</code> has to be applied.
  3320. *
  3321. * @function
  3322. * @param {forge.jsbn.BigInteger}
  3323. * exponentValue the value of the exponent.
  3324. * @returns the value to set to this exponent.
  3325. */
  3326. function getExponent(exponentValue) {
  3327. if ((_q.compareTo(exponentValue) > 0) &&
  3328. (BigInteger.ZERO.compareTo(exponentValue) <= 0)) {
  3329. return exponentValue;
  3330. } else {
  3331. return exponentValue.mod(_q);
  3332. }
  3333. }
  3334. var _value = getExponent(exponentValue);
  3335. /**
  3336. * Checks if this exponent and the received exponent belong to the same
  3337. * group.
  3338. *
  3339. * @function
  3340. * @param exponent
  3341. * {Exponent} the exponent which should be checked to see if
  3342. * it belongs to the same group as this exponent.
  3343. * @throws CryptoLibException
  3344. * if the received exponent is undefined or does not belong
  3345. * to the same group as this exponent.
  3346. */
  3347. this._confirmSameGroup = function(exponent) {
  3348. if (typeof exponent === 'undefined') {
  3349. throw new exceptions.CryptoLibException(
  3350. 'The received exponent is not the expected object');
  3351. }
  3352. if (!_q.equals(exponent.getQ())) {
  3353. throw new exceptions.CryptoLibException(
  3354. 'Operations may only be performed with exponents of the same mathematical group order');
  3355. }
  3356. };
  3357. /**
  3358. * @function
  3359. * @returns The numeric value of the exponent.
  3360. */
  3361. this.getValue = function() {
  3362. return _value;
  3363. };
  3364. /**
  3365. * @function
  3366. * @returns The numeric value of the exponent.
  3367. */
  3368. this.getQ = function() {
  3369. return _q;
  3370. };
  3371. };
  3372. box.commons.mathematical.Exponent.prototype = {
  3373. /**
  3374. * Returns an Exponent whose value is:
  3375. * <p>
  3376. * <code>(this + exponent) mod q</code>
  3377. *
  3378. * @param exponent
  3379. * {Exponent} the exponent to be added to this exponent.
  3380. * @returns <code>(this + exponent) mod q</code>
  3381. */
  3382. add: function(exponent) {
  3383. this._confirmSameGroup(exponent);
  3384. var result = this.getValue().add(exponent.getValue()).mod(this.getQ());
  3385. return new box.commons.mathematical.Exponent(this.getQ(), result);
  3386. },
  3387. /**
  3388. * Returns an Exponent whose value is:
  3389. * <p>
  3390. * <code>(this - exponent) mod q</code>
  3391. *
  3392. * @param exponent
  3393. * {Exponent} the exponent to be subtracted from this
  3394. * exponent.
  3395. * @returns <code>(this - exponent) mod q</code>
  3396. */
  3397. subtract: function(exponent) {
  3398. this._confirmSameGroup(exponent);
  3399. var result =
  3400. this.getValue().subtract(exponent.getValue()).mod(this.getQ());
  3401. return new box.commons.mathematical.Exponent(this.getQ(), result);
  3402. },
  3403. /**
  3404. * Returns an Exponent whose value is:
  3405. * <p>
  3406. * <code>(this * exponent) mod q</code>
  3407. *
  3408. * @param exponent
  3409. * {Exponent} the exponent to be multiplied with this
  3410. * exponent.
  3411. * @returns <code>(this * exponent) mod q</code>
  3412. */
  3413. multiply: function(exponent) {
  3414. this._confirmSameGroup(exponent);
  3415. var result =
  3416. this.getValue().multiply(exponent.getValue()).mod(this.getQ());
  3417. return new box.commons.mathematical.Exponent(this.getQ(), result);
  3418. },
  3419. /**
  3420. * Returns an Exponent whose value is <code>(-this) mod q</code>
  3421. *
  3422. * @returns <code>(-this mod q)</code>
  3423. */
  3424. negate: function() {
  3425. return new box.commons.mathematical.Exponent(
  3426. this.getQ(), this.getValue().negate().mod(this.getQ()));
  3427. },
  3428. /**
  3429. * Check if this exponent is equal to the received exponent.
  3430. * <p>
  3431. * Elements are considered equal if:
  3432. * <ul>
  3433. * <li>They have the same value.</li>
  3434. * <li>They belong to the groups with the same order.</li>
  3435. * </ul>
  3436. *
  3437. * @param {Exponent}
  3438. * exponent the exponent to be checked against this exponent
  3439. * for equality.
  3440. * @returns true if the given exponent has the same <code>value</code>
  3441. * and belongs to the same <code>group</code> as this
  3442. * exponent.
  3443. */
  3444. equals: function(exponent) {
  3445. if (exponent.getValue().equals(this.getValue()) &&
  3446. exponent.getQ().equals(this.getQ())) {
  3447. return true;
  3448. } else {
  3449. return false;
  3450. }
  3451. },
  3452. /**
  3453. * Displays a string representation of the exponent JSON.
  3454. * <p>
  3455. * Note: in order to permit interoperability between libraries, this
  3456. * representation should match the equivalent representation in Java.
  3457. *
  3458. * @function
  3459. * @returns a string representation of the exponent JSON.
  3460. */
  3461. stringify: function() {
  3462. return JSON.stringify({
  3463. exponent: {
  3464. q: converters.base64FromBigInteger(this.getQ()),
  3465. value: converters.base64FromBigInteger(this.getValue())
  3466. }
  3467. });
  3468. }
  3469. };
  3470. /**
  3471. * Provides utility functionality for working with mathematical groups.
  3472. *
  3473. * @class groupUtils
  3474. * @memberof commons/mathematical
  3475. */
  3476. box.commons.mathematical.groupUtils = (function() {
  3477. /**
  3478. * Deserializes a Zp Subgroup string representation to a ZpSubgroup
  3479. * object.
  3480. *
  3481. * @function
  3482. * @memberof commons/mathematical.groupUtils
  3483. * @param groupJson
  3484. * {JSON} a JSON representation of a Zp subgroup.
  3485. * @returns a new ZpSubgroup, created from the received string.
  3486. */
  3487. function deserializeGroup(groupJson) {
  3488. var parsed = JSON.parse(groupJson);
  3489. var p = converters.base64ToBigInteger(parsed.zpSubgroup.p);
  3490. var q = converters.base64ToBigInteger(parsed.zpSubgroup.q);
  3491. var g = converters.base64ToBigInteger(parsed.zpSubgroup.g);
  3492. return new box.commons.mathematical.ZpSubgroup(g, p, q);
  3493. }
  3494. /**
  3495. * Deserializes a Zp Subgroup element string to a ZpGroupElement object.
  3496. *
  3497. * @function
  3498. * @memberof commons/mathematical.groupUtils
  3499. * @param groupElementJson
  3500. * {JSON} a JSON representation of a Zp Subgroup element
  3501. * element.
  3502. * @returns a new ZpGroupElement, created from the received string.
  3503. */
  3504. function deserializeGroupElement(groupElementJson) {
  3505. var parsed = JSON.parse(groupElementJson);
  3506. var value = converters.base64ToBigInteger(parsed.zpGroupElement.value);
  3507. var p = converters.base64ToBigInteger(parsed.zpGroupElement.p);
  3508. var q = converters.base64ToBigInteger(parsed.zpGroupElement.q);
  3509. return new box.commons.mathematical.ZpGroupElement(value, p, q);
  3510. }
  3511. /**
  3512. * Deserializes an exponent string to an Exponent object.
  3513. *
  3514. * @function
  3515. * @memberof commons/mathematical.groupUtils
  3516. * @param exponentJson
  3517. * {JSON} a JSON representation of an exponent.
  3518. * @returns a new Exponent, created from the received string.
  3519. */
  3520. function deserializeExponent(exponentJson) {
  3521. var parsed = JSON.parse(exponentJson);
  3522. var q = converters.base64ToBigInteger(parsed.exponent.q);
  3523. var value = converters.base64ToBigInteger(parsed.exponent.value);
  3524. return new box.commons.mathematical.Exponent(q, value);
  3525. }
  3526. /**
  3527. * Compress a list of group elements.
  3528. * <P>
  3529. * Note: an exception will be thrown if an array is received which
  3530. * contains any elements that are not elements of the mathematical
  3531. * group.
  3532. *
  3533. * @function
  3534. * @memberof commons/mathematical.groupUtils
  3535. * @param group
  3536. * {ZpSubgroup} the mathematical group.
  3537. * @param elementsToBeCompressedArray
  3538. * {object} the array of group elements to be compressed.
  3539. * @returns the result of the compression process, as a group element.
  3540. * @throws CryptoLibException
  3541. * if there are any problems with the inputs.
  3542. */
  3543. function compressGroupElements(group, elementsToBeCompressedArray) {
  3544. validateArray(elementsToBeCompressedArray);
  3545. validateGroup(group);
  3546. var elem = elementsToBeCompressedArray[0];
  3547. for (var i = 1; i < elementsToBeCompressedArray.length; i++) {
  3548. elem = elem.multiply(elementsToBeCompressedArray[i]);
  3549. }
  3550. return elem;
  3551. }
  3552. /**
  3553. * Compress a list of exponents.
  3554. * <P>
  3555. * Note: an exception will be thrown if an array is received which
  3556. * contains any exponents that are not exponents of the mathematical
  3557. * group.
  3558. *
  3559. * @function
  3560. * @memberof commons/mathematical.groupUtils
  3561. * @param group
  3562. * {ZpSubgroup} the mathematical group
  3563. * @param exponentsToBeCompressedArray
  3564. * {object} the array of exponents to be compressed
  3565. * @returns the result of the compression process, as an exponent.
  3566. * @throws CryptoLibException
  3567. * if there are any problems with the inputs.
  3568. */
  3569. function compressExponents(group, exponentsToBeCompressedArray) {
  3570. validateArray(exponentsToBeCompressedArray);
  3571. validateGroup(group);
  3572. validateExponents(group.getQ(), exponentsToBeCompressedArray);
  3573. var elem = exponentsToBeCompressedArray[0];
  3574. for (var i = 1; i < exponentsToBeCompressedArray.length; i++) {
  3575. elem = elem.add(exponentsToBeCompressedArray[i]);
  3576. }
  3577. return elem;
  3578. }
  3579. /**
  3580. * Builds a new array of elements from the input array, where the final
  3581. * elements from the input array are compressed into a simple element.
  3582. *
  3583. * @function
  3584. * @memberof commons/mathematical.groupUtils
  3585. * @param group
  3586. * {ZpSubgroup} the mathematical group that this compressor
  3587. * operates on.
  3588. * @param inputArray
  3589. * {object} the input array of group elements.
  3590. * @param numElementsRequiredInNewList
  3591. * {number} the number of elements that should be in the
  3592. * output array.
  3593. * @returns a new array of group elements.
  3594. * @throws CryptoLibException
  3595. * if there are any problems with the inputs.
  3596. */
  3597. function buildListWithCompressedFinalElement(
  3598. group, inputArray, numElementsRequiredInNewList) {
  3599. validateArray(inputArray);
  3600. validateGroup(group);
  3601. if (numElementsRequiredInNewList < 1) {
  3602. throw new exceptions.CryptoLibException(
  3603. 'The number of elements in the output list must be at least 1');
  3604. }
  3605. var offset = numElementsRequiredInNewList - 1;
  3606. var outputArray = inputArray.slice(0, offset);
  3607. var lastElement = compressGroupElements(
  3608. group, inputArray.slice(offset, inputArray.length));
  3609. outputArray.push(lastElement);
  3610. return outputArray;
  3611. }
  3612. /**
  3613. * Builds a new array of exponents from the input array, where the final
  3614. * exponents from the input array are compressed into a simple
  3615. * exponents.
  3616. *
  3617. * @function
  3618. * @memberof commons/mathematical.groupUtils
  3619. * @param group
  3620. * {ZpSubgroup} the mathematical group that this compressor
  3621. * operates on.
  3622. * @param inputArray
  3623. * {object} the input array of exponents.
  3624. * @param numExponentsRequiredInNewList
  3625. * {number} the number of exponents that should be in the
  3626. * output array.
  3627. * @returns a new array of group elements.
  3628. * @throws CryptoLibException
  3629. * if there are any problems with the inputs.
  3630. */
  3631. function buildListWithCompressedFinalExponent(
  3632. group, inputArray, numExponentsRequiredInNewList) {
  3633. validateArray(inputArray);
  3634. validateGroup(group);
  3635. if (numExponentsRequiredInNewList < 1) {
  3636. throw new exceptions.CryptoLibException(
  3637. 'The number of exponents in the output list must be at least 1');
  3638. }
  3639. var offset = numExponentsRequiredInNewList - 1;
  3640. var outputArray = inputArray.slice(0, offset);
  3641. var lastExponent =
  3642. compressExponents(group, inputArray.slice(offset, inputArray.length));
  3643. outputArray.push(lastExponent);
  3644. return outputArray;
  3645. }
  3646. /**
  3647. * Given two arrays of group elements, this method produces a new list
  3648. * of group elements that represents the two input lists combined.
  3649. * <P>
  3650. * The two arrays must only contain values that are elements of the
  3651. * mathematical group that this divider operates on. If either array
  3652. * contains any element that is not a group element then an exception
  3653. * will be thrown.
  3654. *
  3655. * @function
  3656. * @memberof commons/mathematical.groupUtils
  3657. * @param arrayElements1
  3658. * {object} an input array of Zp group elements.
  3659. * @param arrayElements2
  3660. * {object} an input array of Zp group elements.
  3661. * @returns a new list of group elements.
  3662. * @throws CryptoLibException
  3663. * if there are any problems with the inputs.
  3664. */
  3665. function divide(arrayElements1, arrayElements2) {
  3666. validateArray(arrayElements1);
  3667. validateArray(arrayElements2);
  3668. if (arrayElements1.length !== arrayElements2.length) {
  3669. throw new exceptions.CryptoLibException(
  3670. 'Both arrays should have the same length');
  3671. }
  3672. var newList = [];
  3673. var newElement;
  3674. for (var i = 0; i < arrayElements1.length; i++) {
  3675. newElement = arrayElements1[i].multiply(arrayElements2[i].invert());
  3676. newList.push(newElement);
  3677. }
  3678. return newList;
  3679. }
  3680. /**
  3681. * Given an array of group elements and one exponent, this method
  3682. * produces a new list of group elements that represents the
  3683. * exponentiation of the group elements to the exponent.
  3684. * <P>
  3685. * The array must contain values that are elements of the mathematical
  3686. * group that this exponentiation activity operates on. If the array
  3687. * contains any element that is not a group element then an exception
  3688. * will be thrown.
  3689. *
  3690. * @function
  3691. * @memberof commons/mathematical.groupUtils
  3692. * @param {array} arrayElements
  3693. * an input array of Zp group elements.
  3694. * @param {object} exponent
  3695. * An Exponent.
  3696. * @param {object} group
  3697. * The mathematical group that all of the elements in
  3698. * arrayElements belong to.
  3699. * @param {boolean} validateElements An Exponent.
  3700. * @return A new list of group elements.
  3701. *
  3702. */
  3703. function exponentiateArrays(
  3704. arrayElements, exponent, group, validateElements) {
  3705. validateArray(arrayElements);
  3706. validateExponent(exponent);
  3707. validateGroup(group);
  3708. // If requested, validate all elements prior to any operations.
  3709. if (typeof validateElements !== 'undefined' && validateElements) {
  3710. for (var j = 0; j < arrayElements.length; j++) {
  3711. if (!group.isGroupMember(arrayElements[j])) {
  3712. throw new exceptions.CryptoLibException(
  3713. 'The element does not belong to the group');
  3714. }
  3715. }
  3716. }
  3717. var newList = [];
  3718. var newElement;
  3719. for (var i = 0; i < arrayElements.length; i++) {
  3720. newElement = arrayElements[i].exponentiate(exponent);
  3721. newList.push(newElement);
  3722. }
  3723. return newList;
  3724. }
  3725. /**
  3726. * Returns a new random exponent for the received mathematical group.
  3727. * <P>
  3728. * The value of the created exponent will be between <code>0</code>
  3729. * and q-1.
  3730. *
  3731. * @function
  3732. * @memberof commons/mathematical.groupUtils
  3733. * @param group
  3734. * {ZpSubgroup} the mathematical group.
  3735. * @param cryptoRandomInteger
  3736. * {CryptoScytlRandomInteger} the source of randomness.
  3737. * @param {boolean}
  3738. * useShortExponent true if a short exponent is to be
  3739. * generated. Default value is false.
  3740. * @returns a new random exponent.
  3741. * @throws CryptoLibException
  3742. * if there are any problems with the inputs.
  3743. */
  3744. function generateRandomExponent(
  3745. group, cryptoRandomInteger, useShortExponent) {
  3746. validateGroup(group);
  3747. if (typeof cryptoRandomInteger === 'undefined') {
  3748. throw new exceptions.CryptoLibException(
  3749. 'The given parameters should be initialized');
  3750. }
  3751. var _useShortExponent = true;
  3752. if (!useShortExponent) {
  3753. _useShortExponent = false;
  3754. }
  3755. var q = group.getQ();
  3756. var qBitLength = q.bitLength();
  3757. var randomExponentLength;
  3758. if (_useShortExponent) {
  3759. if (qBitLength < box.SHORT_EXPONENT_BIT_LENGTH) {
  3760. throw new exceptions.CryptoLibException(
  3761. 'Zp subgroup order bit length must be greater than or equal to short exponent bit length : ' +
  3762. box.SHORT_EXPONENT_BIT_LENGTH + '; Found ' + qBitLength);
  3763. }
  3764. randomExponentLength = box.SHORT_EXPONENT_BIT_LENGTH;
  3765. } else {
  3766. randomExponentLength = qBitLength;
  3767. }
  3768. var randomExponentValue;
  3769. var randomExponentFound = false;
  3770. while (!randomExponentFound) {
  3771. randomExponentValue =
  3772. cryptoRandomInteger.nextRandomByBits(randomExponentLength);
  3773. if (randomExponentValue.compareTo(q) < 0) {
  3774. randomExponentFound = true;
  3775. }
  3776. }
  3777. return new box.commons.mathematical.Exponent(q, randomExponentValue);
  3778. }
  3779. /**
  3780. * Returns a group element symmetric key which is obtained by
  3781. * exponentiating the generator of a given mathematical group to a
  3782. * random exponent <code>k</code>.
  3783. *
  3784. * @function
  3785. * @memberof commons/mathematical.groupUtils
  3786. * @param group
  3787. * {ZpSubgroup} the mathematical group.
  3788. * @param cryptoRandomInteger
  3789. * {CryptoScytlRandomInteger} the source of randomness.
  3790. * @returns the secret key, as a group element.
  3791. * @throws CryptoLibException
  3792. * if there are any problems with the inputs.
  3793. */
  3794. function generateGroupElementSecretKey(group, cryptoRandomInteger) {
  3795. var exponent = generateRandomExponent(group, cryptoRandomInteger);
  3796. var groupElementSecretKey = group.getGenerator().exponentiate(exponent);
  3797. return groupElementSecretKey;
  3798. }
  3799. /**
  3800. * Build a ZpSubgroup from the p and g parameters.
  3801. * <P>
  3802. * NOTE: This method builds a particular type of mathematical group with
  3803. * property that:
  3804. * <P>
  3805. * P = (Q * 2) + 1
  3806. * <P>
  3807. * This property holds for all groups generated using this method, but
  3808. * this property does not hold for all mathematical groups.
  3809. *
  3810. * @function
  3811. * @memberof commons/mathematical.groupUtils
  3812. * @param p
  3813. * {forge.jsbn.BigInteger} the p parameter of the group.
  3814. * @param g
  3815. * {forge.jsbn.BigInteger} the generator of the group.
  3816. * @returns the generated ZpSubgroup.
  3817. * @throws CryptoLibException
  3818. * if there are any problems with the inputs.
  3819. */
  3820. function buildZpSubgroupFromPAndG(p, g) {
  3821. validateBuildFromPAndGInputs(p, g);
  3822. var q = p.subtract(BigInteger.ONE).divide(new BigInteger('2'));
  3823. return new box.commons.mathematical.ZpSubgroup(g, p, q);
  3824. }
  3825. /**
  3826. * Build a random ZpSubgroup whose p parameter will have the specified
  3827. * bit length. The certainty that both p and q are both prime is
  3828. * specified by certainty.
  3829. * <P>
  3830. * NOTE: This method builds a particular type of Zp subgroup with
  3831. * property that:
  3832. * <P>
  3833. * p = (q * 2) + 1
  3834. * <P>
  3835. * This property holds for all mathematical groups generated using this
  3836. * method, but this property does not hold for all mathematical groups.
  3837. * <P>
  3838. * Note: the minimum bit length of the p parameter that is permitted by
  3839. * this method is 2. If a bit length less than 2 is requested then a
  3840. * CryptoLibException will be thrown.
  3841. *
  3842. * @function
  3843. * @memberof commons/mathematical.groupUtils
  3844. * @param bitLengthOfP
  3845. * {number} the bit length that the p parameter of the
  3846. * generated group should be.
  3847. * @param cryptoRandomInteger
  3848. * {CryptoScytlRandomInteger} an instance of
  3849. * CryptoRandomInteger that can be used as a source of random
  3850. * integers.
  3851. * @param certainty
  3852. * {number} the required level of certainty that the q
  3853. * parameter of the generated group is prime.
  3854. * @returns the generated ZpSubgroup.
  3855. * @throws CryptoLibException
  3856. * if there are any problems with the inputs.
  3857. */
  3858. function buildRandomZpSubgroupFromLengthOfP(
  3859. bitLengthOfP, cryptoRandomBytes, certainty) {
  3860. validateBuildFromLengthPInputs(
  3861. bitLengthOfP, cryptoRandomBytes, certainty);
  3862. var p, q;
  3863. var twoBI = new BigInteger('2');
  3864. var randomGroupFound = false;
  3865. var options = {prng: cryptoRandomBytes};
  3866. var callback = function(err, num) {
  3867. if (err) {
  3868. throw new exceptions.CryptoLibException(
  3869. 'Error while generating prime ' + err);
  3870. }
  3871. p = num;
  3872. q = num.subtract(BigInteger.ONE).divide(twoBI);
  3873. };
  3874. while (!randomGroupFound) {
  3875. forge.prime.generateProbablePrime(bitLengthOfP, options, callback);
  3876. if (q.isProbablePrime(certainty)) {
  3877. randomGroupFound = true;
  3878. }
  3879. }
  3880. var generator = findSmallestGenerator(p, q);
  3881. return new box.commons.mathematical.ZpSubgroup(generator, p, q);
  3882. }
  3883. /**
  3884. * Given an input array containing possible group members, this method
  3885. * cycles through that array, checking if each element is a group
  3886. * member. This method attempts to find the specified number of group
  3887. * members. Once that number has been found, the method will return a
  3888. * new array containing the specified number of group members.
  3889. * <p>
  3890. * If the required number of group members are not found in the input
  3891. * array then a CryptoLibException will be thrown.
  3892. *
  3893. * @function
  3894. * @memberof commons/mathematical.groupUtils
  3895. * @param possibleGroupMembersArray
  3896. * {object} an array containing possible group members.
  3897. * @param group
  3898. * {ZpSubgroup} the Zp subgroup for which the specified
  3899. * number of group members are required.
  3900. * @param numMembersRequired
  3901. * {number} the number of group members of the specified
  3902. * group that should be added to the output list.
  3903. * @returns a new array containing the specified number of group
  3904. * elements, which have been read from the input array.
  3905. * @throws CryptoLibException
  3906. * if there are any problems with the inputs.
  3907. */
  3908. function extractNumberOfGroupMembersFromListOfPossibleMembers(
  3909. possibleGroupMembersArray, group, numMembersRequired) {
  3910. validateExtractFromListInputs(
  3911. possibleGroupMembersArray, group, numMembersRequired);
  3912. var outputArray = [];
  3913. var membersFound = 0;
  3914. var candidate;
  3915. for (var i = 0; i < possibleGroupMembersArray.length; i++) {
  3916. candidate = new box.commons.mathematical.ZpGroupElement(
  3917. possibleGroupMembersArray[i], group.getP(), group.getQ());
  3918. if (group.isGroupMember(candidate)) {
  3919. outputArray.push(candidate);
  3920. membersFound++;
  3921. }
  3922. if (membersFound === numMembersRequired) {
  3923. return outputArray;
  3924. }
  3925. }
  3926. if (membersFound !== numMembersRequired) {
  3927. throw new exceptions.CryptoLibException(
  3928. 'Error - did not find the required number of group members in the given list. The required number of was ' +
  3929. numMembersRequired + ', number of members found was ' +
  3930. membersFound);
  3931. }
  3932. }
  3933. /**
  3934. * Find the smallest generator of a mathematical group.
  3935. * <p>
  3936. * Note: starts with a candidate generator value (two is the initial
  3937. * candidate generator value), and checks if the candidate generator is
  3938. * a group memeber. If that candidate is a group memeber then return
  3939. * that value, else increment the candidate by one and again check if
  3940. * the candidate is a group member. Continue this process until the
  3941. * candidate value is less than the parameter p.
  3942. *
  3943. * @function
  3944. * @memberof commons/mathematical.groupUtils
  3945. * @params p {number} the p parameter of the group.
  3946. * @params q {number} the q parameter of the group.
  3947. * @throws CryptoLibException
  3948. */
  3949. function findSmallestGenerator(p, q) {
  3950. var g = new BigInteger('2');
  3951. var generatorFound = false;
  3952. while ((!generatorFound) && (g.compareTo(p) < 0)) {
  3953. if (g.modPow(q, p).equals(BigInteger.ONE)) {
  3954. generatorFound = true;
  3955. } else {
  3956. g = g.add(BigInteger.ONE);
  3957. }
  3958. }
  3959. if (!generatorFound) {
  3960. throw new exceptions.CryptoLibException(
  3961. 'Failed to find a generator, p was: ' + p + ', q was: ' + q);
  3962. }
  3963. return g;
  3964. }
  3965. /**
  3966. * Validates a group.
  3967. *
  3968. * @function
  3969. * @memberof commons/mathematical.groupUtils
  3970. * @params group {ZpSubgroup} the group to be validated.
  3971. * @throws CryptoLibException
  3972. * if the received group is undefined.
  3973. */
  3974. function validateGroup(group) {
  3975. if (typeof group === 'undefined' || null === group) {
  3976. throw new exceptions.CryptoLibException(
  3977. 'The given group should be initialized');
  3978. }
  3979. }
  3980. function validateExponent(exponent) {
  3981. if (typeof exponent === 'undefined') {
  3982. throw new exceptions.CryptoLibException(
  3983. 'The given exponent should be initialized');
  3984. }
  3985. }
  3986. /**
  3987. * Validates that an array is initialized and non-empty.
  3988. *
  3989. * @function
  3990. * @memberof commons/mathematical.groupUtils
  3991. * @params inputArray {object} an array to be validated.
  3992. * @throws CryptoLibException
  3993. * if the received array is not initialized or is empty.
  3994. */
  3995. function validateArray(inputArray) {
  3996. if (typeof inputArray === 'undefined') {
  3997. throw new exceptions.CryptoLibException(
  3998. 'The given array should be initialized');
  3999. }
  4000. if (!(inputArray instanceof Array)) {
  4001. throw new exceptions.CryptoLibException(
  4002. 'The given array are not from the expected type');
  4003. }
  4004. if (inputArray.length < 1) {
  4005. throw new exceptions.CryptoLibException(
  4006. 'The given array cannot be empty');
  4007. }
  4008. }
  4009. /**
  4010. * Performs a very basic validation on the received inputs.
  4011. *
  4012. * @function
  4013. * @memberof commons/mathematical.groupUtils
  4014. * @params p {object} the first parameter.
  4015. * @params g {object} the second parameter.
  4016. * @throws CryptoLibException
  4017. * if either (or both) inputs are undefined.
  4018. */
  4019. function validateBuildFromPAndGInputs(p, g) {
  4020. if ((typeof p === 'undefined') || (typeof g === 'undefined')) {
  4021. throw new exceptions.CryptoLibException('p or g are incorrect');
  4022. }
  4023. }
  4024. /**
  4025. * Performs a some basic validations on the received inputs.
  4026. *
  4027. * @function
  4028. * @memberof commons/mathematical.groupUtils
  4029. * @params bitLengthOfP {number} bit length of p parameter.
  4030. * @params cryptoRandomBytes {CryptoScytlRandomBytes} a secure source of
  4031. * random bytes.
  4032. * @params certainty {number} a certainty level.
  4033. * @throws CryptoLibException
  4034. * if any of the inputs fail any of the validations.
  4035. */
  4036. function validateBuildFromLengthPInputs(
  4037. bitLengthOfP, cryptoRandomBytes, certainty) {
  4038. if (bitLengthOfP < 2) {
  4039. throw new exceptions.CryptoLibException(
  4040. 'The bit length should be higher');
  4041. }
  4042. if (typeof cryptoRandomBytes === 'undefined') {
  4043. throw new exceptions.CryptoLibException(
  4044. 'The random generator should be initialized');
  4045. }
  4046. if (certainty < box.MINIMUM_PRIME_CERTAINTY_LEVEL) {
  4047. throw new exceptions.CryptoLibException('Certainty should be higher');
  4048. }
  4049. }
  4050. /**
  4051. * Performs some basic validations on the received inputs.
  4052. *
  4053. * @function
  4054. * @memberof commons/mathematical.groupUtils
  4055. * @params inputArray {object} an array.
  4056. * @params group {ZpSubgroup} a Zp subgroup.
  4057. * @params numMembersRequired {number} an integer value.
  4058. * @throws CryptoLibException
  4059. * if any of the inputs fail any of the validations.
  4060. */
  4061. function validateExtractFromListInputs(
  4062. inputArray, group, numMembersRequired) {
  4063. validateArray(inputArray);
  4064. validateGroup(group);
  4065. if (typeof numMembersRequired === 'undefined') {
  4066. throw new exceptions.CryptoLibException(
  4067. 'The given objects should be initialized');
  4068. }
  4069. if (typeof numMembersRequired !== 'number') {
  4070. throw new exceptions.CryptoLibException(
  4071. 'The given objects are not from the expected type');
  4072. }
  4073. if (numMembersRequired < 1 || numMembersRequired > inputArray.length) {
  4074. throw new exceptions.CryptoLibException(
  4075. 'The given number of required elements cannot be higher than the number of elements of the array');
  4076. }
  4077. }
  4078. /**
  4079. * Validates that all of the exponents in the received list are
  4080. * exponents are members of the received group, by checking if the
  4081. * groups that they contain are equal.
  4082. *
  4083. * @function
  4084. * @memberof commons/mathematical.groupUtils
  4085. * @params group {ZpSubgroup} a Zp subgroup.
  4086. * @params exponents {object} a list of exponents.
  4087. */
  4088. function validateExponents(q, exponents) {
  4089. for (var i = 0; i < exponents.length; i++) {
  4090. if (!exponents[i].getQ().equals(q)) {
  4091. throw new exceptions.CryptoLibException(
  4092. 'The list of exponents contained an exponent which does not belong to the group with the same order.');
  4093. }
  4094. }
  4095. }
  4096. return {
  4097. buildZpSubgroupFromPAndG: buildZpSubgroupFromPAndG,
  4098. buildRandomZpSubgroupFromLengthOfP: buildRandomZpSubgroupFromLengthOfP,
  4099. extractNumberOfGroupMembersFromListOfPossibleMembers:
  4100. extractNumberOfGroupMembersFromListOfPossibleMembers,
  4101. generateRandomExponent: generateRandomExponent,
  4102. generateGroupElementSecretKey: generateGroupElementSecretKey,
  4103. compressGroupElements: compressGroupElements,
  4104. buildListWithCompressedFinalElement: buildListWithCompressedFinalElement,
  4105. deserializeGroup: deserializeGroup,
  4106. deserializeGroupElement: deserializeGroupElement,
  4107. deserializeExponent: deserializeExponent,
  4108. compressExponents: compressExponents,
  4109. buildListWithCompressedFinalExponent:
  4110. buildListWithCompressedFinalExponent,
  4111. divide: divide,
  4112. exponentiateArrays: exponentiateArrays
  4113. };
  4114. })();
  4115. };
  4116. /*
  4117. * Copyright 2018 Scytl Secure Electronic Voting SA
  4118. *
  4119. * All rights reserved
  4120. *
  4121. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  4122. */
  4123. cryptolib.modules.commons = cryptolib.modules.commons || {};
  4124. /** namespace commons/utils */
  4125. cryptolib.modules.commons.utils = function(box) {
  4126. 'use strict';
  4127. box.commons = box.commons || {};
  4128. /**
  4129. * A module that holds utility functionalities.
  4130. *
  4131. * @exports commons/utils
  4132. */
  4133. box.commons.utils = {};
  4134. var exceptions;
  4135. cryptolib('commons.exceptions', function(box) {
  4136. exceptions = box.commons.exceptions;
  4137. });
  4138. /**
  4139. * Defines some useful functions for data manipulation and type conversion.
  4140. *
  4141. * @class
  4142. */
  4143. box.commons.utils.Converters = function() {};
  4144. box.commons.utils.Converters.prototype = {
  4145. /**
  4146. * Base64 encodes some data.
  4147. *
  4148. * @function
  4149. * @param {string}
  4150. * data data to Base64 encode.
  4151. * @param {number}
  4152. * lineLength line length of encoding (No line breaks if not
  4153. * specified).
  4154. * @returns {string} base64 encoded data.
  4155. */
  4156. base64Encode: function(data, lineLength) {
  4157. if (lineLength === undefined || lineLength === null) {
  4158. return forge.util.encode64(data);
  4159. } else {
  4160. return forge.util.encode64(data, lineLength);
  4161. }
  4162. },
  4163. /**
  4164. * Base64 decodes some data.
  4165. *
  4166. * @function
  4167. * @param {string}
  4168. * dataB64 data to Base64 decode.
  4169. * @returns {string} base64 decoded data.
  4170. */
  4171. base64Decode: function(dataB64) {
  4172. return forge.util.decode64(dataB64);
  4173. },
  4174. /**
  4175. * Converts a string to a collection of bytes.
  4176. *
  4177. * @function
  4178. * @param {string}
  4179. * str string to convert to collection of bytes.
  4180. * @returns collection of bytes from string.
  4181. */
  4182. bytesFromString: function(str) {
  4183. var bytes = [];
  4184. for (var i = 0; i < str.length; i++) {
  4185. bytes.push(str.charCodeAt(i));
  4186. }
  4187. return bytes;
  4188. },
  4189. /**
  4190. * Converts a collection of bytes to a string.
  4191. *
  4192. * @function
  4193. * @param {string}
  4194. * bytes collection of bytes to convert to string.
  4195. * @return {string} string from collection of bytes.
  4196. */
  4197. bytesToString: function(bytes) {
  4198. var string = '';
  4199. for (var i = 0; i < bytes.length; i++) {
  4200. string += String.fromCharCode(bytes[i]);
  4201. }
  4202. return string;
  4203. },
  4204. /**
  4205. * Converts a string to a hexadecimal string.
  4206. *
  4207. * @function
  4208. * @param {string}
  4209. * str String to convert.
  4210. * @returns string string in hexadecimal format.
  4211. */
  4212. hexFromString: function(str) {
  4213. return forge.util.bytesToHex(str);
  4214. },
  4215. /**
  4216. * Converts a hexadecimal string to a string.
  4217. *
  4218. * @function
  4219. * @param {string}
  4220. * hexStr hexadecimal string to convert.
  4221. * @returns {string} String from conversion.
  4222. */
  4223. hexToString: function(hexStr) {
  4224. return forge.util.hexToBytes(hexStr);
  4225. },
  4226. /**
  4227. * Converts a BigInteger object to a base64 string.
  4228. *
  4229. * @function
  4230. * @param {object}
  4231. * bigInteger forge.jsbn.BigInteger to convert.
  4232. * @returns {string} base64 string from conversion.
  4233. */
  4234. base64FromBigInteger: function(bigInteger) {
  4235. var array = new Uint8Array(bigInteger.toByteArray());
  4236. return box.forge.util.binary.base64.encode(array);
  4237. },
  4238. /**
  4239. * Converts a base64 string to a BigInteger object.
  4240. *
  4241. * @function
  4242. * @param {string}
  4243. * base64Str base64 string to convert.
  4244. * @returns {object} forge.jsbn.BigInteger from conversion.
  4245. */
  4246. base64ToBigInteger: function(base64Str) {
  4247. var buffer = this.base64Decode(base64Str);
  4248. var hex = this.hexFromString(buffer);
  4249. return new forge.jsbn.BigInteger(hex, 16);
  4250. }
  4251. };
  4252. /**
  4253. * Defines a set of bit operator utilities.
  4254. *
  4255. * @class
  4256. */
  4257. box.commons.utils.BitOperators = function() {};
  4258. box.commons.utils.BitOperators.prototype = {
  4259. /**
  4260. * Bit-wise concatenates some data to some existing data.
  4261. *
  4262. * @function
  4263. * @param {string}
  4264. * data1 existing data, as string.
  4265. * @param {string}
  4266. * data2 data to concatenate, as string.
  4267. * @returns {string} bit-wise concatenation of data, as string.
  4268. */
  4269. concatenate: function(data1, data2) {
  4270. try {
  4271. var converters = new box.commons.utils.Converters();
  4272. var data1Bytes = converters.bytesFromString(data1);
  4273. var data2Bytes = converters.bytesFromString(data2);
  4274. var concatDataBytes = data1Bytes.concat(data2Bytes);
  4275. return converters.bytesToString(concatDataBytes);
  4276. } catch (error) {
  4277. throw new exceptions.CryptoLibException(
  4278. 'Data could not be bit-wise concatenated.', error);
  4279. }
  4280. },
  4281. /**
  4282. * Unpacks a data subset from a bitwise concatenation of data.
  4283. *
  4284. * @function
  4285. * @param {string}
  4286. * concatData bit-wise concatenation of data, as string.
  4287. * @param {number}
  4288. * offset offset of data subset in concatenation.
  4289. * @param {number}
  4290. * size size of data subset.
  4291. * @returns {string} data subset, as string.
  4292. */
  4293. extract: function(concatData, offset, size) {
  4294. try {
  4295. var converters = new box.commons.utils.Converters();
  4296. var concatDataBytes = converters.bytesFromString(concatData);
  4297. var dataSubsetBytes = concatDataBytes.slice(offset, size);
  4298. return converters.bytesToString(dataSubsetBytes);
  4299. } catch (error) {
  4300. throw new exceptions.CryptoLibException(
  4301. 'Data could not be bit-wise extracted.', error);
  4302. }
  4303. }
  4304. };
  4305. /**
  4306. * Defines a set of time utilities.
  4307. *
  4308. * @class
  4309. */
  4310. box.commons.utils.TimeUtils = function() {};
  4311. box.commons.utils.TimeUtils.prototype = {
  4312. /**
  4313. * Generates a time stamp in Unix time, i.e. the number of seconds that
  4314. * have elapsed since 00:00:00 Coordinated Universal Time (UTC), 1
  4315. * January 1970.
  4316. *
  4317. * @function
  4318. * @returns {number} time stamp in seconds, as integer.
  4319. */
  4320. unixTimeStamp: function() {
  4321. try {
  4322. return Math.round(new Date().getTime() / 1000);
  4323. } catch (error) {
  4324. throw new exceptions.CryptoLibException(
  4325. 'Could not generate Unix timestamp.', error);
  4326. }
  4327. },
  4328. /**
  4329. * Generates a time stamp in Unix time, i.e. the number of seconds that
  4330. * have elapsed since 00:00:00 Coordinated Universal Time (UTC), 1
  4331. * January 1970. The value is returned as a floating point number.
  4332. *
  4333. * @function
  4334. * @returns {number} time stamp in seconds, as floating point number.
  4335. */
  4336. unixTimeStampFloat: function() {
  4337. try {
  4338. return new Date().getTime() / 1000;
  4339. } catch (error) {
  4340. throw new exceptions.CryptoLibException(
  4341. 'Could not generate Unix timestamp.', error);
  4342. }
  4343. }
  4344. };
  4345. /**
  4346. * Defines a set of xpath utilities.
  4347. *
  4348. * @class
  4349. * @param {string}
  4350. * path path in XPathForm notation Eg.
  4351. * <form><name>test</name></form> to '/form/name'
  4352. */
  4353. box.commons.utils.XPath = function(xml, path) {
  4354. this.path = path;
  4355. this.node = xml;
  4356. var pathTree = path ? path.split('/') : [];
  4357. for (var i = 0; i < pathTree.length; i++) {
  4358. if (pathTree[i] && this.node) {
  4359. var found = false;
  4360. for (var j = 0; j < this.node.childNodes.length; j++) {
  4361. var child = this.node.childNodes[j];
  4362. // we found the node
  4363. if (child.nodeType === Node.ELEMENT_NODE &&
  4364. child.tagName.toLowerCase() === pathTree[i].toLowerCase()) {
  4365. this.node = child;
  4366. found = true;
  4367. break;
  4368. }
  4369. }
  4370. // invalid xpath
  4371. if (!found) {
  4372. this.node = null;
  4373. throw new exceptions.CryptoLibException('Invalid xpath for: ' + path);
  4374. }
  4375. }
  4376. }
  4377. };
  4378. box.commons.utils.XPath.prototype = {
  4379. /**
  4380. * Gets the value of a node. For example <node>value</node> returns
  4381. * value.
  4382. *
  4383. * @function
  4384. * @returns {string} the value, as string.
  4385. */
  4386. getValue: function() {
  4387. return this.node ? this.node.childNodes[0].nodeValue : '';
  4388. },
  4389. /**
  4390. * Returns the value of an attribute of a node. For example <node
  4391. * attr="attr value">node value</node> returns "attr value".
  4392. *
  4393. * @function
  4394. * @param {object}
  4395. * attribute attribute to get the value.
  4396. * @returns attribute value, as string.
  4397. */
  4398. getAttribute: function(attribute) {
  4399. return this.node ? this.node.getAttribute(attribute) : '';
  4400. },
  4401. /**
  4402. * Gets the node itself-
  4403. *
  4404. * @function
  4405. * @returns {object} xml document, as a DOM object.
  4406. */
  4407. getXml: function() {
  4408. return this.node;
  4409. },
  4410. /**
  4411. * Gets an array of child nodes
  4412. *
  4413. * @function
  4414. * @returns {object} xml document array with all children as DOM
  4415. * objects.
  4416. */
  4417. getChildren: function() {
  4418. return this.node ? this.node.childNodes : '';
  4419. }
  4420. };
  4421. /**
  4422. * Defines a set of string utilities.
  4423. *
  4424. * @class
  4425. */
  4426. box.commons.utils.StringUtils = function() {
  4427. };
  4428. box.commons.utils.StringUtils.prototype = {
  4429. /**
  4430. * Check if a string is within another string
  4431. *
  4432. * @function
  4433. * @param {string}
  4434. * main text
  4435. * @param {string}
  4436. * substring substring to search in the main text
  4437. * @param caseSensitive
  4438. * boolean, case sensitive the search
  4439. *
  4440. * @returns {boolean} boolean, true if found
  4441. */
  4442. containsSubString: function(string, substring, caseSensitive) {
  4443. var main = string, sub = substring;
  4444. if (!caseSensitive) {
  4445. main = main.toLowerCase();
  4446. sub = sub.toLowerCase();
  4447. }
  4448. return main.indexOf(sub) > -1;
  4449. }
  4450. };
  4451. /**
  4452. * Defines a set of parser utilities.
  4453. *
  4454. * @class
  4455. */
  4456. box.commons.utils.Parsers = function() {};
  4457. box.commons.utils.Parsers.prototype = {
  4458. /**
  4459. * Converts a string to an XML document.
  4460. *
  4461. * @function
  4462. * @param {string}
  4463. * str String to convert.
  4464. * @returns {string} XML document, as string.
  4465. */
  4466. xmlFromString: function(str) {
  4467. if (this.isIE()) {
  4468. // Remove null terminating character if exists
  4469. var strNoNull = this.removeNullTerminatingChar(str);
  4470. var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM');
  4471. xmlDoc.async = false;
  4472. xmlDoc.loadXML(strNoNull);
  4473. return xmlDoc;
  4474. } else if (typeof window.DOMParser !== 'undefined') {
  4475. return (new window.DOMParser()).parseFromString(str, 'text/xml');
  4476. } else {
  4477. throw new exceptions.CryptoLibException(
  4478. 'XML string could not be parsed.');
  4479. }
  4480. },
  4481. /**
  4482. * Converts an XML document to a string.
  4483. *
  4484. * @fuction
  4485. * @param {string}
  4486. * xmlDoc xml document to convert, as string.
  4487. * @param {boolean}
  4488. * removeSelfClosingTags removes self closing tags to
  4489. * explicit tags. Example: <tag/> to <tag></tag>
  4490. * @returns {string} string from conversion.
  4491. */
  4492. xmlToString: function(xmlDoc, removeSelfClosingTags) {
  4493. var result = this.xmlToStringIeCompatible(xmlDoc);
  4494. if (removeSelfClosingTags) {
  4495. result = this.xmlRemoveSelfClosingTags(result);
  4496. }
  4497. return result;
  4498. },
  4499. xmlRemoveSelfClosingTags: function(data) {
  4500. var split = data.split('/>');
  4501. var newXml = '';
  4502. for (var i = 0; i < split.length - 1; i++) {
  4503. var edsplit = split[i].split('<');
  4504. newXml +=
  4505. split[i] + '></' + edsplit[edsplit.length - 1].split(' ')[0] + '>';
  4506. }
  4507. return newXml + split[split.length - 1];
  4508. },
  4509. xmlToStringIeCompatible: function(xmlNode) {
  4510. if (this.isIE()) {
  4511. return xmlNode.xml;
  4512. } else if (typeof window.XMLSerializer !== 'undefined') {
  4513. return (new window.XMLSerializer()).serializeToString(xmlNode);
  4514. } else {
  4515. throw new exceptions.CryptoLibException(
  4516. 'Error while tring to construct XML from String.');
  4517. }
  4518. },
  4519. /**
  4520. * Removes all newline characters from some data.
  4521. *
  4522. * @function
  4523. * @param {string}
  4524. * data data from which to remove all newline characters, as
  4525. * string.
  4526. * @returns {string} data with all newline characters removed, as
  4527. * string.
  4528. */
  4529. removeNewLineChars: function(data) {
  4530. return data.replace(/(\r\n|\n|\r)/gm, '');
  4531. },
  4532. /**
  4533. * Removes all carriage return characters from some data.
  4534. *
  4535. * @param data
  4536. * Data from which to remove all carriage return characters,
  4537. * as string.
  4538. * @return Data with all carriage return characters removed, as string.
  4539. */
  4540. removeCarriageReturnChars: function(data) {
  4541. return data.replace(/(\r)/gm, '');
  4542. },
  4543. /**
  4544. * Removes the null terminating character from some data.
  4545. *
  4546. * @function
  4547. * @param {string}
  4548. * data Data from which to remove the null terminating
  4549. * character, as string.
  4550. * @returns {string} data with null terminating character removed, as
  4551. * string.
  4552. */
  4553. removeNullTerminatingChar: function(data) {
  4554. return data.replace(/\x00+$/, '');
  4555. },
  4556. /**
  4557. * Removes the XML header from a string representing an XML.
  4558. *
  4559. * @param data
  4560. * The XML string from which to remove the XML header.
  4561. * @return XML string with the XML header removed.
  4562. */
  4563. removeXmlHeaderFromString: function(data) {
  4564. return data.replace('<?xml version="1.0" encoding="UTF-8"?>', '');
  4565. },
  4566. /**
  4567. * Removes the signature node from a string representing an XML.
  4568. *
  4569. * @param data
  4570. * The XML string from which to remove the signature node.
  4571. * @return XML string with the signature node removed.
  4572. */
  4573. removeXmlSignature: function(data) {
  4574. return data.replace(/<Signature[\s\S]*?Signature>/g, '');
  4575. },
  4576. /**
  4577. * Detects if the client agent is Microsoft Internet Explorer. This has
  4578. * been tested to work with Internet Explorer 9, 10 and 11. If this
  4579. * software is to be used on other versions, then it should be checked
  4580. * if those versions are supported by this function and if they are not
  4581. * then this function should be updated.
  4582. */
  4583. isIE: function() {
  4584. var ua = window.navigator.userAgent;
  4585. var msie = ua.indexOf('MSIE ');
  4586. if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
  4587. return true;
  4588. } else {
  4589. return false;
  4590. }
  4591. }
  4592. };
  4593. /**
  4594. * Defines a set of connectors.
  4595. *
  4596. * @class
  4597. */
  4598. box.commons.utils.Connectors = function() {};
  4599. box.commons.utils.Connectors.prototype = {
  4600. /**
  4601. * Posts a request message to a destination via HTTP.
  4602. *
  4603. * @function
  4604. * @param {string}
  4605. * request request message to post, as string.
  4606. * @param {string}
  4607. * url url of request destination, as string.
  4608. * @param {boolean}
  4609. * isAsynch boolean indicating whether the post is
  4610. * asynchronous.
  4611. * @return {string} response retrieved from request destination, as
  4612. * string.
  4613. */
  4614. postHttpRequestMessage: function(request, url, isAsynch) {
  4615. // Check if a post destination was provided.
  4616. if (url === '') {
  4617. throw new exceptions.CryptoLibException(
  4618. 'No URL provided for posting HTTP request.');
  4619. }
  4620. // Create HTTP request object.
  4621. var httpRequest;
  4622. var done;
  4623. if (window.XMLHttpRequest) {
  4624. httpRequest = new XMLHttpRequest();
  4625. done = XMLHttpRequest.DONE;
  4626. } else {
  4627. throw new exceptions.CryptoLibException(
  4628. 'Could not create HTTP request object for this browser.');
  4629. }
  4630. // Define post response message handling.
  4631. var response;
  4632. httpRequest.onreadystatechange = function() {
  4633. if (httpRequest.readyState === done) {
  4634. if (httpRequest.status === 200) {
  4635. response = httpRequest.responseText;
  4636. } else {
  4637. var errorMsg =
  4638. 'HTTP request message POST was not successful.\n Status: ' +
  4639. httpRequest.status + ', Message: ' + httpRequest.statusText;
  4640. throw new exceptions.CryptoLibException(errorMsg);
  4641. }
  4642. }
  4643. };
  4644. // Open HTTP request object for synchronous post.
  4645. httpRequest.open('POST', url, isAsynch);
  4646. // Post HTTP request message.
  4647. try {
  4648. httpRequest.send(request);
  4649. } catch (error) {
  4650. var errorMsg =
  4651. 'Could not post HTTP request message; IP of web application might be incorrect.';
  4652. throw new exceptions.CryptoLibException(errorMsg, error);
  4653. }
  4654. return response;
  4655. }
  4656. };
  4657. /**
  4658. * Defines a progress meter.
  4659. *
  4660. * @param {integer}
  4661. * progressMax Maximum amount of progress to be attained.
  4662. * @param {integer}
  4663. * progressCallback Progress callback function.
  4664. * @param {integer}
  4665. * progressPercentMinCheckInterval Progress percentage minimum
  4666. * check interval (optional) (default: 10%).
  4667. * @class
  4668. */
  4669. box.commons.utils.ProgressMeter = function(
  4670. progressMax, progressCallback, progressPercentMinCheckInterval) {
  4671. this.progressMax = progressMax;
  4672. this.progressCallback = progressCallback;
  4673. this.progressPercentMinCheckInterval =
  4674. progressPercentMinCheckInterval || 10;
  4675. this.lastProgressPercent = 0;
  4676. };
  4677. box.commons.utils.ProgressMeter.prototype = {
  4678. /**
  4679. * Calculates the progress as a percentage of the total and provides it
  4680. * as input to the provided callback function.
  4681. *
  4682. * @function
  4683. * @param {integer}
  4684. * progress Present amount of progress.
  4685. */
  4686. update: function(progress) {
  4687. if (typeof this.progressCallback === 'undefined') {
  4688. return;
  4689. }
  4690. var progressPercent = Math.floor((progress / this.progressMax) * 100);
  4691. progressPercent = Math.min(progressPercent, 100);
  4692. var progressPercentChange = progressPercent - this.lastProgressPercent;
  4693. if (progressPercentChange > 0) {
  4694. var checkProgress =
  4695. (progressPercentChange >= this.progressPercentMinCheckInterval) ||
  4696. (progressPercent === 100);
  4697. if (checkProgress) {
  4698. this.lastProgressPercent = progressPercent;
  4699. this.progressCallback(progressPercent);
  4700. }
  4701. }
  4702. }
  4703. };
  4704. };
  4705. /*
  4706. * Copyright 2018 Scytl Secure Electronic Voting SA
  4707. *
  4708. * All rights reserved
  4709. *
  4710. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  4711. */
  4712. var cryptoPRNG = (function() {
  4713. 'use strict';
  4714. return {
  4715. _collectorsStarted: false,
  4716. _collectors: [],
  4717. _events: [],
  4718. _entropy: '',
  4719. _entropyCounter: 0,
  4720. _maxEntropyCounter: 0,
  4721. _collectorHashUpdater: null,
  4722. _hashUpdaterInterval: 0,
  4723. _fullEntropyCallback: null,
  4724. _tools: null,
  4725. _seedLength: 0,
  4726. _prng: null,
  4727. _privateKeyPem: '',
  4728. _pinEntropy: 0,
  4729. _usePrivateKeyEntropy: false,
  4730. /**
  4731. * Initializes all the round object fields.
  4732. *
  4733. * @function
  4734. * @param hashUpdaterInterval
  4735. * the interval, in millis, that the function that replaces the
  4736. * current entropy content by an hash is called. By default it is
  4737. * initialized to 5000.
  4738. * @param maxEntropyCounter
  4739. * number of maximum bits used to determine when the collectors
  4740. * should stop collecting entropy. By default it is initialized
  4741. * to 256.
  4742. */
  4743. _initAndStart: function(hashUpdaterInterval, fullEntropyCallback) {
  4744. this._collectorsStarted = false;
  4745. this._collectors = [];
  4746. this._events = [];
  4747. this._entropy = '';
  4748. this._entropyCounter = 0;
  4749. this._maxEntropyCounter = 256;
  4750. this._collectorHashUpdater = null;
  4751. this._hashUpdaterInterval =
  4752. (hashUpdaterInterval ? hashUpdaterInterval : 1000);
  4753. this._fullEntropyCallback = fullEntropyCallback;
  4754. this._tools = cryptoPRNG.Tools.init();
  4755. this._initCollectors();
  4756. this._startCollectors();
  4757. },
  4758. /**
  4759. * adds a new collector to the list of available connectors
  4760. *
  4761. * @param collector
  4762. * must return an object that implements the startCollector and
  4763. * stopCollector methods
  4764. */
  4765. _addCollector: function(collector) {
  4766. this._collectors.push(collector);
  4767. },
  4768. /**
  4769. * adds a new event to the list of available events
  4770. *
  4771. * @param type
  4772. * event type
  4773. * @param listener
  4774. * function that will be executed
  4775. */
  4776. _addEvent: function(type, listener) {
  4777. this._events.push({'type': type, 'listener': listener});
  4778. },
  4779. /**
  4780. * Initializes the random generator with the web kit random collector if
  4781. * available.
  4782. *
  4783. * If it is not, it considers the rest of collectors: ajax calls collector,
  4784. * JS calls execution collector, navigator information collector, math
  4785. * random collector, web kit random collector, mouse events collectors, key
  4786. * events collectors, load event collector, scroll collector)
  4787. */
  4788. _initCollectors: function() {
  4789. if (this._noWindow()) {
  4790. this._addNonWindowEntropyCollectors();
  4791. return;
  4792. }
  4793. var _crypto = this._getCrypto();
  4794. if ((_crypto) && (_crypto.getRandomValues)) {
  4795. this._addCollector(cryptoPRNG.Collectors.getWebKitRandomCollector(
  4796. _crypto, this._maxEntropyCounter));
  4797. } else {
  4798. this._addNonWindowEntropyCollectors();
  4799. // The API detects and delivers accelerometer data 50 times per
  4800. // second
  4801. if (window.DeviceOrientationEvent) {
  4802. // Listen for the device orientation event and handle
  4803. // DeviceOrientationEvent object
  4804. this._addEvent(
  4805. 'deviceorientation',
  4806. cryptoPRNG.Collectors.getDeviceOrientationCollector);
  4807. } else if (window.OrientationEvent) {
  4808. // Listen for the MozOrientation event and handle
  4809. // OrientationData object
  4810. this._addEvent(
  4811. 'MozOrientation',
  4812. cryptoPRNG.Collectors.getDeviceOrientationCollector);
  4813. }
  4814. if (window.DeviceMotionEvent) {
  4815. this._addEvent(
  4816. 'devicemotion', cryptoPRNG.Collectors.getDeviceMotionCollector);
  4817. }
  4818. }
  4819. },
  4820. _addNonWindowEntropyCollectors: function() {
  4821. if (this._usePrivateKeyEntropy) {
  4822. this._addCollector(cryptoPRNG.Collectors.getPrivateKeyCollector(
  4823. this._privateKeyPem, this._pinEntropy));
  4824. }
  4825. this._addCollector(cryptoPRNG.Collectors.getAjaxCollector());
  4826. this._addCollector(cryptoPRNG.Collectors.getJSExecutionCollector());
  4827. this._addCollector(cryptoPRNG.Collectors.getNavigatorInfoCollector());
  4828. this._addCollector(cryptoPRNG.Collectors.getMathRandomCollector());
  4829. // mouse events collectors
  4830. this._addEvent('mousemove', cryptoPRNG.Collectors.getMouseMoveCollector);
  4831. this._addEvent(
  4832. 'mousewheel', cryptoPRNG.Collectors.getMouseWheelCollector);
  4833. this._addEvent('mouseup', cryptoPRNG.Collectors.getMouseUpCollector);
  4834. this._addEvent('mousedown', cryptoPRNG.Collectors.getMouseDownCollector);
  4835. this._addEvent(
  4836. 'touchstart', cryptoPRNG.Collectors.getTouchStartCollector);
  4837. this._addEvent('touchmove', cryptoPRNG.Collectors.getTouchMoveCollector);
  4838. this._addEvent('touchend', cryptoPRNG.Collectors.getTouchEndCollector);
  4839. this._addEvent(
  4840. 'gesturestart', cryptoPRNG.Collectors.getGestureStartCollector);
  4841. this._addEvent(
  4842. 'gestureend', cryptoPRNG.Collectors.getGestureEndCollector);
  4843. // keyboard events collectors
  4844. this._addEvent('keyup', cryptoPRNG.Collectors.getKeyUpCollector);
  4845. this._addEvent('keydown', cryptoPRNG.Collectors.getKeyDownCollector);
  4846. // page events collectors
  4847. this._addEvent('load', cryptoPRNG.Collectors.getLoadCollector);
  4848. this._addEvent('scroll', cryptoPRNG.Collectors.getScrollCollector);
  4849. // requests collector collectors
  4850. this._addEvent('beforeload', cryptoPRNG.Collectors.getRequestsCollector);
  4851. },
  4852. _getCrypto: function() {
  4853. return window.crypto || window.msCrypto;
  4854. },
  4855. _noWindow: function() {
  4856. return (typeof window === 'undefined');
  4857. },
  4858. /**
  4859. * Start the collectors
  4860. */
  4861. _startCollectors: function() {
  4862. if (this._collectorsStarted) {
  4863. return;
  4864. }
  4865. var i = 0;
  4866. // start all the collectors
  4867. while (i < this._collectors.length) {
  4868. try {
  4869. this._collectors[i].startCollector();
  4870. } catch (e) {
  4871. // do not do anything about any exception that is thrown
  4872. // by the execution of the collectors
  4873. }
  4874. i++;
  4875. }
  4876. i = 0;
  4877. // start all the events
  4878. while (i < this._events.length) {
  4879. try {
  4880. if (window.addEventListener) {
  4881. window.addEventListener(
  4882. this._events[i].type, this._events[i].listener, false);
  4883. } else if (document.attachEvent) {
  4884. document.attachEvent(
  4885. 'on' + this._events[i].type, this._events[i].listener);
  4886. }
  4887. } catch (e) {
  4888. // do not do anything about any exception that is thrown
  4889. // by the execution of the events
  4890. }
  4891. i++;
  4892. }
  4893. this._tools._mdUpdate.start();
  4894. this._collectorHashUpdater = setInterval(function() {
  4895. cryptoPRNG._hashUpdater();
  4896. }, this._hashUpdaterInterval);
  4897. this._collectorsStarted = true;
  4898. },
  4899. /**
  4900. * Stop the collectors
  4901. */
  4902. _stopCollectors: function() {
  4903. if (!this._collectorsStarted) {
  4904. return;
  4905. }
  4906. var i = 0;
  4907. while (i < this._collectors.length) {
  4908. try {
  4909. this._collectors[i].stopCollector();
  4910. } catch (e) {
  4911. // do not do anything about any exception that is thrown
  4912. // by the execution of the collectors
  4913. }
  4914. i++;
  4915. }
  4916. i = 0;
  4917. while (i < this._events.length) {
  4918. try {
  4919. if (window.removeEventListener) {
  4920. window.removeEventListener(
  4921. this._events[i].type, this._events[i].listener, false);
  4922. } else if (document.detachEvent) {
  4923. document.detachEvent(
  4924. 'on' + this._events[i].type, this._events[i].listener);
  4925. }
  4926. } catch (e) {
  4927. // do not do anything about any exception that is thrown
  4928. // by the remove of the events
  4929. }
  4930. i++;
  4931. }
  4932. if (this._collectorHashUpdater) {
  4933. clearInterval(this._collectorHashUpdater);
  4934. }
  4935. this._collectorsStarted = false;
  4936. },
  4937. /**
  4938. * Usually this method is called from the collectors and events. It adds
  4939. * entropy to the already collected entropy and increments the entropy
  4940. * counter
  4941. *
  4942. * @param data
  4943. * the entropy data to be added
  4944. * @param entropyCounter
  4945. * the entropy counter to be added
  4946. */
  4947. _collectEntropy: function(data, entropyCounter) {
  4948. this._entropy += data;
  4949. this._entropyCounter += (entropyCounter ? entropyCounter : 0);
  4950. // if the entropy counter has reach the limit, update the hash and stop
  4951. // the collectors
  4952. if (this._entropyCounter >= this._maxEntropyCounter &&
  4953. this._collectorsStarted) {
  4954. this._hashUpdater();
  4955. }
  4956. },
  4957. /**
  4958. * Sets the entropy data with the hash that is created using the current
  4959. * entropy data value. If the entropy counter has reached the max entropy
  4960. * counter set, it stops the collectors
  4961. *
  4962. * @return the generated entropy hash
  4963. */
  4964. _hashUpdater: function() {
  4965. var entropyHash = this._updateEntropyHash();
  4966. if (this._entropyCounter >= this._maxEntropyCounter &&
  4967. this._collectorsStarted) {
  4968. entropyHash = this._stopCollectEntropy();
  4969. var newPRNG = new cryptoPRNG.PRNG(entropyHash, this._tools);
  4970. if (this._fullEntropyCallback) {
  4971. this._fullEntropyCallback(newPRNG);
  4972. } else {
  4973. this._prng = newPRNG;
  4974. }
  4975. }
  4976. return entropyHash;
  4977. },
  4978. _stopCollectEntropy: function() {
  4979. // stop collecting entropy
  4980. this._stopCollectors();
  4981. var entropyHash = this._updateEntropyHash();
  4982. this._entropy = '';
  4983. this._entropyCounter = 0;
  4984. return entropyHash;
  4985. },
  4986. _updateEntropyHash: function() {
  4987. var digester = this._tools._mdUpdate;
  4988. digester.update(this._entropy);
  4989. var entropyHash = forge.util.bytesToHex(digester.digest().getBytes());
  4990. this._entropy = entropyHash;
  4991. return entropyHash;
  4992. },
  4993. /**
  4994. * Set Private Key and an Entropy it adds to be used to collect Entropy. The
  4995. * amount of randomness(entropy) depends on the pin that is used for Private
  4996. * Key generating.
  4997. *
  4998. * @function
  4999. * @param privateKey
  5000. * {string} private key, as string in PEM format.
  5001. * @param pinEntropy
  5002. * the amount of randomness that can be extracted from the
  5003. * Private Key.
  5004. */
  5005. setDataForPrivateKeyEntropyCollector: function(privateKeyPem, pinEntropy) {
  5006. if (privateKeyPem && (!isNaN(pinEntropy)) && (pinEntropy > 0)) {
  5007. this._privateKeyPem = privateKeyPem;
  5008. this._pinEntropy = pinEntropy;
  5009. this._usePrivateKeyEntropy = true;
  5010. }
  5011. },
  5012. /**
  5013. * Initializes collectors and starts them. Set Private Key and Entropy
  5014. * before if this information should be used to collect Entropy.
  5015. */
  5016. startEntropyCollection: function(entropyCollectorCallback) {
  5017. var hashUpdaterInterval = 1000;
  5018. this._initAndStart(hashUpdaterInterval, entropyCollectorCallback);
  5019. },
  5020. /**
  5021. * In the case that the maximum amount of entropy had been reached before
  5022. * calling this method, it does not do anything, and a false is returned.
  5023. * Otherwise, this method creates a PRNG if the collectors have not gathered
  5024. * the maximum amount of entropy. In addition, it stops the collectors.
  5025. *
  5026. * This method return a true if the maximum entropy was already reached and
  5027. * false in other case.
  5028. */
  5029. stopEntropyCollectionAndCreatePRNG: function() {
  5030. var generatedWithMaximumEntropy = true;
  5031. if (!this._prng) {
  5032. var entropyHash = this._stopCollectEntropy();
  5033. this._prng = new cryptoPRNG.PRNG(entropyHash, this._tools);
  5034. generatedWithMaximumEntropy = false;
  5035. }
  5036. return generatedWithMaximumEntropy;
  5037. },
  5038. /**
  5039. * This method creates a PRNG from a given seed, in Hexadecimal format. This
  5040. * method is to be used from a Worker, which has received the seed from the
  5041. * main thread.
  5042. *
  5043. * @param seed
  5044. * A string of 64 characters. It represents a 32-byte array in
  5045. * Hexadecimal.
  5046. *
  5047. */
  5048. createPRNGFromSeed: function(seed) {
  5049. this._prng = new cryptoPRNG.PRNG(seed, this._tools);
  5050. },
  5051. /**
  5052. * Generates a random array of bytes, which is then formatted to hexadecimal
  5053. * This method is to be called from the main thread, and the given string is
  5054. * to be passed to a Worker.
  5055. */
  5056. generateRandomSeedInHex: function(lengthSeed) {
  5057. this._seedLength = (lengthSeed ? lengthSeed : 32);
  5058. var seedInBytes = this._prng.generate(this._seedLength);
  5059. return forge.util.bytesToHex(seedInBytes);
  5060. },
  5061. getPRNG: function() {
  5062. if (!this._prng) {
  5063. throw new Error('The PRNG has not been initialized yet');
  5064. }
  5065. return this._prng;
  5066. },
  5067. getEntropyCollectedAsPercentage: function() {
  5068. if (this._entropyCounter >= this._maxEntropyCounter) {
  5069. return 100;
  5070. }
  5071. return this._entropyCounter * 100 / this._maxEntropyCounter;
  5072. }
  5073. };
  5074. })();
  5075. cryptoPRNG.Tools = (function() {
  5076. 'use strict';
  5077. return {
  5078. _mdUpdate: null,
  5079. _mdReseed: null,
  5080. _formatKey: null,
  5081. _formatSeed: null,
  5082. _cipher: null,
  5083. init: function() {
  5084. this._mdUpdate = forge.md.sha256.create();
  5085. this._mdReseed = forge.md.sha256.create();
  5086. this._formatKey = function(key) {
  5087. // convert the key into 32-bit integers
  5088. var tmp = forge.util.createBuffer(key);
  5089. key = [
  5090. tmp.getInt32(),
  5091. tmp.getInt32(),
  5092. tmp.getInt32(),
  5093. tmp.getInt32(),
  5094. tmp.getInt32(),
  5095. tmp.getInt32(),
  5096. tmp.getInt32(),
  5097. tmp.getInt32()
  5098. ];
  5099. // return the expanded key
  5100. return forge.aes._expandKey(key, false);
  5101. };
  5102. this._formatSeed = function(seed) {
  5103. // convert seed into 32-bit integers
  5104. var tmp = forge.util.createBuffer(seed);
  5105. seed = [
  5106. tmp.getInt32(),
  5107. tmp.getInt32(),
  5108. tmp.getInt32(),
  5109. tmp.getInt32()
  5110. ];
  5111. return seed;
  5112. };
  5113. this._cipher = function(key, counter) {
  5114. var aes_output = [];
  5115. forge.aes._updateBlock(
  5116. this._formatKey(key), this._formatSeed('' + counter), aes_output,
  5117. false);
  5118. var aes_buffer = forge.util.createBuffer();
  5119. aes_buffer.putInt32(aes_output[0]);
  5120. aes_buffer.putInt32(aes_output[1]);
  5121. aes_buffer.putInt32(aes_output[2]);
  5122. aes_buffer.putInt32(aes_output[3]);
  5123. return aes_buffer.getBytes();
  5124. };
  5125. return this;
  5126. }
  5127. };
  5128. })();
  5129. cryptoPRNG.PRNG = function(entropyHash, tools) {
  5130. 'use strict';
  5131. this._key = '';
  5132. this._counter = 0;
  5133. this._tools = null;
  5134. if (tools) {
  5135. this._tools = tools;
  5136. } else {
  5137. this._tools = cryptoPRNG.Tools.init();
  5138. }
  5139. this._entropyHash = entropyHash;
  5140. };
  5141. cryptoPRNG.PRNG.prototype = (function() {
  5142. 'use strict';
  5143. return {
  5144. /**
  5145. * Generates a random array of bytes using the gathered entropy data.
  5146. *
  5147. * @param count
  5148. * the total number of random bytes to generate
  5149. */
  5150. generate: function(count) {
  5151. var keyAux;
  5152. if (this._key === null || this._key === '') {
  5153. this._reseed();
  5154. }
  5155. // buffer where to store the random bytes
  5156. var b = forge.util.createBuffer();
  5157. var limitReach = 1;
  5158. while (b.length() < count) {
  5159. b.putBytes(this._tools._cipher(this._key, this._counter));
  5160. this._counter++;
  5161. if (b.length >= (limitReach * Math.pow(2, 20))) {
  5162. keyAux = this._key;
  5163. this._key = '';
  5164. for (var i = 0; i < 2; i++) {
  5165. this._key += this._tools._cipher(keyAux, this._counter);
  5166. this._counter++;
  5167. }
  5168. limitReach++;
  5169. }
  5170. }
  5171. // do it two times to ensure a key with 256 bits
  5172. keyAux = this._key;
  5173. this._key = '';
  5174. for (var j = 0; j < 2; j++) {
  5175. this._key += this._tools._cipher(keyAux, this._counter);
  5176. this._counter++;
  5177. }
  5178. return b.getBytes(count);
  5179. },
  5180. /**
  5181. * Reseeds the generator
  5182. */
  5183. _reseed: function() {
  5184. var digester = this._tools._mdReseed;
  5185. digester.start();
  5186. digester.update(this._entropyHash);
  5187. digester.update(this._key);
  5188. this._key = forge.util.bytesToHex(digester.digest().getBytes());
  5189. this._counter++;
  5190. }
  5191. };
  5192. })();
  5193. cryptoPRNG.Collectors = (function() {
  5194. 'use strict';
  5195. var MIN_MATH_ROUND_ENTROPY_FACTOR = 1000000;
  5196. function _getMathRoundWithEntropy(data) {
  5197. return Math.round(data * MIN_MATH_ROUND_ENTROPY_FACTOR);
  5198. }
  5199. return {
  5200. getAjaxCollector: function() {
  5201. return {
  5202. startCollector: function() {
  5203. // if jQuery is included
  5204. if (window.jQuery !== undefined) {
  5205. $(window)
  5206. .ajaxStart(function() {
  5207. cryptoPRNG._collectEntropy((+new Date()), 1);
  5208. })
  5209. .ajaxComplete(function() {
  5210. cryptoPRNG._collectEntropy((+new Date()), 1);
  5211. });
  5212. }
  5213. },
  5214. stopCollector: function() {
  5215. // if jQuery is included
  5216. if (window.jQuery !== undefined) {
  5217. $(window).unbind('ajaxStart');
  5218. $(window).unbind('ajaxComplete');
  5219. }
  5220. return true;
  5221. }
  5222. };
  5223. },
  5224. getJSExecutionCollector: function() {
  5225. return {
  5226. _collectTimeout: null,
  5227. startCollector: function() {
  5228. var timer_start = (+new Date()), timer_end;
  5229. this._collectTimeout = (function collect() {
  5230. timer_end = (+new Date());
  5231. var total_time = timer_end - timer_start;
  5232. // because of browser baseline time checks we limit it
  5233. if (total_time > 20) {
  5234. cryptoPRNG._collectEntropy((+new Date()), 1);
  5235. }
  5236. timer_start = timer_end;
  5237. return setTimeout(collect, 0);
  5238. })();
  5239. },
  5240. stopCollector: function() {
  5241. clearTimeout(this._collectTimeout);
  5242. }
  5243. };
  5244. },
  5245. getNavigatorInfoCollector: function() {
  5246. return {
  5247. startCollector: function() {
  5248. if (typeof(navigator) !== 'undefined') {
  5249. var _navString = '';
  5250. for (var key in navigator) {
  5251. if (typeof key !== 'undefined') {
  5252. try {
  5253. if (typeof(navigator[key]) === 'string') {
  5254. _navString += navigator[key];
  5255. }
  5256. } catch (e) {
  5257. // ignore any kind of exception
  5258. }
  5259. }
  5260. }
  5261. cryptoPRNG._collectEntropy(_navString, 1);
  5262. }
  5263. },
  5264. stopCollector: function() {
  5265. // just executed once, so no need to execute nothing more
  5266. return true;
  5267. }
  5268. };
  5269. },
  5270. getMathRandomCollector: function() {
  5271. return {
  5272. startCollector: function() {
  5273. cryptoPRNG._collectEntropy(Math.random(), 0);
  5274. },
  5275. stopCollector: function() {
  5276. // just executed once, so no need to execute nothing more
  5277. return true;
  5278. }
  5279. };
  5280. },
  5281. getPrivateKeyCollector: function(privateKeyPem, pinEntropy) {
  5282. var privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
  5283. return {
  5284. pkCollector: true,
  5285. startCollector: function() {
  5286. cryptoPRNG._collectEntropy(privateKey.d, pinEntropy);
  5287. },
  5288. stopCollector: function() {
  5289. // just executed once, so no need to execute nothing more
  5290. return true;
  5291. }
  5292. };
  5293. },
  5294. getWebKitRandomCollector: function(globalCrypto, entropyQuantity) {
  5295. return {
  5296. startCollector: function() {
  5297. var numPositions = entropyQuantity / 32;
  5298. // get cryptographically strong entropy in Webkit
  5299. var ab = new Uint32Array(numPositions);
  5300. globalCrypto.getRandomValues(ab);
  5301. var data = '';
  5302. for (var i = 0; i < ab.length; i++) {
  5303. data += '' + (ab[i]);
  5304. }
  5305. cryptoPRNG._collectEntropy(data, entropyQuantity);
  5306. },
  5307. stopCollector: function() {
  5308. // just executed once, so no need to execute nothing more
  5309. return true;
  5310. }
  5311. };
  5312. },
  5313. getMouseMoveCollector: function(ev) {
  5314. // to ensure compatibility with IE 8
  5315. ev = ev || window.event;
  5316. cryptoPRNG._collectEntropy(
  5317. (ev.x || ev.clientX || ev.offsetX || 0) +
  5318. (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
  5319. 3);
  5320. },
  5321. getMouseWheelCollector: function(ev) {
  5322. ev = ev || window.event;
  5323. cryptoPRNG._collectEntropy((ev.offsetY || 0) + (+new Date()), 3);
  5324. },
  5325. getMouseDownCollector: function(ev) {
  5326. ev = ev || window.event;
  5327. cryptoPRNG._collectEntropy(
  5328. (ev.x || ev.clientX || ev.offsetX || 0) +
  5329. (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
  5330. 3);
  5331. },
  5332. getMouseUpCollector: function(ev) {
  5333. ev = ev || window.event;
  5334. cryptoPRNG._collectEntropy(
  5335. (ev.x || ev.clientX || ev.offsetX || 0) +
  5336. (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
  5337. 3);
  5338. },
  5339. getTouchStartCollector: function(ev) {
  5340. ev = ev || window.event;
  5341. cryptoPRNG._collectEntropy(
  5342. (ev.touches[0].pageX || ev.clientX || 0) +
  5343. (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
  5344. 5);
  5345. },
  5346. getTouchMoveCollector: function(ev) {
  5347. ev = ev || window.event;
  5348. cryptoPRNG._collectEntropy(
  5349. (ev.touches[0].pageX || ev.clientX || 0) +
  5350. (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
  5351. 3);
  5352. },
  5353. getTouchEndCollector: function() {
  5354. cryptoPRNG._collectEntropy((+new Date()), 1);
  5355. },
  5356. getGestureStartCollector: function(ev) {
  5357. ev = ev || window.event;
  5358. cryptoPRNG._collectEntropy(
  5359. (ev.touches[0].pageX || ev.clientX || 0) +
  5360. (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
  5361. 5);
  5362. },
  5363. getGestureEndCollector: function() {
  5364. cryptoPRNG._collectEntropy((+new Date()), 1);
  5365. },
  5366. motionX: null,
  5367. motionY: null,
  5368. motionZ: null,
  5369. getDeviceMotionCollector: function(ev) {
  5370. ev = ev || window.event;
  5371. var acceleration = ev.accelerationIncludingGravity;
  5372. var currentX = (_getMathRoundWithEntropy(acceleration.x) || 0);
  5373. var currentY = (_getMathRoundWithEntropy(acceleration.y) || 0);
  5374. var currentZ = (_getMathRoundWithEntropy(acceleration.z) || 0);
  5375. var rotation = ev.rotationRate;
  5376. if (rotation !== null) {
  5377. currentX += _getMathRoundWithEntropy(rotation.alpha);
  5378. currentY += _getMathRoundWithEntropy(rotation.beta);
  5379. currentZ += _getMathRoundWithEntropy(rotation.gamma);
  5380. }
  5381. // The API detects and delivers accelerometer data 50 times per
  5382. // second
  5383. // even if there is any event related, so this is
  5384. // a way to control if it really changed or not
  5385. if ((cryptoPRNG.Collectors.motionX === null) ||
  5386. (cryptoPRNG.Collectors.motionY === null) ||
  5387. (cryptoPRNG.Collectors.motionZ === null) ||
  5388. (cryptoPRNG.Collectors.motionX !== currentX) ||
  5389. (cryptoPRNG.Collectors.motionY !== currentY) ||
  5390. (cryptoPRNG.Collectors.motionZ !== currentZ)) {
  5391. cryptoPRNG.Collectors.motionX = currentX;
  5392. cryptoPRNG.Collectors.motionY = currentY;
  5393. cryptoPRNG.Collectors.motionZ = currentZ;
  5394. cryptoPRNG._collectEntropy(
  5395. currentX + currentY + currentZ + (+new Date()), 1);
  5396. }
  5397. },
  5398. deviceOrientationX: null,
  5399. deviceOrientationY: null,
  5400. deviceOrientationZ: null,
  5401. getDeviceOrientationCollector: function(ev) {
  5402. ev = ev || window.event;
  5403. var currentX =
  5404. (_getMathRoundWithEntropy(ev.gamma) ||
  5405. _getMathRoundWithEntropy(ev.x) || 0);
  5406. var currentY =
  5407. (_getMathRoundWithEntropy(ev.beta) ||
  5408. _getMathRoundWithEntropy(ev.y) || 0);
  5409. var currentZ =
  5410. (_getMathRoundWithEntropy(ev.alpha) ||
  5411. _getMathRoundWithEntropy(ev.z) || 0);
  5412. // The API detects and delivers accelerometer data 50 times per
  5413. // second
  5414. // even if there is any event related, so this is
  5415. // a way to control if it really changed or not
  5416. if ((cryptoPRNG.Collectors.deviceOrientationX === null) ||
  5417. (cryptoPRNG.Collectors.deviceOrientationY === null) ||
  5418. (cryptoPRNG.Collectors.deviceOrientationZ === null) ||
  5419. (cryptoPRNG.Collectors.deviceOrientationX !== currentX) ||
  5420. (cryptoPRNG.Collectors.deviceOrientationY !== currentY) ||
  5421. (cryptoPRNG.Collectors.deviceOrientationZ !== currentZ)) {
  5422. cryptoPRNG.Collectors.deviceOrientationX = currentX;
  5423. cryptoPRNG.Collectors.deviceOrientationY = currentY;
  5424. cryptoPRNG.Collectors.deviceOrientationZ = currentZ;
  5425. cryptoPRNG._collectEntropy(
  5426. currentX + currentY + currentZ + (+new Date()), 1);
  5427. }
  5428. },
  5429. getKeyDownCollector: function(ev) {
  5430. ev = ev || window.event;
  5431. cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
  5432. },
  5433. getKeyUpCollector: function(ev) {
  5434. ev = ev || window.event;
  5435. cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
  5436. },
  5437. getLoadCollector: function(ev) {
  5438. ev = ev || window.event;
  5439. cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
  5440. },
  5441. getScrollCollector: function(ev) {
  5442. ev = ev || window.event;
  5443. cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
  5444. },
  5445. getRequestsCollector: function(ev) {
  5446. ev = ev || window.event;
  5447. cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
  5448. }
  5449. };
  5450. })();
  5451. /*
  5452. * Copyright 2018 Scytl Secure Electronic Voting SA
  5453. *
  5454. * All rights reserved
  5455. *
  5456. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  5457. */
  5458. cryptolib.modules = cryptolib.modules || {};
  5459. /**
  5460. * Defines the generation and opening of digital envelopes.
  5461. */
  5462. cryptolib.modules.digitalenvelope = function(box) {
  5463. 'use strict';
  5464. box.digitalenvelope = box.digitalenvelope || {};
  5465. box.digitalenvelope.factory = {};
  5466. var policies = {
  5467. symmetric: {
  5468. secretkey: {
  5469. encryption: {
  5470. lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
  5471. .encryption.lengthBytes
  5472. },
  5473. mac: {
  5474. lengthBytes:
  5475. box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
  5476. }
  5477. }
  5478. }
  5479. };
  5480. var exceptions;
  5481. var converters;
  5482. var bitOperators;
  5483. var secretKeyFactory;
  5484. var macDigester;
  5485. var symmetricCipher;
  5486. var asymmetricCipher;
  5487. var f = function(box) {
  5488. exceptions = box.commons.exceptions;
  5489. converters = new box.commons.utils.Converters();
  5490. bitOperators = new box.commons.utils.BitOperators();
  5491. secretKeyFactory = new box.symmetric.secretkey.factory.SecretKeyFactory();
  5492. macDigester = (new box.symmetric.mac.factory.MacFactory()).create();
  5493. symmetricCipher =
  5494. (new box.symmetric.cipher.factory.SymmetricCipherFactory())
  5495. .getCryptoSymmetricCipher();
  5496. asymmetricCipher =
  5497. (new box.asymmetric.cipher.factory.AsymmetricCipherFactory())
  5498. .getCryptoAsymmetricCipher();
  5499. };
  5500. f.policies = {
  5501. symmetric: {
  5502. secretkey: {
  5503. encryption: {
  5504. lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
  5505. .encryption.lengthBytes
  5506. },
  5507. mac: {
  5508. lengthBytes:
  5509. box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
  5510. },
  5511. secureRandom: {
  5512. provider: box.policies.digitalenvelope.symmetric.secretkey
  5513. .secureRandom.provider
  5514. }
  5515. },
  5516. cipher: {
  5517. provider: box.policies.digitalenvelope.symmetric.cipher.provider,
  5518. algorithm: {
  5519. AES128_GCM: {
  5520. name: box.policies.digitalenvelope.symmetric.cipher.algorithm
  5521. .AES128_GCM.name,
  5522. keyLengthBytes: box.policies.digitalenvelope.symmetric.cipher
  5523. .algorithm.AES128_GCM.keyLengthBytes,
  5524. tagLengthBytes: box.policies.digitalenvelope.symmetric.cipher
  5525. .algorithm.AES128_GCM.tagLengthBytes
  5526. }
  5527. },
  5528. initializationVectorLengthBytes:
  5529. box.policies.digitalenvelope.symmetric.cipher
  5530. .initializationVectorLengthBytes,
  5531. secureRandom: {
  5532. provider: box.policies.digitalenvelope.symmetric.cipher.secureRandom
  5533. .provider
  5534. }
  5535. },
  5536. mac: {
  5537. hash: box.policies.digitalenvelope.symmetric.mac.hash,
  5538. provider: box.policies.digitalenvelope.symmetric.mac.provider
  5539. }
  5540. },
  5541. asymmetric: {
  5542. cipher: {
  5543. algorithm: box.policies.digitalenvelope.asymmetric.cipher.algorithm,
  5544. secretKeyLengthBytes:
  5545. box.policies.digitalenvelope.asymmetric.cipher.secretKeyLengthBytes,
  5546. ivLengthBytes:
  5547. box.policies.digitalenvelope.asymmetric.cipher.ivLengthBytes,
  5548. tagLengthBytes:
  5549. box.policies.digitalenvelope.asymmetric.cipher.tagLengthBytes,
  5550. deriver: box.policies.digitalenvelope.asymmetric.cipher.deriver,
  5551. hash: box.policies.digitalenvelope.asymmetric.cipher.hash,
  5552. symmetricCipher:
  5553. box.policies.digitalenvelope.asymmetric.cipher.symmetricCipher,
  5554. provider: box.policies.digitalenvelope.asymmetric.cipher.provider,
  5555. secureRandom: {
  5556. provider: box.policies.digitalenvelope.asymmetric.cipher.secureRandom
  5557. .provider
  5558. }
  5559. }
  5560. }
  5561. };
  5562. cryptolib('commons', 'symmetric', 'asymmetric.cipher', f);
  5563. /**
  5564. * Defines a factory for the creation of digital envelope generators and
  5565. * openers.
  5566. *
  5567. * @class DigitalEnvelopeFactory
  5568. * @memberof digitalenvelope
  5569. */
  5570. box.digitalenvelope.factory.DigitalEnvelopeFactory = function() {
  5571. };
  5572. box.digitalenvelope.factory.DigitalEnvelopeFactory.prototype = {
  5573. /**
  5574. * Obtains a new digital envelope generator.
  5575. *
  5576. * @function getDigitalEnvelopeGenerator
  5577. * @return {DigitalEnvelopeGenerator} the digital envelope generator.
  5578. */
  5579. getDigitalEnvelopeGenerator: function() {
  5580. try {
  5581. return new box.digitalenvelope.DigitalEnvelopeGenerator();
  5582. } catch (error) {
  5583. throw new exceptions.CryptoLibException(
  5584. 'Could not obtain a digital envelope generator.', error);
  5585. }
  5586. },
  5587. /**
  5588. * Obtains new a digital envelope opener.
  5589. *
  5590. * @function getDigitalEnvelopeOpener
  5591. * @return {DigitalEnvelopeOpener} the digital envelope opener.
  5592. */
  5593. getDigitalEnvelopeOpener: function() {
  5594. try {
  5595. return new box.digitalenvelope.DigitalEnvelopeOpener();
  5596. } catch (error) {
  5597. throw new exceptions.CryptoLibException(
  5598. 'Could not obtain a digital envelope opener.', error);
  5599. }
  5600. }
  5601. };
  5602. /**
  5603. * Defines a digital envelope generator.
  5604. *
  5605. * @class DigitalEnvelopeGenerator
  5606. * @memberof digitalenvelope
  5607. */
  5608. box.digitalenvelope.DigitalEnvelopeGenerator = function() {
  5609. };
  5610. box.digitalenvelope.DigitalEnvelopeGenerator.prototype = {
  5611. /**
  5612. * Generates a digital envelope for some data. The envelope can be
  5613. * generated with one or more public keys, each of whose corresponding
  5614. * private key can be used to open the envelope.
  5615. *
  5616. * @function generate
  5617. * @param dataBase64
  5618. * {string} the data to store in the digital envelope, as a
  5619. * string in Base64 encoded format.
  5620. * @param publicKeysPem
  5621. * {string[]} a list of one or more public keys used to
  5622. * generate the digital envelope, as an array of strings in
  5623. * PEM format.
  5624. * @return {DigitalEnvelope} the generated digital envelope.
  5625. */
  5626. generate: function(dataBase64, publicKeysPem) {
  5627. try {
  5628. validateGeneratorInput(dataBase64, publicKeysPem);
  5629. // Generate encryption secret key and use it to symmetrically encrypt
  5630. // data.
  5631. var secretKeyForEncryptionBase64 =
  5632. secretKeyFactory.getCryptoSecretKeyGeneratorForEncryption()
  5633. .generate();
  5634. var encryptedDataBase64 =
  5635. symmetricCipher.encrypt(secretKeyForEncryptionBase64, dataBase64);
  5636. // Generate MAC secret key and use it to generate MAC of symmetrically
  5637. // Base64 encryption of encrypted data.
  5638. var secretKeyForMacBase64 =
  5639. secretKeyFactory.getCryptoSecretKeyGeneratorForMac().generate();
  5640. var encryptedDataBase64Base64 =
  5641. converters.base64Encode(encryptedDataBase64);
  5642. var macBase64 = macDigester.generate(
  5643. secretKeyForMacBase64, [encryptedDataBase64Base64]);
  5644. // Construct bit-wise concatenation of encryption and MAC secret keys.
  5645. var secretKeyForEncryption =
  5646. converters.base64Decode(secretKeyForEncryptionBase64);
  5647. var secretKeyForMac = converters.base64Decode(secretKeyForMacBase64);
  5648. var secretKeyConcatenation =
  5649. secretKeyForEncryption.toString() + secretKeyForMac.toString();
  5650. var secretKeyConcatenationBase64 =
  5651. converters.base64Encode(secretKeyConcatenation);
  5652. // Generate list of asymmetric encryptions of the secret key
  5653. // concatenation, each encryption created using a different one of the
  5654. // public keys provided as input for the digital envelope generation.
  5655. var secretKeyEncryptions = [];
  5656. for (var i = 0; i < publicKeysPem.length; i++) {
  5657. var publicKeyPem = publicKeysPem[i];
  5658. var encryptedSecretKeyConcatentionBase64 = asymmetricCipher.encrypt(
  5659. publicKeyPem, secretKeyConcatenationBase64);
  5660. secretKeyEncryptions.push(new SecretKeyEncryption(
  5661. encryptedSecretKeyConcatentionBase64, publicKeyPem));
  5662. }
  5663. return new DigitalEnvelope(
  5664. encryptedDataBase64, macBase64, secretKeyEncryptions);
  5665. } catch (error) {
  5666. throw new exceptions.CryptoLibException(
  5667. 'Digital envelope could not be generated.', error);
  5668. }
  5669. }
  5670. };
  5671. /**
  5672. * Defines a digital envelope opener.
  5673. *
  5674. * @class DigitalEnvelopeOpener
  5675. * @memberof digitalenvelope
  5676. */
  5677. box.digitalenvelope.DigitalEnvelopeOpener = function() {
  5678. this._getEncryptedSecretKeyConcatenation = function(
  5679. secretKeyEncryptions, privateKeyPem) {
  5680. // Extract modulus and public exponent from private key.
  5681. var privateKey = box.forge.pki.privateKeyFromPem(privateKeyPem);
  5682. var modulus = privateKey.n;
  5683. var publicExponent = privateKey.e;
  5684. for (var i = 0; i < secretKeyEncryptions.length; i++) {
  5685. var publicKeyPem = secretKeyEncryptions[i].getPublicKey();
  5686. var publicKey = box.forge.pki.publicKeyFromPem(publicKeyPem);
  5687. if (publicKey.n.equals(modulus) && publicKey.e.equals(publicExponent)) {
  5688. return secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
  5689. }
  5690. }
  5691. throw new exceptions.CryptoLibException(
  5692. 'Could not find an asymmetric encryption of the secret key concatenation that could be decrypted using the private key provided.');
  5693. };
  5694. };
  5695. box.digitalenvelope.DigitalEnvelopeOpener.prototype = {
  5696. /**
  5697. * Opens a digital envelope and retrieves its data. The envelope can be
  5698. * opened with any private key corresponding to a public key that was
  5699. * used to generate the envelope.
  5700. *
  5701. * @function open
  5702. * @param digitalEnvelope
  5703. * {DigitalEnvelope} the digital envelope to open.
  5704. * @param privateKeyPem
  5705. * {string} the private key used to open the digital
  5706. * envelope, as a string in PEM format.
  5707. * @return {string} the data stored in the digital envelope, as a string
  5708. * in Base64 encoded format.
  5709. */
  5710. open: function(digitalEnvelope, privateKeyPem) {
  5711. try {
  5712. validateOpenerInput(digitalEnvelope, privateKeyPem);
  5713. // Retrieve data from digital envelope.
  5714. var encryptedDataBase64 = digitalEnvelope.getEncryptedData();
  5715. var macBase64 = digitalEnvelope.getMac();
  5716. var secretKeyEncryptions = digitalEnvelope.getSecretKeyEncryptions();
  5717. // Retrieve asymmetric encryption of bit-wise concatenation of
  5718. // encryption and MAC secret keys that can be decrypted with private
  5719. // key provided as input.
  5720. var encryptedSecretKeyConcatenationBase64 =
  5721. this._getEncryptedSecretKeyConcatenation(
  5722. secretKeyEncryptions, privateKeyPem);
  5723. // Asymmetrically decrypt bit-wise concatenation of encryption and MAC
  5724. // secret keys.
  5725. var secretKeyConcatenationBase64 = asymmetricCipher.decrypt(
  5726. privateKeyPem, encryptedSecretKeyConcatenationBase64);
  5727. var secretKeyConcatenation =
  5728. converters.base64Decode(secretKeyConcatenationBase64);
  5729. // Extract secret keys from bit-wise concatenation.
  5730. var secretKeyForEncryptionLength =
  5731. policies.symmetric.secretkey.encryption.lengthBytes;
  5732. var secretKeyForMacLength =
  5733. policies.symmetric.secretkey.mac.lengthBytes;
  5734. var secretKeyForEncryption = bitOperators.extract(
  5735. secretKeyConcatenation, 0, secretKeyForEncryptionLength);
  5736. var secretKeyForEncryptionBase64 =
  5737. converters.base64Encode(secretKeyForEncryption);
  5738. var secretKeyForMac = bitOperators.extract(
  5739. secretKeyConcatenation, secretKeyForEncryptionLength,
  5740. secretKeyForEncryptionLength + secretKeyForMacLength);
  5741. var secretKeyForMacBase64 = converters.base64Encode(secretKeyForMac);
  5742. // Check integrity of digital envelope.
  5743. var encryptedDataBase64Base64 =
  5744. converters.base64Encode(encryptedDataBase64);
  5745. if (!macDigester.verify(
  5746. macBase64, secretKeyForMacBase64,
  5747. [encryptedDataBase64Base64])) {
  5748. throw new exceptions.CryptoLibException(
  5749. 'Integrity of digital envelope could not be verified.');
  5750. }
  5751. return symmetricCipher.decrypt(
  5752. secretKeyForEncryptionBase64, encryptedDataBase64);
  5753. } catch (error) {
  5754. throw new exceptions.CryptoLibException(
  5755. 'Digital envelope could not be opened.', error);
  5756. }
  5757. }
  5758. };
  5759. /**
  5760. * Container class for a digital envelope.
  5761. *
  5762. * @class DigitalEnvelope
  5763. * @param encryptedDataBase64
  5764. * {string} the symmetrically encrypted data, as a string in
  5765. * Base64 encoded format.
  5766. * @param macBase64
  5767. * {string} the MAC of the symmetrically encrypted data, as a
  5768. * string in Base64 encoded format.
  5769. * @param secretKeyEncryptions
  5770. * {SecretKeyEncryption[]} the list of asymmetric encryptions of
  5771. * the secret key concatenation, each encryption having been
  5772. * created using a different one of the public keys provided as
  5773. * input to the digital envelope generator.
  5774. * @memberof digitalenvelope
  5775. */
  5776. function DigitalEnvelope(
  5777. encryptedDataBase64, macBase64, secretKeyEncryptions) {
  5778. this.encryptedDataBase64 = encryptedDataBase64;
  5779. this.macBase64 = macBase64;
  5780. this.secretKeyEncryptions = secretKeyEncryptions;
  5781. var _encryptedSecretKeyConcatsBase64 = [];
  5782. var _publicKeysPem = [];
  5783. for (var i = 0; i < secretKeyEncryptions.length; i++) {
  5784. _encryptedSecretKeyConcatsBase64[i] =
  5785. secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
  5786. _publicKeysPem[i] = secretKeyEncryptions[i].getPublicKey();
  5787. }
  5788. this._getEncryptedSecretKeyConcatsBase64 = function() {
  5789. return _encryptedSecretKeyConcatsBase64;
  5790. };
  5791. this._getPublicKeysPem = function() {
  5792. return _publicKeysPem;
  5793. };
  5794. }
  5795. DigitalEnvelope.prototype = {
  5796. /**
  5797. * @function getEncryptedData
  5798. * @return {string} the symmetrically encrypted data, as a string in
  5799. * Base64 encoded format.
  5800. */
  5801. getEncryptedData: function() {
  5802. return this.encryptedDataBase64;
  5803. },
  5804. /**
  5805. * @function getMac
  5806. * @return {string} the MAC of the symmetrically encrypted data, as a
  5807. * string in Base64 encoded format.
  5808. */
  5809. getMac: function() {
  5810. return this.macBase64;
  5811. },
  5812. /**
  5813. * @function getSecretKeyEncryptions
  5814. * @return {SecretKeyEncryption[]} the list of asymmetric encryptions of
  5815. * the secret key concatenation.
  5816. */
  5817. getSecretKeyEncryptions: function() {
  5818. return this.secretKeyEncryptions;
  5819. },
  5820. /**
  5821. * Generates a string representation of the digital envelope.
  5822. * <p>
  5823. * Note: in order to permit interoperability between libraries, this
  5824. * representation should match the equivalent representation in Java.
  5825. *
  5826. * @function stringify
  5827. * @return {string} the string representation of the digital envelope.
  5828. */
  5829. stringify: function() {
  5830. return JSON.stringify({
  5831. digitalEnvelope: {
  5832. encryptedDataBase64: this.encryptedDataBase64,
  5833. macBase64: this.macBase64,
  5834. encryptedSecretKeyConcatsBase64:
  5835. this._getEncryptedSecretKeyConcatsBase64(),
  5836. publicKeysPem: this._getPublicKeysPem()
  5837. }
  5838. });
  5839. }
  5840. };
  5841. /**
  5842. * Container class for the asymmetric encryption of the bit-wise
  5843. * concatenation of the secret key used to symmetrically encrypt the data of
  5844. * a digital envelope and the secret key used to generate an MAC for
  5845. * checking the integrity of the symmetric encryption. The public key used
  5846. * to perform the asymmetric encryption of the secret key concatenation is
  5847. * also included.
  5848. *
  5849. * @class SecretKeyEncryption
  5850. * @param encryptedSecretKeyConcatBase64
  5851. * {string} the asymmetric encryption of the secret key
  5852. * concatenation, using the public key provided as input, as a
  5853. * string in Base64 encoded format.
  5854. * @param publicKeyPem
  5855. * {string} the public key, of type
  5856. * {@link java.security.PublicKey}, used to asymmetrically
  5857. * encrypt the secret key concatenation.
  5858. * @memberof digitalenvelope
  5859. */
  5860. function SecretKeyEncryption(encryptedSecretKeyConcatBase64, publicKeyPem) {
  5861. /**
  5862. * @function getEncryptedSecretKeyConcatenationBase64
  5863. * @return {string} the asymmetrically encrypted secret key
  5864. * concatenation, as a string in Base64 encoded format.
  5865. */
  5866. var getEncryptedSecretKeyConcatenation = function() {
  5867. return encryptedSecretKeyConcatBase64;
  5868. };
  5869. /**
  5870. * @function getPublicKey
  5871. * @return {string} the public key used to asymmetrically encrypt the
  5872. * secret key concatenation, as a string in PEM format.
  5873. */
  5874. var getPublicKey = function() {
  5875. return publicKeyPem;
  5876. };
  5877. return {
  5878. getEncryptedSecretKeyConcatenation: getEncryptedSecretKeyConcatenation,
  5879. getPublicKey: getPublicKey
  5880. };
  5881. }
  5882. /**
  5883. * Deserializes a digital envelope.
  5884. *
  5885. * @function deserialize
  5886. * @param serializedDigitalEnvelope
  5887. * {string} the serialized digital envelope.
  5888. * @return {DigitalEnvelope} the digital envelope after deserialization.
  5889. * @memberof digitalenvelope
  5890. */
  5891. box.digitalenvelope.deserialize = function(serializedDigitalEnvelope) {
  5892. validateDeserializerInput(serializedDigitalEnvelope);
  5893. var digitalEnvelopeJson =
  5894. JSON.parse(serializedDigitalEnvelope).digitalEnvelope;
  5895. var encryptedDataBase64 = digitalEnvelopeJson.encryptedDataBase64;
  5896. var macBase64 = digitalEnvelopeJson.macBase64;
  5897. var encryptedSecretKeyConcatsBase64 =
  5898. digitalEnvelopeJson.encryptedSecretKeyConcatsBase64;
  5899. var publicKeysPem = digitalEnvelopeJson.publicKeysPem;
  5900. var secretKeyEncryptions = [];
  5901. for (var i = 0; i < encryptedSecretKeyConcatsBase64.length; i++) {
  5902. secretKeyEncryptions.push(new SecretKeyEncryption(
  5903. encryptedSecretKeyConcatsBase64[i], publicKeysPem[i]));
  5904. }
  5905. return new DigitalEnvelope(
  5906. encryptedDataBase64, macBase64, secretKeyEncryptions);
  5907. };
  5908. function validateGeneratorInput(dataBase64, publicKeysPem) {
  5909. if (typeof dataBase64 === 'undefined') {
  5910. throw new exceptions.CryptoLibException(
  5911. 'Data provided to digital envelope generator is undefined.');
  5912. }
  5913. if (converters.base64Decode(dataBase64) === '') {
  5914. throw new exceptions.CryptoLibException(
  5915. 'Data provided to digital envelope generator is empty.');
  5916. }
  5917. if (typeof dataBase64 !== 'string') {
  5918. throw new exceptions.CryptoLibException(
  5919. 'Base64 encoded data provided to digital envelope generator is not a String.');
  5920. }
  5921. if (typeof publicKeysPem === 'undefined') {
  5922. throw new exceptions.CryptoLibException(
  5923. 'Public key array provided to digital envelope generator is undefined.');
  5924. }
  5925. if (!(publicKeysPem instanceof Array)) {
  5926. throw new exceptions.CryptoLibException(
  5927. 'Public key array provided to digital envelope generator is not of type Array.');
  5928. }
  5929. if (publicKeysPem.length === 0) {
  5930. throw new exceptions.CryptoLibException(
  5931. 'Public key array provided to digital envelope generator is empty.');
  5932. }
  5933. }
  5934. function validateOpenerInput(digitalEnvelope, privateKeyPem) {
  5935. if (typeof digitalEnvelope === 'undefined') {
  5936. throw new exceptions.CryptoLibException(
  5937. 'Digital envelope provided to digital envelope opener is undefined.');
  5938. }
  5939. if (!(digitalEnvelope instanceof Object)) {
  5940. throw new exceptions.CryptoLibException(
  5941. 'Digital envelope provided to digital envelope generator is not of type Object.');
  5942. }
  5943. if (typeof privateKeyPem === 'undefined') {
  5944. throw new exceptions.CryptoLibException(
  5945. 'Private key provided to digital envelope opener is undefined.');
  5946. }
  5947. if (typeof privateKeyPem !== 'string') {
  5948. throw new exceptions.CryptoLibException(
  5949. 'Private key PEM provided to digital envelope opener is not of type String.');
  5950. }
  5951. }
  5952. function validateDeserializerInput(serializedDigitalEnvelope) {
  5953. if (typeof serializedDigitalEnvelope === 'undefined') {
  5954. throw new exceptions.CryptoLibException(
  5955. 'Serialized object provided to digital envelope deserializer is undefined.');
  5956. }
  5957. if (typeof serializedDigitalEnvelope !== 'string') {
  5958. throw new exceptions.CryptoLibException(
  5959. 'Serialized object provided to digital envelope deserializer is not of type String.');
  5960. }
  5961. if (serializedDigitalEnvelope.length === 0) {
  5962. throw new exceptions.CryptoLibException(
  5963. 'Serialized object provided to digital envelope deserializer is empty.');
  5964. }
  5965. }
  5966. };
  5967. /*
  5968. * Copyright 2018 Scytl Secure Electronic Voting SA
  5969. *
  5970. * All rights reserved
  5971. *
  5972. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  5973. */
  5974. cryptolib.modules.digitalenvelope = cryptolib.modules.digitalenvelope || {};
  5975. /**
  5976. * Defines the digital envelope service.
  5977. *
  5978. * @namespace digitalenvelope
  5979. */
  5980. cryptolib.modules.digitalenvelope.service = function(box) {
  5981. 'use strict';
  5982. box.digitalenvelope = box.digitalenvelope || {};
  5983. box.digitalenvelope.service = {};
  5984. var digitalEnvelopeFactory;
  5985. cryptolib('digitalenvelope', function(box) {
  5986. digitalEnvelopeFactory =
  5987. new box.digitalenvelope.factory.DigitalEnvelopeFactory();
  5988. });
  5989. /**
  5990. * Creates a digital envelope, using one or more public keys, each of whose
  5991. * corresponding private key can be used to open the envelope and retrieve
  5992. * the data.
  5993. *
  5994. * @function createDigitalEnvelope
  5995. * @param dataBase64
  5996. * {string} the data to store in the digital envelope, as a
  5997. * string in Base64 encoded format.
  5998. * @param publicKeysPem
  5999. * {string[]} a list of one or more public keys used to generate
  6000. * the digital envelope, as an array of strings in PEM format.
  6001. * @return {DigitalEnvelope} the newly created digital envelope.
  6002. */
  6003. box.digitalenvelope.service.createDigitalEnvelope = function(
  6004. dataBase64, publicKeysPem) {
  6005. var generator = digitalEnvelopeFactory.getDigitalEnvelopeGenerator();
  6006. return generator.generate(dataBase64, publicKeysPem);
  6007. };
  6008. /**
  6009. * Opens an existing digital envelope and retrieves the data that it
  6010. * contains. The envelope can be opened with any private key corresponding
  6011. * to a public key that was used to generate the envelope.
  6012. *
  6013. * @function openDigitalEnvelope
  6014. * @param digitalEnvelope
  6015. * {DigitalEnvelope} the digital envelope to open.
  6016. * @param privateKeyPem
  6017. * {string} the private key used to open the digital envelope, as
  6018. * a string in PEM format.
  6019. * @return {string} the data contained in the digital envelope, as a string
  6020. * in Base64 encoded format.
  6021. */
  6022. box.digitalenvelope.service.openDigitalEnvelope = function(
  6023. digitalEnvelope, privateKeyPem) {
  6024. var opener = digitalEnvelopeFactory.getDigitalEnvelopeOpener();
  6025. return opener.open(digitalEnvelope, privateKeyPem);
  6026. };
  6027. };
  6028. /*
  6029. * Copyright 2018 Scytl Secure Electronic Voting SA
  6030. *
  6031. * All rights reserved
  6032. *
  6033. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  6034. */
  6035. cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
  6036. cryptolib.modules.homomorphic.cipher = function(box) {
  6037. 'use strict';
  6038. box.homomorphic = box.homomorphic || {};
  6039. box.homomorphic.cipher = {};
  6040. /**
  6041. * A submodule that holds ElGamal cipher functionalities.
  6042. *
  6043. * @exports homomorphic/cipher/factory
  6044. */
  6045. box.homomorphic.cipher.factory = {};
  6046. var converters, exceptions, randomFactory, mathematical, keyPairFactory;
  6047. var f = function(box) {
  6048. converters = new box.commons.utils.Converters();
  6049. exceptions = box.commons.exceptions;
  6050. mathematical = box.commons.mathematical;
  6051. randomFactory =
  6052. new box.primitives.securerandom.factory.SecureRandomFactory();
  6053. keyPairFactory = new box.homomorphic.keypair.factory.KeyFactory();
  6054. };
  6055. f.policies = {
  6056. primitives: {
  6057. secureRandom:
  6058. {provider: box.policies.homomorphic.cipher.secureRandom.provider}
  6059. }
  6060. };
  6061. cryptolib('commons', 'primitives.securerandom', 'homomorphic.keypair', f);
  6062. /** @class */
  6063. box.homomorphic.cipher.factory.ElGamalCipherFactory = function() {
  6064. };
  6065. box.homomorphic.cipher.factory.ElGamalCipherFactory.prototype = {
  6066. /**
  6067. * @function createEncrypter
  6068. * @returns ElGamalEncrypter
  6069. */
  6070. createEncrypter: function(elGamalPublicKey, cryptoRandomInteger) {
  6071. if (typeof cryptoRandomInteger === 'undefined') {
  6072. cryptoRandomInteger = randomFactory.getCryptoRandomInteger();
  6073. }
  6074. return new ElGamalEncrypter(elGamalPublicKey, cryptoRandomInteger);
  6075. },
  6076. /**
  6077. * @function createDecrypter
  6078. * @returns ElGamalDecrypter
  6079. */
  6080. createDecrypter: function(elGamalPrivateKey) {
  6081. return new ElGamalDecrypter(elGamalPrivateKey);
  6082. },
  6083. /**
  6084. * @function createRandomDecrypter
  6085. * @returns ElGamalRandomDecrypter
  6086. */
  6087. createRandomDecrypter: function(elGamalPublicKey, cryptoRandomInteger) {
  6088. return new ElGamalRandomDecrypter(elGamalPublicKey, cryptoRandomInteger);
  6089. }
  6090. };
  6091. function validateArray(inputArray) {
  6092. if (typeof inputArray === 'undefined') {
  6093. throw new exceptions.CryptoLibException(
  6094. 'The given array should be initialized');
  6095. }
  6096. if (!(inputArray instanceof Array)) {
  6097. throw new exceptions.CryptoLibException(
  6098. 'The given array are not from the expected type');
  6099. }
  6100. if (inputArray === []) {
  6101. throw new exceptions.CryptoLibException(
  6102. 'The given array cannot be empty');
  6103. }
  6104. }
  6105. /**
  6106. * Defines an ElGamal encrypter.
  6107. * <P>
  6108. * The methods specified in this object allow data to be encrypted using an
  6109. * implementation of the ElGamal cryptosystem.
  6110. *
  6111. * @class ElGamalEncrypter
  6112. * @param {ElGamalPublicKey}
  6113. * elGamalPublicKey The public key.
  6114. * @param {Object}
  6115. * cryptoRandomInteger The source of randomness.
  6116. * @returns {ElGamalEncrypter}
  6117. */
  6118. function ElGamalEncrypter(elGamalPublicKey, cryptoRandomInteger) {
  6119. var _elGamalPublicKey = elGamalPublicKey;
  6120. var _cryptoRandomInteger = cryptoRandomInteger;
  6121. /**
  6122. * @function getElGamalPublicKey
  6123. *
  6124. * @returns {ElGamalPublicKey}
  6125. */
  6126. this.getElGamalPublicKey = function() {
  6127. return _elGamalPublicKey;
  6128. };
  6129. /**
  6130. * @function getCryptoRandomInteger
  6131. *
  6132. * @returns {ElGamalPublicKey}
  6133. */
  6134. this.getCryptoRandomInteger = function() {
  6135. return _cryptoRandomInteger;
  6136. };
  6137. // Private methods
  6138. this._validateMessagesNotLargerThanKeySize = function(length) {
  6139. if (_elGamalPublicKey.getGroupElementsArray().length < length) {
  6140. throw new exceptions.CryptoLibException(
  6141. 'The list of messages to encrypt was larger than the number of public key elements.');
  6142. }
  6143. };
  6144. this._validatePrePhisNotLargerThanKeySize = function(phis) {
  6145. if (_elGamalPublicKey.getGroupElementsArray().length < phis.length) {
  6146. throw new exceptions.CryptoLibException(
  6147. 'The list of prePhis was larger than the number of public key elements.');
  6148. }
  6149. };
  6150. this._preCompute = function(useShortExponent) {
  6151. var gamma;
  6152. var prePhis = [];
  6153. try {
  6154. var publicKeyElements = _elGamalPublicKey.getGroupElementsArray();
  6155. var group = _elGamalPublicKey.getGroup();
  6156. if (useShortExponent &&
  6157. !group.isQuadraticResidueGroup()) {
  6158. throw new exceptions.CryptoLibException(
  6159. 'Attempt to ElGamal encrypt using short exponent for Zp subgroup that is not of type quadratic residue.');
  6160. }
  6161. var randomExponent = mathematical.groupUtils.generateRandomExponent(
  6162. group, _cryptoRandomInteger, useShortExponent);
  6163. gamma = group.getGenerator().exponentiate(randomExponent);
  6164. // For each element in the array of public key elements, compute the
  6165. // following: element: prephi[i] = pubKey[i]^(random)
  6166. var pubKeyElementRaised;
  6167. for (var i = 0; i < publicKeyElements.length; i++) {
  6168. pubKeyElementRaised =
  6169. publicKeyElements[i].exponentiate(randomExponent);
  6170. prePhis.push(pubKeyElementRaised);
  6171. }
  6172. return new ElGamalEncrypterValues(randomExponent, gamma, prePhis);
  6173. } catch (error) {
  6174. throw new exceptions.CryptoLibException(
  6175. 'There was an error while precomputing values.', error);
  6176. }
  6177. };
  6178. this._compute = function(messages, computationValues) {
  6179. var compressedComputationValues = compressComputationValuesIfNecessary(
  6180. messages.length, computationValues);
  6181. var phis = [];
  6182. // For each element in the array of messages, compute the following:
  6183. // element:phi[i]=message[i]*prePhi[i]
  6184. for (var i = 0; i < compressedComputationValues.getPhis().length; i++) {
  6185. phis.push(
  6186. messages[i].multiply(compressedComputationValues.getPhis()[i]));
  6187. }
  6188. return new box.homomorphic.cipher.ElGamalComputationValues(
  6189. compressedComputationValues.getGamma(), phis);
  6190. };
  6191. this._getListAsQuadraticResidues = function(messages) {
  6192. var valuesZpSubgroupElements = [];
  6193. var group = _elGamalPublicKey.getGroup();
  6194. var groupElement;
  6195. for (var i = 0; i < messages.length; i++) {
  6196. groupElement = new mathematical.ZpGroupElement(
  6197. new box.forge.jsbn.BigInteger(messages[i]), group.getP(),
  6198. group.getQ());
  6199. valuesZpSubgroupElements.push(groupElement);
  6200. }
  6201. return valuesZpSubgroupElements;
  6202. };
  6203. function compressComputationValuesIfNecessary(
  6204. numMessages, computationValues) {
  6205. var phis = computationValues.getPhis();
  6206. if (phis.length <= numMessages) {
  6207. return computationValues;
  6208. }
  6209. var compressedPhiArray =
  6210. mathematical.groupUtils.buildListWithCompressedFinalElement(
  6211. _elGamalPublicKey.getGroup(), phis, numMessages);
  6212. return new box.homomorphic.cipher.ElGamalComputationValues(
  6213. computationValues.getGamma(), compressedPhiArray);
  6214. }
  6215. }
  6216. ElGamalEncrypter.prototype = {
  6217. /**
  6218. * Encrypt the received list of messages (which are represented as
  6219. * ZpGroupElements).
  6220. * <p>
  6221. * The length of the received list of messages must be equal to, or less
  6222. * than, the length of the public key of this encrypter. If this
  6223. * condition is not met, then an exception will be thrown.
  6224. *
  6225. * @function encryptGroupElements
  6226. *
  6227. * @param {Array}
  6228. * messages an array of ZpGroupElements.
  6229. * @param {Object} [encryptionOption] an optional input parameter. If this option is of type
  6230. * {boolean}, then the encryption will be pre-computed, using
  6231. * the value of the boolean to determine whether or not to
  6232. * use a short random exponent for the pre-computation. If
  6233. * the option is of type {ElGamalEncrypterValues} then it
  6234. * will be used as the pre-computation of the encryption.
  6235. *
  6236. * @returns {ElGamalEncrypterValues}
  6237. */
  6238. encryptGroupElements: function(messages, encryptionOption) {
  6239. validateArray(messages);
  6240. this._validateMessagesNotLargerThanKeySize(messages.length);
  6241. var useShortExponent;
  6242. var preComputedValues;
  6243. if (typeof encryptionOption !== 'undefined' &&
  6244. typeof encryptionOption === 'boolean') {
  6245. useShortExponent = encryptionOption;
  6246. } else {
  6247. preComputedValues = encryptionOption;
  6248. }
  6249. if (!preComputedValues) {
  6250. preComputedValues = this._preCompute(useShortExponent);
  6251. } else {
  6252. var prePhis = preComputedValues.getPhis();
  6253. validateArray(prePhis);
  6254. this._validatePrePhisNotLargerThanKeySize(prePhis);
  6255. }
  6256. var computationValues = this._compute(
  6257. messages, preComputedValues.getElGamalComputationValues());
  6258. return new ElGamalEncrypterValues(
  6259. preComputedValues.getR(), computationValues.getGamma(),
  6260. computationValues.getPhis());
  6261. },
  6262. /**
  6263. * Pre-compute the ElGamal encrypter values, based on the ElGamal public
  6264. * key provided to the encrypter.
  6265. *
  6266. * @param {boolean}
  6267. * [useShortExponent] true if a short exponent is to be used
  6268. * for the pre-computations. Default value is false.
  6269. * @returns {ElGamalEncrypterValues}
  6270. */
  6271. preCompute: function(useShortExponent) {
  6272. return this._preCompute(useShortExponent);
  6273. },
  6274. /**
  6275. * Encrypt the received list of messages (which are represented as
  6276. * Strings).
  6277. * <p>
  6278. * The length of the received list of messages must be equal to, or less
  6279. * than, the length of the public key of this encrypter. If this
  6280. * condition is not met, then an exception will be thrown.
  6281. *
  6282. * @function encryptStrings
  6283. *
  6284. * @param {Array}
  6285. * messages an array of strings.
  6286. * @param {ElGamalEncrypterValues}
  6287. * [preComputedValues] an optional parameter. If it is not
  6288. * provided, then pre-computations are made.
  6289. *
  6290. * @returns {ElGamalEncrypterValues} the pre-computed values.
  6291. */
  6292. encryptStrings: function(messages, preComputedValues) {
  6293. var messagesAsGroupElements = this._getListAsQuadraticResidues(messages);
  6294. if (!preComputedValues) {
  6295. return this.encryptGroupElements(messagesAsGroupElements);
  6296. } else {
  6297. return this.encryptGroupElements(
  6298. messagesAsGroupElements, preComputedValues);
  6299. }
  6300. }
  6301. };
  6302. /**
  6303. * Defines an ElGamal decrypter.
  6304. *
  6305. * @class ElGamalDecrypter
  6306. * @param {ElGamalPrivateKey}
  6307. * elGamalPrivateKey The ElGamal private key.
  6308. * @returns {ElGamalDecrypter}
  6309. */
  6310. function ElGamalDecrypter(elGamalPrivateKey) {
  6311. function validateCorrectGroup(elGamalPrivateKey) {
  6312. var exponentsArray = elGamalPrivateKey.getExponentsArray();
  6313. var group = elGamalPrivateKey.getGroup();
  6314. for (var i = 0; i < exponentsArray.length; i++) {
  6315. if (!(group.getQ().equals(exponentsArray[i].getQ()))) {
  6316. throw new exceptions.CryptoLibException(
  6317. 'Each Exponent must be of the specified group order.');
  6318. }
  6319. }
  6320. }
  6321. validateCorrectGroup(elGamalPrivateKey);
  6322. var _elGamalPrivateKey = elGamalPrivateKey;
  6323. this.getElGamalPrivateKey = function() {
  6324. return _elGamalPrivateKey;
  6325. };
  6326. this._areGroupMembers = function(cipherText) {
  6327. for (var i = 0; i < cipherText.getPhis().length; i++) {
  6328. var next = cipherText.getPhis()[i];
  6329. if (!(_elGamalPrivateKey.getGroup().isGroupMember(next))) {
  6330. return false;
  6331. }
  6332. }
  6333. return true;
  6334. };
  6335. this._validateCiphertextSize = function(cipherText) {
  6336. if (_elGamalPrivateKey.getExponentsArray().length <
  6337. cipherText.getPhis().length) {
  6338. throw new exceptions.CryptoLibException(
  6339. 'The list of ciphertext was larger than the number of private key exponents.');
  6340. }
  6341. };
  6342. this._compressKeyIfNecessary = function(numRequired) {
  6343. var exponents = _elGamalPrivateKey.getExponentsArray();
  6344. var group = _elGamalPrivateKey.getGroup();
  6345. if (exponents.length <= numRequired) {
  6346. return _elGamalPrivateKey;
  6347. }
  6348. var listWithCompressedFinalExponent =
  6349. mathematical.groupUtils.buildListWithCompressedFinalExponent(
  6350. group, exponents, numRequired);
  6351. return keyPairFactory.createPrivateKey(
  6352. listWithCompressedFinalExponent, _elGamalPrivateKey.getGroup());
  6353. };
  6354. }
  6355. ElGamalDecrypter.prototype = {
  6356. /**
  6357. * Decrypts a ciphertext.
  6358. * <P>
  6359. * The encrypted message parameter will be a list of group elements,
  6360. * encapsulated within an ComputationValues object.
  6361. * <P>
  6362. * The length of the received ciphertext (number of group elements
  6363. * contained within it) must be equal to, or less than, the length of
  6364. * the private key of this decrypter. If this condition is not met, then
  6365. * an exception will be thrown.
  6366. *
  6367. * @function decrypt
  6368. *
  6369. * @param {Array}
  6370. * cipherText the encrypted message to be decrypted.
  6371. * @param {Boolean}
  6372. * [confirmGroupMembership] if true, a confirmation is made that
  6373. * each element in
  6374. * {@code ciphertext} is a member of the mathematical group
  6375. * over which this decrypter operates. Default value is false.
  6376. * @returns {Array} the decrypted ciphertext.
  6377. */
  6378. decrypt: function(cipherText, confirmGroupMembership) {
  6379. if (confirmGroupMembership === true &&
  6380. !this._areGroupMembers(cipherText)) {
  6381. throw new exceptions.CryptoLibException(
  6382. 'All values to decrypt must be group elements.');
  6383. }
  6384. this._validateCiphertextSize(cipherText);
  6385. var privateKeyAfterCompression =
  6386. this._compressKeyIfNecessary(cipherText.getPhis().length);
  6387. var plaintext = [];
  6388. var negatedExponent;
  6389. var exponentsArray = privateKeyAfterCompression.getExponentsArray();
  6390. for (var i = 0; i < cipherText.getPhis().length; i++) {
  6391. // Compute the e = negate (-) of privKey[i]
  6392. negatedExponent = exponentsArray[i].negate();
  6393. // Compute dm[i]= gamma^(e) * phi[i]
  6394. plaintext.push(cipherText.getGamma()
  6395. .exponentiate(negatedExponent)
  6396. .multiply(cipherText.getPhis()[i]));
  6397. }
  6398. return plaintext;
  6399. }
  6400. };
  6401. /**
  6402. * Defines an ElGamal decrypter that can be used to decrypt some ciphertext,
  6403. * given the public key and the source of randomness used to generate the
  6404. * ciphertext.
  6405. *
  6406. * @class ElGamalRandomDecrypter
  6407. * @param {ElGamalPublicKey}
  6408. * elGamalPublicKey The ElGamal public key.
  6409. * @param {Object} cryptoRandomInteger The source of randomness.
  6410. * @returns {ElGamalDecrypter} The ElGamal decrypter.
  6411. */
  6412. function ElGamalRandomDecrypter(elGamalPublicKey, cryptoRandomInteger) {
  6413. function validateCorrectGroup(elGamalPublicKey) {
  6414. var elementsArray = elGamalPublicKey.getGroupElementsArray();
  6415. var group = elGamalPublicKey.getGroup();
  6416. for (var i = 0; i < elementsArray.length; i++) {
  6417. if (!(group.getP().equals(elementsArray[i].getP()))) {
  6418. throw new exceptions.CryptoLibException(
  6419. 'Each element must be of the specified group modulus.');
  6420. }
  6421. if (!(group.getQ().equals(elementsArray[i].getQ()))) {
  6422. throw new exceptions.CryptoLibException(
  6423. 'Each element must be of the specified group order.');
  6424. }
  6425. }
  6426. }
  6427. validateCorrectGroup(elGamalPublicKey);
  6428. var _elGamalPublicKey = elGamalPublicKey;
  6429. var _cryptoRandomInteger = cryptoRandomInteger;
  6430. this.getElGamalPublicKey = function() {
  6431. return _elGamalPublicKey;
  6432. };
  6433. this.getCryptoRandomInteger = function() {
  6434. return _cryptoRandomInteger;
  6435. };
  6436. this._areGroupMembers = function(cipherText) {
  6437. for (var i = 0; i < cipherText.getPhis().length; i++) {
  6438. var next = cipherText.getPhis()[i];
  6439. if (!(_elGamalPublicKey.getGroup().isGroupMember(next))) {
  6440. return false;
  6441. }
  6442. }
  6443. return true;
  6444. };
  6445. this._validateCiphertextSize = function(cipherText) {
  6446. if (_elGamalPublicKey.getGroupElementsArray().length <
  6447. cipherText.getPhis().length) {
  6448. throw new exceptions.CryptoLibException(
  6449. 'The list of ciphertext was larger than the number of public key elements.');
  6450. }
  6451. };
  6452. this._compressKeyIfNecessary = function(numRequired) {
  6453. var publicKeyElements = _elGamalPublicKey.getGroupElementsArray();
  6454. var group = _elGamalPublicKey.getGroup();
  6455. if (publicKeyElements.length <= numRequired) {
  6456. return _elGamalPublicKey;
  6457. }
  6458. var listWithCompressedFinalElement =
  6459. mathematical.groupUtils.buildListWithCompressedFinalElement(
  6460. group, publicKeyElements, numRequired);
  6461. return keyPairFactory.createPublicKey(
  6462. listWithCompressedFinalElement, _elGamalPublicKey.getGroup());
  6463. };
  6464. }
  6465. ElGamalRandomDecrypter.prototype = {
  6466. /**
  6467. * Decrypts a ciphertext, using the public key and the source of randomness
  6468. * used to generate the ciphertext. <P> The encrypted message parameter will
  6469. * be a list of group elements, encapsulated within an ComputationValues
  6470. * object. <P> The length of the received ciphertext (number of group
  6471. * elements contained within it) must be equal to, or less than, the length
  6472. * of the public key of this decrypter. If this condition is not met, then
  6473. * an exception will be thrown.
  6474. *
  6475. * @function decrypt
  6476. *
  6477. * @param {Array}
  6478. * cipherText the encrypted message to be decrypted.
  6479. * @param {Boolean}
  6480. * [confirmGroupMembership] if true, a confirmation is made that
  6481. * each element in
  6482. * {@code ciphertext} is a member of the mathematical group
  6483. * over which this decrypter operates. Default value is false.
  6484. * @param {boolean}
  6485. * [useShortExponent] set to true if a short exponent was used
  6486. * for the encryption. Default value is false.
  6487. * @returns {Array} the decrypted messages.
  6488. */
  6489. decrypt: function(cipherText, confirmGroupMembership, useShortExponent) {
  6490. if (confirmGroupMembership === true &&
  6491. !this._areGroupMembers(cipherText)) {
  6492. throw new exceptions.CryptoLibException(
  6493. 'All values to decrypt must be group elements.');
  6494. }
  6495. if (typeof useShortExponent === 'undefined') {
  6496. useShortExponent = false;
  6497. }
  6498. this._validateCiphertextSize(cipherText);
  6499. var publicKeyAfterCompression =
  6500. this._compressKeyIfNecessary(cipherText.getPhis().length);
  6501. var group = publicKeyAfterCompression.getGroup();
  6502. var publicKeyElements = publicKeyAfterCompression.getGroupElementsArray();
  6503. var plaintext = [];
  6504. var negatedExponent;
  6505. var randomExponent = mathematical.groupUtils.generateRandomExponent(
  6506. group, this.getCryptoRandomInteger(), useShortExponent);
  6507. negatedExponent = randomExponent.negate();
  6508. for (var i = 0; i < cipherText.getPhis().length; i++) {
  6509. // Compute dm[i]= publicKeyElement^(-e) * phi[i]
  6510. plaintext.push(publicKeyElements[i]
  6511. .exponentiate(negatedExponent)
  6512. .multiply(cipherText.getPhis()[i]));
  6513. }
  6514. return plaintext;
  6515. }
  6516. };
  6517. /**
  6518. * Class which encapsulates an 'r' value (random exponent) and a set of
  6519. * ElGamal encryption values (a gamma value and a list of phi values).
  6520. *
  6521. * @class ElGamalEncrypterValues
  6522. * @param {Exponent}
  6523. * exponent the Exponent to set.
  6524. * @param {ZpGroupElement}
  6525. * gamma the gamma (first element) of the ciphertext.
  6526. * @param {Array}
  6527. * phis the phi values of the ciphertext.
  6528. * @returns {ElGamalEncrypterValues}
  6529. */
  6530. function ElGamalEncrypterValues(exponent, gamma, phis) {
  6531. var _r = exponent;
  6532. var _gamma = gamma;
  6533. var _phis = phis;
  6534. /**
  6535. * @function
  6536. *
  6537. * @returns {Exponent}
  6538. */
  6539. this.getR = function() {
  6540. return _r;
  6541. };
  6542. /**
  6543. * @function
  6544. *
  6545. * @returns {ZpGroupElement}
  6546. */
  6547. this.getGamma = function() {
  6548. return _gamma;
  6549. };
  6550. /**
  6551. * @function
  6552. *
  6553. * @returns {Array}
  6554. */
  6555. this.getPhis = function() {
  6556. return _phis;
  6557. };
  6558. this.getElGamalComputationValues = function() {
  6559. return new box.homomorphic.cipher.ElGamalComputationValues(_gamma, _phis);
  6560. };
  6561. }
  6562. box.homomorphic.cipher.ElGamalEncrypterValues = ElGamalEncrypterValues;
  6563. /**
  6564. * Encapsulates encryption parameters.
  6565. * <p>
  6566. * These parameters should have been generated as defined below:
  6567. * <ul>
  6568. * <li> For p and q:
  6569. * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
  6570. * <li> For g:
  6571. * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
  6572. * <li> For f:
  6573. * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
  6574. * </ul>
  6575. * <p>
  6576. * Note that p, q, and g are received within the mathematical group.
  6577. *
  6578. *
  6579. * @class EncryptionParameters
  6580. * @param {ZpSubgroup}
  6581. * group the group of the encryption parameters.
  6582. *
  6583. * @returns {EncryptionParameters}
  6584. */
  6585. box.homomorphic.cipher.EncryptionParameters = function(group) {
  6586. var _group = group;
  6587. /**
  6588. * @function
  6589. *
  6590. * @returns {ZpSubgroup}
  6591. */
  6592. this.getEncParamGroup = function() {
  6593. return _group;
  6594. };
  6595. };
  6596. /**
  6597. * Class which encapsulates a gamma and a set of phi values that are Zp
  6598. * subgroup elements.
  6599. *
  6600. * @class ElGamalComputationValues
  6601. * @param {ZpGroupElement}
  6602. * gamma the gamma (first element) of the ciphertext.
  6603. * @param {Array}
  6604. * phis the phi values of the ciphertext.
  6605. */
  6606. box.homomorphic.cipher.ElGamalComputationValues = function(gamma, phis) {
  6607. this._gamma = gamma;
  6608. this._phis = phis;
  6609. };
  6610. box.homomorphic.cipher.ElGamalComputationValues.prototype = {
  6611. getGamma: function() {
  6612. return this._gamma;
  6613. },
  6614. getPhis: function() {
  6615. return this._phis;
  6616. },
  6617. stringify: function() {
  6618. var phis = Array();
  6619. for (var i = 0; i < this._phis.length; i++) {
  6620. phis[i] =
  6621. converters.base64FromBigInteger(this._phis[i].getElementValue());
  6622. }
  6623. return JSON.stringify({
  6624. ciphertext: {
  6625. p: converters.base64FromBigInteger(this._gamma.getP()),
  6626. q: converters.base64FromBigInteger(this._gamma.getQ()),
  6627. gamma: converters.base64FromBigInteger(this._gamma.getElementValue()),
  6628. phis: phis
  6629. }
  6630. });
  6631. }
  6632. };
  6633. box.homomorphic.cipher.deserializeElGamalComputationValues = function(
  6634. serializedObject) {
  6635. var valuesJson = JSON.parse(serializedObject).ciphertext;
  6636. var p = converters.base64ToBigInteger(valuesJson.p);
  6637. var q = converters.base64ToBigInteger(valuesJson.q);
  6638. var gamma = new mathematical.ZpGroupElement(
  6639. converters.base64ToBigInteger(valuesJson.gamma), p, q);
  6640. var phis = [];
  6641. for (var i = 0; i < valuesJson.phis.length; i++) {
  6642. phis.push(new mathematical.ZpGroupElement(
  6643. converters.base64ToBigInteger(valuesJson.phis[i]), p, q));
  6644. }
  6645. return new box.homomorphic.cipher.ElGamalComputationValues(gamma, phis);
  6646. };
  6647. };
  6648. /*
  6649. * Copyright 2018 Scytl Secure Electronic Voting SA
  6650. *
  6651. * All rights reserved
  6652. *
  6653. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  6654. */
  6655. cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
  6656. cryptolib.modules.homomorphic.keypair = function(box) {
  6657. 'use strict';
  6658. box.homomorphic = box.homomorphic || {};
  6659. box.homomorphic.keypair = {};
  6660. /**
  6661. * A submodule that holds ElGamal key pair functionalities.
  6662. * @exports homomorphic/keypair/factory
  6663. */
  6664. box.homomorphic.keypair.factory = {};
  6665. var converters;
  6666. var mathematical;
  6667. var f = function(box) {
  6668. converters = new box.commons.utils.Converters();
  6669. mathematical = box.commons.mathematical;
  6670. };
  6671. cryptolib('commons.exceptions', 'commons.utils', 'commons.mathematical', f);
  6672. /** @class */
  6673. box.homomorphic.keypair.factory.KeyFactory = function() {
  6674. };
  6675. box.homomorphic.keypair.factory.KeyFactory.prototype = {
  6676. /**
  6677. * @function
  6678. * @returns ElGamalKeyPair
  6679. */
  6680. createKeyPair: function(elGamalPublicKey, elGamalPrivateKey) {
  6681. return new ElGamalKeyPair(elGamalPublicKey, elGamalPrivateKey);
  6682. },
  6683. /**
  6684. * @function
  6685. * @returns ElGamalPublicKey
  6686. */
  6687. createPublicKey: function(
  6688. serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup) {
  6689. return new ElGamalPublicKey(
  6690. serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup);
  6691. },
  6692. /**
  6693. * @function
  6694. * @returns ElGamalPrivateKey
  6695. */
  6696. createPrivateKey: function(
  6697. serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup) {
  6698. return new ElGamalPrivateKey(
  6699. serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup);
  6700. }
  6701. };
  6702. /**
  6703. * Representation of an ElGamal key pair. This key pair is composed of a
  6704. * private key and a public key.
  6705. * @class ElGamalKeyPair
  6706. * @param elGamalPublicKey
  6707. * ElGamal public key.
  6708. * @param elGamalPrivateKey
  6709. * ElGamal private key.
  6710. * @returns {ElGamalKeyPair}
  6711. */
  6712. function ElGamalKeyPair(elGamalPublicKey, elGamalPrivateKey) {
  6713. var _elGamalPublicKey = elGamalPublicKey;
  6714. var _elGamalPrivateKey = elGamalPrivateKey;
  6715. this.getPublicKey = function() {
  6716. return _elGamalPublicKey;
  6717. };
  6718. this.getPrivateKey = function() {
  6719. return _elGamalPrivateKey;
  6720. };
  6721. }
  6722. /**
  6723. * Encapsulates an ElGamal public key.
  6724. * <P>
  6725. * This class includes the key itself (which is actually a list of
  6726. * elements), as well as the mathematical group that this key belongs to.
  6727. * @class ElGamalPublicKey
  6728. * @param {String_or_Array} serializedElGamalPublicKeyB64OrListOfGroupElements
  6729. * this parameter can be either a string containing the
  6730. * serialized ElGamal public key to JSON string, or an array of
  6731. * ZpGroupElement.
  6732. * @param {ZpSubgroup} keyGroup
  6733. * the ZpSubgroup of the public key.
  6734. * @returns {ElGamalPublicKey}
  6735. */
  6736. function ElGamalPublicKey(
  6737. serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup) {
  6738. var _group;
  6739. var _groupElementsArray = [];
  6740. var _fromJson = function(serializedElGamalPublicKey) {
  6741. var parsedPublicKey = JSON.parse(serializedElGamalPublicKey).publicKey;
  6742. var p = converters.base64ToBigInteger(
  6743. parsedPublicKey.zpSubgroup.p.toString());
  6744. var q = converters.base64ToBigInteger(
  6745. parsedPublicKey.zpSubgroup.q.toString());
  6746. var generator = converters.base64ToBigInteger(
  6747. parsedPublicKey.zpSubgroup.g.toString());
  6748. _group = new mathematical.ZpSubgroup(generator, p, q);
  6749. for (var i = 0; i < parsedPublicKey.elements.length; i++) {
  6750. var elementValue =
  6751. converters.base64ToBigInteger(parsedPublicKey.elements[i]);
  6752. var element = new mathematical.ZpGroupElement(
  6753. elementValue, _group.getP(), _group.getQ());
  6754. _groupElementsArray.push(element);
  6755. }
  6756. };
  6757. if (typeof keyGroup === 'undefined') {
  6758. var serializedElGamalPublicKey = converters.base64Decode(
  6759. serializedElGamalPublicKeyB64OrListOfGroupElements);
  6760. _fromJson(serializedElGamalPublicKey);
  6761. } else {
  6762. _groupElementsArray = serializedElGamalPublicKeyB64OrListOfGroupElements;
  6763. _group = keyGroup;
  6764. }
  6765. this.getGroup = function() {
  6766. return _group;
  6767. };
  6768. this.getGroupElementsArray = function() {
  6769. return _groupElementsArray;
  6770. };
  6771. }
  6772. /**
  6773. * Encapsulates an ElGamal private key.
  6774. * <P>
  6775. * This class includes the key itself (which is actually a list of
  6776. * exponents), as well as the mathematical group that this key belongs to.
  6777. * @class ElGamalPrivateKey
  6778. * @param {String_or_Array} serializedElGamalPrivateKeyB64OrListOfExponents
  6779. * this parameter can be either a string containing the
  6780. * serialized to JSON string ElGamal private key
  6781. * or an array of Exponents.
  6782. * @param {ZpSubgroup} keyGroup
  6783. * the ZpSubgroup of the private key.
  6784. * @returns {ElGamalPrivateKey}
  6785. */
  6786. function ElGamalPrivateKey(
  6787. serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup) {
  6788. var _group;
  6789. var _exponentsArray = [];
  6790. var _fromJson = function(serializedElGamalPrivateKey) {
  6791. var parsedPrivateKey = JSON.parse(serializedElGamalPrivateKey).privateKey;
  6792. var p = converters.base64ToBigInteger(
  6793. parsedPrivateKey.zpSubgroup.p.toString());
  6794. var q = converters.base64ToBigInteger(
  6795. parsedPrivateKey.zpSubgroup.q.toString());
  6796. var generator = converters.base64ToBigInteger(
  6797. parsedPrivateKey.zpSubgroup.g.toString());
  6798. _group = new mathematical.ZpSubgroup(generator, p, q);
  6799. for (var i = 0; i < parsedPrivateKey.exponents.length; i++) {
  6800. var exponentValue =
  6801. converters.base64ToBigInteger(parsedPrivateKey.exponents[i]);
  6802. var exponent = new mathematical.Exponent(_group.getQ(), exponentValue);
  6803. _exponentsArray.push(exponent);
  6804. }
  6805. };
  6806. if (typeof keyGroup === 'undefined') {
  6807. var serializedElGamalPrivateKey = converters.base64Decode(
  6808. serializedElGamalPrivateKeyB64OrListOfExponents);
  6809. _fromJson(serializedElGamalPrivateKey);
  6810. } else {
  6811. _exponentsArray = serializedElGamalPrivateKeyB64OrListOfExponents;
  6812. _group = keyGroup;
  6813. }
  6814. this.getGroup = function() {
  6815. return _group;
  6816. };
  6817. this.getExponentsArray = function() {
  6818. return _exponentsArray;
  6819. };
  6820. }
  6821. };
  6822. /*
  6823. * Copyright 2018 Scytl Secure Electronic Voting SA
  6824. *
  6825. * All rights reserved
  6826. *
  6827. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  6828. */
  6829. cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
  6830. cryptolib.modules.homomorphic.service = function(box) {
  6831. 'use strict';
  6832. box.homomorphic = box.homomorphic || {};
  6833. /**
  6834. * A module that provides high-level ElGamal cryptographic services.
  6835. *
  6836. * @exports homomorphic/service
  6837. */
  6838. box.homomorphic.service = {};
  6839. var elGamalFactory;
  6840. var keyFactory;
  6841. cryptolib('homomorphic.cipher', 'homomorphic.keypair', function(box) {
  6842. elGamalFactory = new box.homomorphic.cipher.factory.ElGamalCipherFactory();
  6843. keyFactory = new box.homomorphic.keypair.factory.KeyFactory();
  6844. });
  6845. /**
  6846. * @function createElGamalKeyPair
  6847. * @param elGamalPublicKey
  6848. * {Object} an ElGamal public key.
  6849. * @param elGamalPrivateKey
  6850. * {Object} an ElGamal private key.
  6851. *
  6852. * @returns {Object} an object of ElGamalKeyPair.
  6853. */
  6854. box.homomorphic.service.createElGamalKeyPair = function(
  6855. elGamalPublicKey, elGamalPrivateKey) {
  6856. return keyFactory.createKeyPair(elGamalPublicKey, elGamalPrivateKey);
  6857. };
  6858. /**
  6859. * @function createElGamalPublicKey
  6860. * @param serializedElGamalPublicKeyB64
  6861. * {String] a serialized ElGamalPublicKey, in base 64 encoded
  6862. * format.
  6863. *
  6864. * @returns {Object} a ElGamalPublicKey, as an object.
  6865. */
  6866. box.homomorphic.service.createElGamalPublicKey = function(
  6867. serializedElGamalPublicKeyB64) {
  6868. return keyFactory.createPublicKey(serializedElGamalPublicKeyB64);
  6869. };
  6870. /**
  6871. * @function createElGamalPrivateKey
  6872. * @param serializedElGamalPrivateKeyB64
  6873. * {String} a serialized ElGamalPrivateKey, in base 64 encoded
  6874. * format.
  6875. *
  6876. * @returns {Object} a ElGamalPrivateKey, as an object.
  6877. */
  6878. box.homomorphic.service.createElGamalPrivateKey = function(
  6879. serializedElGamalPrivateKeyB64) {
  6880. return keyFactory.createPrivateKey(serializedElGamalPrivateKeyB64);
  6881. };
  6882. /**
  6883. * @function createEncrypter
  6884. * @param elGamalPublicKey
  6885. * {Object} a public key, as an ElGamalPublicKey object.
  6886. * @param [cryptoRandomInteger] {Object} an optional parameter to set the
  6887. * source of randomness for the generation of the ElGamal encryption
  6888. * exponent. If not provided, the source will be created internally.
  6889. *
  6890. * @returns {Object} an ElGamalEncrypter.
  6891. */
  6892. box.homomorphic.service.createEncrypter = function(
  6893. elGamalPublicKey, cryptoRandomInteger) {
  6894. return elGamalFactory.createEncrypter(
  6895. elGamalPublicKey, cryptoRandomInteger);
  6896. };
  6897. /**
  6898. * @function createDecrypter
  6899. * @param elGamalPrivateKey
  6900. * {Object} a private key, as an ElGamalPrivateKey object.
  6901. *
  6902. * @returns {Object} an ElGamalDecrypter.
  6903. */
  6904. box.homomorphic.service.createDecrypter = function(elGamalPrivateKey) {
  6905. return elGamalFactory.createDecrypter(elGamalPrivateKey);
  6906. };
  6907. /**
  6908. * @function createRandomDecrypter
  6909. * @param elGamalPublicKey
  6910. * {Object} a public key, as an ElGamalPublicKey object.
  6911. * @param cryptoRandomInteger {Object} the
  6912. * source of randomness for the generation of the ElGamal encryption
  6913. * exponent.
  6914. * @returns {Object} an ElGamalRandomDecrypter.
  6915. */
  6916. box.homomorphic.service.createRandomDecrypter = function(
  6917. elGamalPublicKey, cryptoRandomInteger) {
  6918. return elGamalFactory.createRandomDecrypter(
  6919. elGamalPublicKey, cryptoRandomInteger);
  6920. };
  6921. };
  6922. /*
  6923. * Copyright 2018 Scytl Secure Electronic Voting SA
  6924. *
  6925. * All rights reserved
  6926. *
  6927. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  6928. */
  6929. cryptolib.modules.primitives = cryptolib.modules.primitives || {};
  6930. /** @namespace primitives/derivation */
  6931. cryptolib.modules.primitives.derivation = function(box) {
  6932. 'use strict';
  6933. box.primitives = box.primitives || {};
  6934. box.primitives.derivation = {};
  6935. /**
  6936. * A module that holds derivation functionalities.
  6937. *
  6938. * @exports primitives/derivation
  6939. */
  6940. box.primitives.derivation.factory = {};
  6941. var policies = {
  6942. pbkdf: {
  6943. provider: box.policies.primitives.derivation.pbkdf.provider,
  6944. hash: box.policies.primitives.derivation.pbkdf.hash,
  6945. saltLengthBytes: box.policies.primitives.derivation.pbkdf.saltLengthBytes,
  6946. keyLengthBytes: box.policies.primitives.derivation.pbkdf.keyLengthBytes,
  6947. iterations: box.policies.primitives.derivation.pbkdf.iterations
  6948. }
  6949. };
  6950. var exceptions, converters;
  6951. cryptolib('rnd', 'commons', function(box) {
  6952. exceptions = box.commons.exceptions;
  6953. converters = new box.commons.utils.Converters();
  6954. });
  6955. /**
  6956. * A factory class for generating {@link CryptoForgePBKDFSecretKeyGenerator}
  6957. * objects.
  6958. *
  6959. * @class
  6960. */
  6961. box.primitives.derivation.factory.SecretKeyGeneratorFactory = function() {
  6962. };
  6963. box.primitives.derivation.factory.SecretKeyGeneratorFactory.prototype = {
  6964. /**
  6965. * Creates a generator for deriving passwords.
  6966. *
  6967. * @function
  6968. * @returns {primitives/derivation.CryptoForgePBKDFSecretKeyGenerator} a
  6969. * {@link primitives/derivation.CryptoForgePBKDFSecretKeyGenerator}
  6970. * object.
  6971. */
  6972. createPBKDF: function() {
  6973. var provider = policies.pbkdf.provider;
  6974. try {
  6975. if (provider === Config.primitives.derivation.pbkdf.provider.FORGE) {
  6976. return new CryptoForgePBKDFSecretKeyGenerator();
  6977. } else {
  6978. throw new exceptions.CryptoLibException(
  6979. 'The specified provider ' + provider + ' is not supported.');
  6980. }
  6981. } catch (error) {
  6982. throw new exceptions.CryptoLibException(
  6983. 'A CryptoPBKDFSecretKeyGenerator object could not be created.',
  6984. error);
  6985. }
  6986. }
  6987. };
  6988. /**
  6989. *
  6990. * @class
  6991. * @memberof primitives/derivation
  6992. */
  6993. function CryptoForgePBKDFSecretKeyGenerator() {
  6994. validateHash(policies.pbkdf.hash);
  6995. validateKeyLengthBytes(policies.pbkdf.keyLengthBytes);
  6996. validateSaltLengthBytes(policies.pbkdf.saltLengthBytes);
  6997. validateIterations(policies.pbkdf.iterations);
  6998. this.keyLengthBytes = policies.pbkdf.keyLengthBytes;
  6999. }
  7000. CryptoForgePBKDFSecretKeyGenerator.prototype = {
  7001. /**
  7002. * @param {string}
  7003. * password the password, as a string of bytes in Base64
  7004. * encoded format.
  7005. * @param {string}
  7006. * salt the salt, as a string of bytes in Base64 encoded
  7007. * format. Note that the salt length should coincide with the
  7008. * one required by the hash algorithm.
  7009. *
  7010. * @return {string} the derived key, as a string of bytes in Base64
  7011. * encoded format.
  7012. */
  7013. generateSecret: function(passwordB64, saltB64) {
  7014. var password = converters.base64Decode(passwordB64);
  7015. var salt = converters.base64Decode(saltB64);
  7016. if (salt.length < policies.pbkdf.saltLengthBytes) {
  7017. throw new exceptions.CryptoLibException(
  7018. 'The salt byte length ' + salt.length +
  7019. ' is less than the minimum allowed salt length ' +
  7020. policies.pbkdf.saltLengthBytes +
  7021. ' set by the cryptographic policy.');
  7022. }
  7023. var derivedKey = sjcl.misc.pbkdf2(
  7024. password, sjcl.codec.base64.toBits(saltB64),
  7025. policies.pbkdf.iterations, this.keyLengthBytes * 8,
  7026. hashCallback(policies.pbkdf.hash));
  7027. return sjcl.codec.base64.fromBits(derivedKey);
  7028. }
  7029. };
  7030. function hashCallback(algorithm) {
  7031. if (algorithm === Config.primitives.derivation.pbkdf.hash.SHA256) {
  7032. return null;
  7033. } else {
  7034. throw new exceptions.CryptoLibException(
  7035. 'Hash algorithm \'' + algorithm + '\' is unsupported');
  7036. }
  7037. }
  7038. function validateHash(hash) {
  7039. var supportedHashAlgorithms =
  7040. [Config.primitives.derivation.pbkdf.hash.SHA256];
  7041. if (supportedHashAlgorithms.indexOf(hash) < 0) {
  7042. throw new exceptions.CryptoLibException(
  7043. 'The specified hash algorithm ' + hash +
  7044. ' is not one of the supported options: ' + supportedHashAlgorithms);
  7045. }
  7046. }
  7047. function validateSaltLengthBytes(saltLengthBytes) {
  7048. var supportedSaltLengthBytes = [
  7049. Config.primitives.derivation.pbkdf.saltLengthBytes.SL_20,
  7050. Config.primitives.derivation.pbkdf.saltLengthBytes.SL_32
  7051. ];
  7052. if (typeof saltLengthBytes !== 'number' || saltLengthBytes % 1 !== 0 ||
  7053. saltLengthBytes < 0) {
  7054. throw new exceptions.CryptoLibException(
  7055. 'The specified salt byte length ' + saltLengthBytes +
  7056. ' is not a positive integer.');
  7057. }
  7058. if (supportedSaltLengthBytes.indexOf(saltLengthBytes) < 0) {
  7059. throw new exceptions.CryptoLibException(
  7060. 'The specified salt byte length ' + saltLengthBytes +
  7061. ' is not one of the supported options: ' + supportedSaltLengthBytes);
  7062. }
  7063. }
  7064. function validateKeyLengthBytes(keyLengthBytes) {
  7065. var supportedKeyLengthBytes = [
  7066. Config.primitives.derivation.pbkdf.keyLengthBytes.KL_16,
  7067. Config.primitives.derivation.pbkdf.keyLengthBytes.KL_32
  7068. ];
  7069. if (typeof keyLengthBytes !== 'number' || keyLengthBytes % 1 !== 0 ||
  7070. keyLengthBytes < 0) {
  7071. throw new exceptions.CryptoLibException(
  7072. 'The specified key byte length ' + keyLengthBytes +
  7073. ' is not a positive number.');
  7074. }
  7075. if (supportedKeyLengthBytes.indexOf(keyLengthBytes) < 0) {
  7076. throw new exceptions.CryptoLibException(
  7077. 'The specified key byte length ' + keyLengthBytes +
  7078. ' is not one of the supported options: ' + supportedKeyLengthBytes);
  7079. }
  7080. }
  7081. function validateIterations(iterations) {
  7082. var supportedIterations = [
  7083. Config.primitives.derivation.pbkdf.iterations.I_1,
  7084. Config.primitives.derivation.pbkdf.iterations.I_8000,
  7085. Config.primitives.derivation.pbkdf.iterations.I_16000,
  7086. Config.primitives.derivation.pbkdf.iterations.I_32000,
  7087. Config.primitives.derivation.pbkdf.iterations.I_64000
  7088. ];
  7089. if (typeof iterations !== 'number' || iterations % 1 !== 0 ||
  7090. iterations < 0) {
  7091. throw new exceptions.CryptoLibException(
  7092. 'The specified number of iterations ' + iterations +
  7093. ' is not a positive integer.');
  7094. }
  7095. if (supportedIterations.indexOf(iterations) < 0) {
  7096. throw new exceptions.CryptoLibException(
  7097. 'The specified number of iterations ' + iterations +
  7098. ' is not one of the supported options: ' + supportedIterations);
  7099. }
  7100. }
  7101. };
  7102. /*
  7103. * Copyright 2018 Scytl Secure Electronic Voting SA
  7104. *
  7105. * All rights reserved
  7106. *
  7107. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7108. */
  7109. cryptolib.modules.primitives = cryptolib.modules.primitives || {};
  7110. /**
  7111. * @namespace primitives/messagedigest
  7112. */
  7113. cryptolib.modules.primitives.messagedigest = function(box) {
  7114. 'use strict';
  7115. box.primitives = box.primitives || {};
  7116. box.primitives.messagedigest = box.primitives.messagedigest || {};
  7117. /**
  7118. * A module that holds message digest functionalities.
  7119. * @exports primitives/messagedigest
  7120. */
  7121. box.primitives.messagedigest.factory =
  7122. box.primitives.messagedigest.factory || {};
  7123. var policies = {
  7124. messagedigest: {
  7125. algorithm: box.policies.primitives.messagedigest.algorithm,
  7126. provider: box.policies.primitives.messagedigest.provider
  7127. }
  7128. };
  7129. var converters, exceptions;
  7130. cryptolib('commons', function(box) {
  7131. converters = new box.commons.utils.Converters();
  7132. exceptions = box.commons.exceptions;
  7133. });
  7134. /**
  7135. * A factory class for creating a message digest generator and verifier.
  7136. * @class
  7137. */
  7138. box.primitives.messagedigest.factory.MessageDigestFactory = function() {};
  7139. box.primitives.messagedigest.factory.MessageDigestFactory.prototype = {
  7140. /**
  7141. * Gets a message dister object.
  7142. * @function
  7143. * @returns {primitives/messagedigest.CryptoForgeMessageDigest}
  7144. */
  7145. getCryptoMessageDigest: function() {
  7146. try {
  7147. if (policies.messagedigest.provider ===
  7148. Config.primitives.messagedigest.provider.FORGE) {
  7149. return this.getCryptoForgeMessageDigest();
  7150. } else {
  7151. throw new exceptions.CryptoLibException(
  7152. 'No suitable provider was provided.');
  7153. }
  7154. } catch (error) {
  7155. throw new exceptions.CryptoLibException(
  7156. 'A CryptoSymmetricCipher could not be obtained.', error);
  7157. }
  7158. },
  7159. getCryptoForgeMessageDigest: function() {
  7160. return new CryptoForgeMessageDigest();
  7161. }
  7162. };
  7163. /**
  7164. * Defines a message digest hash function.
  7165. * @class
  7166. * @memberof primitives/messagedigest
  7167. */
  7168. function CryptoForgeMessageDigest() {
  7169. this.digester = null;
  7170. try {
  7171. if (policies.messagedigest.algorithm ===
  7172. Config.primitives.messagedigest.algorithm.SHA256) {
  7173. this.digester = forge.md.sha256.create();
  7174. } else if (
  7175. policies.messagedigest.algorithm ===
  7176. Config.primitives.messagedigest.algorithm.SHA512_224) {
  7177. this.digester = forge.md.sha512.sha224.create();
  7178. } else {
  7179. var errorMessage = 'Message digester type \'' +
  7180. policies.messagedigest.algorithm +
  7181. '\' not recognized by CryptoForgeMessageDigest.';
  7182. throw new exceptions.CryptoLibException(errorMessage);
  7183. }
  7184. } catch (error) {
  7185. throw new exceptions.CryptoLibException(
  7186. 'CryptoForgeMessageDigest could not be created.', error);
  7187. }
  7188. }
  7189. CryptoForgeMessageDigest.prototype = {
  7190. /**
  7191. * Initializes the message digest generator.
  7192. * @function
  7193. */
  7194. start: function() {
  7195. try {
  7196. this.digester.start();
  7197. } catch (error) {
  7198. throw new exceptions.CryptoLibException(
  7199. 'Message digest could not be initialized.', error);
  7200. }
  7201. },
  7202. /**
  7203. * Updates the message digest generator.
  7204. * @function
  7205. * @param {Array} arrayDataBase64
  7206. * data to compute the hash, as an array of string in Base64
  7207. * encoded format.
  7208. */
  7209. update: function(arrayDataBase64) {
  7210. try {
  7211. if (!arrayDataBase64 || arrayDataBase64.length < 1) {
  7212. throw new exceptions.CryptoLibException(
  7213. 'The array of data in Base64 should contain at least one element.');
  7214. }
  7215. for (var i = 0; i < arrayDataBase64.length; i++) {
  7216. this.digester.update(converters.base64Decode(arrayDataBase64[i]));
  7217. }
  7218. } catch (error) {
  7219. throw new exceptions.CryptoLibException(
  7220. 'Message digest could not be updated.', error);
  7221. }
  7222. },
  7223. /**
  7224. * Generates the message digest for the updated data.
  7225. * @function
  7226. * @returns {string} Message digest, as string in Base64 encoded format.
  7227. */
  7228. digest: function() {
  7229. try {
  7230. var messageDigest = this.digester.digest();
  7231. var rawOutput = messageDigest.getBytes();
  7232. var encodedOutput = converters.base64Encode(rawOutput);
  7233. return encodedOutput;
  7234. } catch (error) {
  7235. throw new exceptions.CryptoLibException(
  7236. 'Message digest could not be generated.', error);
  7237. }
  7238. }
  7239. };
  7240. };
  7241. /*
  7242. * Copyright 2018 Scytl Secure Electronic Voting SA
  7243. *
  7244. * All rights reserved
  7245. *
  7246. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7247. */
  7248. cryptolib.modules.primitives = cryptolib.modules.primitives || {};
  7249. /**
  7250. * @namespace primitives/securerandom
  7251. */
  7252. cryptolib.modules.primitives.securerandom = function(box) {
  7253. 'use strict';
  7254. box.primitives = box.primitives || {};
  7255. box.primitives.securerandom = {};
  7256. /**
  7257. * A module that holds secure random functionalities.
  7258. *
  7259. * @exports primitives/securerandom
  7260. */
  7261. box.primitives.securerandom.factory = {};
  7262. var policies = {
  7263. secureRandom: {provider: box.policies.primitives.secureRandom.provider}
  7264. };
  7265. var converters, exceptions;
  7266. cryptolib('commons', function(box) {
  7267. converters = new box.commons.utils.Converters();
  7268. exceptions = box.commons.exceptions;
  7269. });
  7270. /**
  7271. * A factory class for creating random generators.
  7272. *
  7273. * @class
  7274. */
  7275. box.primitives.securerandom.factory.SecureRandomFactory = function() {
  7276. };
  7277. box.primitives.securerandom.factory.SecureRandomFactory.prototype = {
  7278. /**
  7279. * Instantiates a random byte generator.
  7280. *
  7281. * @function
  7282. * @returns {primitives/securerandom.CryptoScytlRandomBytes}
  7283. */
  7284. getCryptoRandomBytes: function() {
  7285. try {
  7286. if (policies.secureRandom.provider ===
  7287. Config.primitives.secureRandom.provider.SCYTL) {
  7288. return this.getCryptoScytlRandomBytes();
  7289. } else {
  7290. throw new exceptions.CryptoLibException(
  7291. 'No suitable provider was provided.');
  7292. }
  7293. } catch (error) {
  7294. throw new exceptions.CryptoLibException(
  7295. 'A CryptoRandomBytes could not be obtained.', error);
  7296. }
  7297. },
  7298. /**
  7299. * Instantiates a Scytl random byte generator.
  7300. *
  7301. * @function
  7302. * @returns {primitives/securerandom.CryptoScytlRandomBytes}
  7303. */
  7304. getCryptoScytlRandomBytes: function() {
  7305. return new CryptoScytlRandomBytes();
  7306. },
  7307. /**
  7308. * Instantiates a random integer generator.
  7309. *
  7310. * @function
  7311. * @returns {primitives/securerandom.CryptoScytlRandomBytes}
  7312. */
  7313. getCryptoRandomInteger: function() {
  7314. try {
  7315. if (policies.secureRandom.provider ===
  7316. Config.primitives.secureRandom.provider.SCYTL) {
  7317. return this.getCryptoScytlRandomInteger();
  7318. } else {
  7319. throw new exceptions.CryptoLibException(
  7320. 'No suitable provider was provided.');
  7321. }
  7322. } catch (error) {
  7323. throw new exceptions.CryptoLibException(
  7324. 'A CryptoRandomBytes could not be obtained.', error);
  7325. }
  7326. },
  7327. /**
  7328. * Instantiates a Scytl random integer generator.
  7329. *
  7330. * @function
  7331. * @returns {primitives/securerandom.CryptoScytlRandomBytes}
  7332. */
  7333. getCryptoScytlRandomInteger: function() {
  7334. return new CryptoScytlRandomInteger();
  7335. }
  7336. };
  7337. var validate = function(length) {
  7338. try {
  7339. if (typeof length !== 'number') {
  7340. throw new exceptions.CryptoLibException(
  7341. 'The given length is not a number');
  7342. }
  7343. if (length < 1) {
  7344. throw new exceptions.CryptoLibException(
  7345. 'The given length should be a strictly positive integer.');
  7346. }
  7347. if (length > box.MAXIMUM_LENGTH_TO_GENERATE_DATA) {
  7348. throw new exceptions.CryptoLibException(
  7349. 'The given length should be lower than or equal to ' +
  7350. box.MAXIMUM_LENGTH_TO_GENERATE_DATA);
  7351. }
  7352. } catch (error) {
  7353. throw new exceptions.CryptoLibException(
  7354. 'Random generation failed.', error);
  7355. }
  7356. };
  7357. /**
  7358. * The SCYTL Bytes Random Generator
  7359. *
  7360. * @class
  7361. * @memberof primitives/securerandom
  7362. */
  7363. function CryptoScytlRandomBytes() {}
  7364. CryptoScytlRandomBytes.prototype = {
  7365. /**
  7366. * Generates secure random bytes.
  7367. *
  7368. * @function
  7369. * @param {number}
  7370. * numBytes number of bytes to be generated..
  7371. * @returns {string} secure random string.
  7372. */
  7373. nextRandom: function(length) {
  7374. validate(length);
  7375. var randomBytes = box.prng.generate(length);
  7376. return randomBytes.toString();
  7377. },
  7378. /**
  7379. * Method to be compliant with the Forge library.
  7380. *
  7381. * @function
  7382. * @param {number}
  7383. * numBytes number of bytes to be generated..
  7384. * @returns {string} secure random string.
  7385. */
  7386. getBytesSync: function(length) {
  7387. return this.nextRandom(length);
  7388. }
  7389. };
  7390. /**
  7391. * The SCYTL Integer Random Generator
  7392. *
  7393. * @class
  7394. * @memberof primitives/securerandom
  7395. */
  7396. function CryptoScytlRandomInteger() {}
  7397. CryptoScytlRandomInteger.prototype = {
  7398. /**
  7399. * Generates a secure random big integer (Forge).
  7400. *
  7401. * @function
  7402. * @params {number} length the bit length of the random integer.
  7403. * @returns {object} secure random big integer.
  7404. */
  7405. nextRandom: function(length) {
  7406. validate(length);
  7407. var n = ((new box.forge.jsbn.BigInteger('10')).pow(length))
  7408. .subtract(box.forge.jsbn.BigInteger.ONE);
  7409. var bitLength = n.bitLength();
  7410. var numberOfBytes = bitLength / box.NUMBER_OF_BITS_PER_BYTE;
  7411. numberOfBytes = Math.floor(numberOfBytes);
  7412. var modBytes = bitLength % box.NUMBER_OF_BITS_PER_BYTE;
  7413. if (modBytes !== 0) {
  7414. numberOfBytes++;
  7415. }
  7416. var generatedInteger;
  7417. do {
  7418. var randomBytes = box.prng.generate(numberOfBytes);
  7419. randomBytes = '\x00' + randomBytes;
  7420. randomBytes = converters.bytesFromString(randomBytes);
  7421. generatedInteger = new box.forge.jsbn.BigInteger(randomBytes);
  7422. } while ((generatedInteger.compareTo(forge.jsbn.BigInteger.ZERO) <= 0) ||
  7423. (generatedInteger.compareTo(n) > 0));
  7424. return generatedInteger;
  7425. },
  7426. /**
  7427. * Generates a secure random big integer according to the specified bit
  7428. * length.
  7429. *
  7430. * @function
  7431. * @params {number} bitsLength the bit length of the random integer.
  7432. * @returns {object} Secure random big integer.
  7433. */
  7434. nextRandomByBits: function(bitsLength) {
  7435. var byteLength = Math.ceil(bitsLength / box.NUMBER_OF_BITS_PER_BYTE);
  7436. var modBytes = box.NUMBER_OF_BITS_PER_BYTE -
  7437. (bitsLength % box.NUMBER_OF_BITS_PER_BYTE);
  7438. var randomBytes = box.prng.generate(byteLength);
  7439. randomBytes = '\x00' + randomBytes;
  7440. randomBytes = converters.bytesFromString(randomBytes);
  7441. var generatedInteger = new box.forge.jsbn.BigInteger(randomBytes);
  7442. generatedInteger = generatedInteger.shiftRight(modBytes);
  7443. return generatedInteger;
  7444. }
  7445. };
  7446. };
  7447. /*
  7448. * Copyright 2018 Scytl Secure Electronic Voting SA
  7449. *
  7450. * All rights reserved
  7451. *
  7452. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7453. */
  7454. cryptolib.modules.primitives = cryptolib.modules.primitives || {};
  7455. /**
  7456. * Defines primitives services.
  7457. * @namespace primitives/service
  7458. */
  7459. cryptolib.modules.primitives.service = function(box) {
  7460. 'use strict';
  7461. box.primitives = box.primitives || {};
  7462. /**
  7463. * A module that holds primitives API.
  7464. * @exports primitives/service
  7465. */
  7466. box.primitives.service = {};
  7467. var securerandomFactory, messageDigestFactory, secretKeyGeneratorFactory;
  7468. cryptolib(
  7469. 'primitives.securerandom', 'commons.exceptions',
  7470. 'primitives.messagedigest', 'primitives.derivation', function(box) {
  7471. securerandomFactory =
  7472. new box.primitives.securerandom.factory.SecureRandomFactory();
  7473. messageDigestFactory =
  7474. new box.primitives.messagedigest.factory.MessageDigestFactory();
  7475. secretKeyGeneratorFactory =
  7476. new box.primitives.derivation.factory.SecretKeyGeneratorFactory();
  7477. });
  7478. /**
  7479. * Provides a random bytes generator.
  7480. * @function
  7481. * @returns {primitives/securerandom.CryptoScytlRandomBytes} a CryptoRandomBytes object.
  7482. */
  7483. box.primitives.service.getCryptoRandomBytes = function() {
  7484. return securerandomFactory.getCryptoRandomBytes();
  7485. };
  7486. /**
  7487. * Provides a random integer generator.
  7488. * @function
  7489. * @returns {primitives/securerandom.CryptoScytlRandomInteger} a CryptoRandomInteger object.
  7490. */
  7491. box.primitives.service.getCryptoRandomInteger = function() {
  7492. return securerandomFactory.getCryptoRandomInteger();
  7493. };
  7494. /**
  7495. * Generates a hash for the given data.
  7496. * @function
  7497. * @parameter {array} ArrayDataBase64 the input data for the hash.
  7498. * @returns {string} the hash, as a string in Base64 encoded format.
  7499. */
  7500. box.primitives.service.getHash = function(ArrayDataBase64) {
  7501. var hashFunction = messageDigestFactory.getCryptoMessageDigest();
  7502. hashFunction.start();
  7503. hashFunction.update(ArrayDataBase64);
  7504. return hashFunction.digest();
  7505. };
  7506. /**
  7507. * Provides a derived secret key generator.
  7508. * @function
  7509. * @returns {primitives/derivation.CryptoForgePBKDFSecretKeyGenerator} a the pbkdf Generator.
  7510. */
  7511. box.primitives.service.getPbkdfSecretKeyGenerator = function() {
  7512. return secretKeyGeneratorFactory.createPBKDF();
  7513. };
  7514. };
  7515. /*
  7516. * Copyright 2018 Scytl Secure Electronic Voting SA
  7517. *
  7518. * All rights reserved
  7519. *
  7520. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7521. */
  7522. cryptolib.modules = cryptolib.modules || {};
  7523. cryptolib.modules.proofs = cryptolib.modules.proofs || {};
  7524. /**
  7525. * Defines Zero-Knowledge Proofs (ZKPs).
  7526. */
  7527. cryptolib.modules.proofs.implementation = function(box) {
  7528. 'use strict';
  7529. box.proofs = box.proofs || {};
  7530. var exceptions, mathematical, utils, converters, secureRandomFactory,
  7531. messageDigestFactory;
  7532. var f = function(box) {
  7533. exceptions = box.commons.exceptions;
  7534. mathematical = box.commons.mathematical;
  7535. utils = box.commons.utils;
  7536. converters = new box.commons.utils.Converters();
  7537. secureRandomFactory =
  7538. new box.primitives.securerandom.factory.SecureRandomFactory();
  7539. messageDigestFactory =
  7540. new box.primitives.messagedigest.factory.MessageDigestFactory();
  7541. };
  7542. f.policies = {
  7543. primitives: {
  7544. messagedigest: {
  7545. algorithm: box.policies.proofs.messagedigest.algorithm,
  7546. provider: box.policies.proofs.messagedigest.provider
  7547. },
  7548. secureRandom: {provider: box.policies.proofs.secureRandom.provider}
  7549. }
  7550. };
  7551. cryptolib(
  7552. 'commons.exceptions', 'commons.mathematical', 'primitives.messagedigest',
  7553. 'commons.utils', 'primitives.securerandom', f);
  7554. /**
  7555. * Schnorr proof generator.
  7556. */
  7557. box.proofs.SchnorrProofGenerator = function(voterID, electionID, group) {
  7558. checkNotEmpty('voter ID', voterID);
  7559. checkNotEmpty('election ID', electionID);
  7560. checkDefined('group', group);
  7561. var computationRules = [[[1, 1]]];
  7562. var _voterID = voterID;
  7563. var _electionID = electionID;
  7564. var _progressMeter;
  7565. var _numOutputs = 1;
  7566. var buildListOfBaseElements = function() {
  7567. var baseElements = [];
  7568. baseElements.push(group.getGenerator());
  7569. return baseElements;
  7570. };
  7571. var phiFunctionSchnorr = new box.proofs.PhiFunction(
  7572. group, 1, _numOutputs, buildListOfBaseElements(), computationRules);
  7573. var _prover = new box.proofs.Prover(group, phiFunctionSchnorr);
  7574. this._buildListPublicValues = function(exponentiatedElement) {
  7575. var publicList = [];
  7576. publicList.push(exponentiatedElement);
  7577. return publicList;
  7578. };
  7579. this._getProver = function() {
  7580. return _prover;
  7581. };
  7582. this._buildListExponents = function(witness) {
  7583. var exponentList = [];
  7584. exponentList.push(witness);
  7585. return exponentList;
  7586. };
  7587. this._buildDataString = function() {
  7588. return 'SchnorrProof:VoterID=' + _voterID +
  7589. 'ElectionEventID=' + _electionID;
  7590. };
  7591. this._getProgressMeter = function() {
  7592. return _progressMeter;
  7593. };
  7594. this.initProgressMeter = function(
  7595. progressCallback, progressPercentMinCheckInterval) {
  7596. _progressMeter = createProgressMeter(
  7597. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  7598. return this;
  7599. };
  7600. };
  7601. box.proofs.SchnorrProofGenerator.prototype = {
  7602. preCompute: function() {
  7603. return this._getProver().preCompute(1, this._getProgressMeter());
  7604. },
  7605. generate: function(exponentiatedElement, witness, preComputedValues) {
  7606. checkDefined('exponentiated element', exponentiatedElement);
  7607. checkDefined('witness', witness);
  7608. if (!preComputedValues) {
  7609. preComputedValues = this.preCompute();
  7610. }
  7611. return this._getProver().prove(
  7612. this._buildListPublicValues(exponentiatedElement),
  7613. this._buildListExponents(witness), this._buildDataString(),
  7614. preComputedValues);
  7615. }
  7616. };
  7617. /**
  7618. * Exponentiation proof generator.
  7619. */
  7620. box.proofs.ExponentiationProofGenerator = function(baseElements, group) {
  7621. checkDefined('base elements', baseElements);
  7622. checkDefined('group', group);
  7623. var buildComputationRules = function(k) {
  7624. var rules = [];
  7625. for (var i = 0; i < k; i++) {
  7626. rules[i] = [];
  7627. rules[i][0] = [];
  7628. rules[i][0].push(i + 1);
  7629. rules[i][0].push(1);
  7630. }
  7631. return rules;
  7632. };
  7633. var _numOutputs = baseElements.length;
  7634. var phiFunctionExponentiation = new box.proofs.PhiFunction(
  7635. group, 1, _numOutputs, baseElements,
  7636. buildComputationRules(_numOutputs));
  7637. var _prover = new box.proofs.Prover(group, phiFunctionExponentiation);
  7638. var _progressMeter;
  7639. this._getProgressMeter = function() {
  7640. return _progressMeter;
  7641. };
  7642. this.initProgressMeter = function(
  7643. progressCallback, progressPercentMinCheckInterval) {
  7644. _progressMeter = createProgressMeter(
  7645. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  7646. return this;
  7647. };
  7648. this.check = function(exponentiatedElements) {
  7649. if (exponentiatedElements.length !== _numOutputs) {
  7650. throw new exceptions.CryptoLibException(
  7651. 'The number of exponentiated elements must be equal to the number of base elements');
  7652. }
  7653. };
  7654. this._getProver = function() {
  7655. return _prover;
  7656. };
  7657. };
  7658. box.proofs.ExponentiationProofGenerator.prototype = {
  7659. preCompute: function() {
  7660. var EXPONENT_QUANTITY = 1;
  7661. return this._getProver().preCompute(
  7662. EXPONENT_QUANTITY, this._getProgressMeter());
  7663. },
  7664. generate: function(exponentiatedElements, exponent, preComputedValues) {
  7665. checkDefined('exponentiatedElements', exponentiatedElements);
  7666. checkDefined('exponent', exponent);
  7667. this.check(exponentiatedElements);
  7668. var exponents = [];
  7669. exponents.push(exponent);
  7670. if (!preComputedValues) {
  7671. preComputedValues = this.preCompute();
  7672. }
  7673. return this._getProver().prove(
  7674. exponentiatedElements, exponents,
  7675. box.EXPONENTIATION_PROOF_AUXILIARY_DATA, preComputedValues);
  7676. }
  7677. };
  7678. /**
  7679. * Plaintext proof generator.
  7680. */
  7681. box.proofs.PlaintextProofGenerator = function(publicKey, group) {
  7682. checkDefined('public key', publicKey);
  7683. checkDefined('group', group);
  7684. var buildListOfBaseElements = function() {
  7685. var list = [];
  7686. list.push(group.getGenerator());
  7687. list.addAll(publicKey.getGroupElementsArray());
  7688. return list;
  7689. };
  7690. var buildComputationRules = function(k) {
  7691. var rules = [];
  7692. for (var i = 0; i < (k + 1); i++) {
  7693. rules[i] = [];
  7694. rules[i][0] = [];
  7695. rules[i][0].push(i + 1);
  7696. rules[i][0].push(1);
  7697. }
  7698. return rules;
  7699. };
  7700. var _publicKeyLength = publicKey.getGroupElementsArray().length;
  7701. var numOutputs = _publicKeyLength + 1;
  7702. var phiFunctionPlaintext = new box.proofs.PhiFunction(
  7703. group, 1, numOutputs, buildListOfBaseElements(),
  7704. buildComputationRules(_publicKeyLength));
  7705. var _prover = new box.proofs.Prover(group, phiFunctionPlaintext);
  7706. var _progressMeter;
  7707. this._buildListPublicValues = function(ciphertext, plaintext) {
  7708. var dividedCiphertext =
  7709. mathematical.groupUtils.divide(ciphertext.getPhis(), plaintext);
  7710. var publicValues = [];
  7711. publicValues.push(ciphertext.getGamma());
  7712. publicValues.addAll(dividedCiphertext);
  7713. return publicValues;
  7714. };
  7715. this._getPublicKeyLength = function() {
  7716. return _publicKeyLength;
  7717. };
  7718. this._getProver = function() {
  7719. return _prover;
  7720. };
  7721. this._getProgressMeter = function() {
  7722. return _progressMeter;
  7723. };
  7724. this.initProgressMeter = function(
  7725. progressCallback, progressPercentMinCheckInterval) {
  7726. _progressMeter = createProgressMeter(
  7727. _publicKeyLength + 1, progressCallback,
  7728. progressPercentMinCheckInterval);
  7729. return this;
  7730. };
  7731. };
  7732. box.proofs.PlaintextProofGenerator.prototype = {
  7733. preCompute: function() {
  7734. return this._getProver().preCompute(1, this._getProgressMeter());
  7735. },
  7736. generate: function(ciphertext, plaintext, witness, preComputedValues) {
  7737. checkDefined('ciphertext', ciphertext);
  7738. checkDefined('plaintext', plaintext);
  7739. checkDefined('witness', witness);
  7740. var publicKeyLength = this._getPublicKeyLength();
  7741. var numPhis = ciphertext.getPhis().length;
  7742. if (publicKeyLength !== numPhis) {
  7743. throw new exceptions.CryptoLibException(
  7744. 'The length of the ciphertext must be equal to the length of the public key + 1.');
  7745. }
  7746. if (publicKeyLength !== plaintext.length) {
  7747. throw new exceptions.CryptoLibException(
  7748. 'The public key and the plaintext must have the same number of elements');
  7749. }
  7750. if (!preComputedValues) {
  7751. preComputedValues = this.preCompute();
  7752. }
  7753. var exponents = [];
  7754. exponents.push(witness);
  7755. return this._getProver().prove(
  7756. this._buildListPublicValues(ciphertext, plaintext), exponents,
  7757. box.PLAINTEXT_PROOF_AUXILIARY_DATA, preComputedValues);
  7758. }
  7759. };
  7760. /**
  7761. * Simple plaintext equality proof generator.
  7762. */
  7763. box.proofs.SimplePlaintextEqualityProofGenerator = function(
  7764. primaryPublicKey, secondaryPublicKey, group) {
  7765. checkDefined('primary public key', primaryPublicKey);
  7766. checkDefined('secondary public key', secondaryPublicKey);
  7767. checkDefined('group', group);
  7768. var _primaryPublicKey = primaryPublicKey;
  7769. var _secondaryPublicKey = secondaryPublicKey;
  7770. var _group = group;
  7771. var buildComputationRules = function(k) {
  7772. var rules = [];
  7773. var firstDimensionLength = k + 1;
  7774. rules[0] = [];
  7775. rules[0][0] = [];
  7776. rules[0][0].push(1);
  7777. rules[0][0].push(1);
  7778. for (var i = 1; i < firstDimensionLength; i++) {
  7779. rules[i] = [];
  7780. rules[i][0] = [];
  7781. rules[i][1] = [];
  7782. rules[i][0].push(i + 1);
  7783. rules[i][0].push(1);
  7784. rules[i][1].push(i + 1 + k);
  7785. rules[i][1].push(1);
  7786. }
  7787. return rules;
  7788. };
  7789. var buildSecondaryInvertedPublicKey = function() {
  7790. var listInvertedElements = [];
  7791. var keys = _secondaryPublicKey.getGroupElementsArray();
  7792. for (var i = 0; i < keys.length; i++) {
  7793. listInvertedElements.push(keys[i].invert());
  7794. }
  7795. return listInvertedElements;
  7796. };
  7797. var buildListOfBaseElements = function() {
  7798. var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
  7799. var baseElements = [];
  7800. baseElements.push(group.getGenerator());
  7801. baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
  7802. baseElements.addAll(invertedSecondaryKeyValues);
  7803. return baseElements;
  7804. };
  7805. var primaryPublicKeyLength =
  7806. primaryPublicKey.getGroupElementsArray().length;
  7807. var secondaryPublicKeyLength =
  7808. secondaryPublicKey.getGroupElementsArray().length;
  7809. if (primaryPublicKeyLength !== secondaryPublicKeyLength) {
  7810. throw new exceptions.CryptoLibException(
  7811. 'The number of elements in the primary and secondary public keys must be equal');
  7812. }
  7813. var _progressMeter;
  7814. var _numKeyElements = primaryPublicKey.getGroupElementsArray().length;
  7815. var numOutputs = _numKeyElements + 1;
  7816. var rules = buildComputationRules(_numKeyElements);
  7817. var phiFunctionSimplePlaintextEquality = new box.proofs.PhiFunction(
  7818. group, 1, numOutputs, buildListOfBaseElements(), rules);
  7819. var _prover =
  7820. new box.proofs.Prover(_group, phiFunctionSimplePlaintextEquality);
  7821. this._buildListExponents = function(witness) {
  7822. var exponentList = [];
  7823. exponentList.push(witness);
  7824. return exponentList;
  7825. };
  7826. this._buildInputList = function(primaryCiphertext, secondaryCiphertext) {
  7827. var dividedSubCiphertext = mathematical.groupUtils.divide(
  7828. primaryCiphertext.getPhis(), secondaryCiphertext.getPhis());
  7829. var generatedList = [];
  7830. generatedList.push(secondaryCiphertext.getGamma());
  7831. generatedList.addAll(dividedSubCiphertext);
  7832. return generatedList;
  7833. };
  7834. this._getProgressMeter = function() {
  7835. return _progressMeter;
  7836. };
  7837. this.initProgressMeter = function(
  7838. progressCallback, progressPercentMinCheckInterval) {
  7839. _progressMeter = createProgressMeter(
  7840. _numKeyElements * 2 + 1, progressCallback,
  7841. progressPercentMinCheckInterval);
  7842. return this;
  7843. };
  7844. this._getProver = function() {
  7845. return _prover;
  7846. };
  7847. this._check = function(primaryCiphertextLength) {
  7848. if (primaryCiphertextLength !== (primaryPublicKeyLength + 1)) {
  7849. throw new exceptions.CryptoLibException(
  7850. 'The number of elements in the ciphertext must be equal to the number in the public key + 1');
  7851. }
  7852. };
  7853. };
  7854. box.proofs.SimplePlaintextEqualityProofGenerator.prototype = {
  7855. preCompute: function() {
  7856. return this._getProver().preCompute(1, this._getProgressMeter());
  7857. },
  7858. generate: function(
  7859. primaryCiphertext, secondaryCiphertext, witness, preComputedValues) {
  7860. checkDefined('primary ciphertext', primaryCiphertext);
  7861. checkDefined('secondary ciphertext', secondaryCiphertext);
  7862. checkDefined('witness', witness);
  7863. var primaryCiphertextLength = primaryCiphertext.getPhis().length + 1;
  7864. var secondaryCiphertextLength = secondaryCiphertext.getPhis().length + 1;
  7865. if (primaryCiphertextLength !== secondaryCiphertextLength) {
  7866. throw new exceptions.CryptoLibException(
  7867. 'The number of elements in the primary and secondary ciphertext must be equal');
  7868. }
  7869. this._check(primaryCiphertextLength);
  7870. if (!preComputedValues) {
  7871. preComputedValues = this.preCompute();
  7872. }
  7873. return this._getProver().prove(
  7874. this._buildInputList(primaryCiphertext, secondaryCiphertext),
  7875. this._buildListExponents(witness),
  7876. box.SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
  7877. preComputedValues);
  7878. }
  7879. };
  7880. /**
  7881. * Plaintext equality proof generator.
  7882. */
  7883. box.proofs.PlaintextEqualityProofGenerator = function(
  7884. primaryPublicKey, secondaryPublicKey, group) {
  7885. checkDefined('primary public key', primaryPublicKey);
  7886. checkDefined('secondary public key', secondaryPublicKey);
  7887. checkDefined('group', group);
  7888. var numPrimaryPublicKeyElements =
  7889. primaryPublicKey.getGroupElementsArray().length;
  7890. var numSecondaryPublicKeyElements =
  7891. secondaryPublicKey.getGroupElementsArray().length;
  7892. if (numPrimaryPublicKeyElements !== numSecondaryPublicKeyElements) {
  7893. throw new exceptions.CryptoLibException(
  7894. 'The primary and secondary public keys contain different numbers of elements: ' +
  7895. numPrimaryPublicKeyElements + ', ' + numSecondaryPublicKeyElements);
  7896. }
  7897. var _primaryPublicKey = primaryPublicKey;
  7898. var _secondaryPublicKey = secondaryPublicKey;
  7899. var _group = group;
  7900. var _progressMeter;
  7901. this._buildListExponents = function(primaryWitness, secondaryWitness) {
  7902. var exponentList = [];
  7903. exponentList.push(primaryWitness);
  7904. exponentList.push(secondaryWitness);
  7905. return exponentList;
  7906. };
  7907. this._buildInputList = function(primaryCiphertext, secondaryCiphertext) {
  7908. var dividedSubCiphertext = mathematical.groupUtils.divide(
  7909. primaryCiphertext.getPhis(), secondaryCiphertext.getPhis());
  7910. var generatedList = [];
  7911. generatedList.push(primaryCiphertext.getGamma());
  7912. generatedList.push(secondaryCiphertext.getGamma());
  7913. generatedList.addAll(dividedSubCiphertext);
  7914. return generatedList;
  7915. };
  7916. function buildComputationRules(k) {
  7917. var firstDimensionLength = k + 2;
  7918. var rules = [];
  7919. rules[0] = [];
  7920. rules[0][0] = [];
  7921. rules[0][0].push(1);
  7922. rules[0][0].push(1);
  7923. rules[1] = [];
  7924. rules[1][0] = [];
  7925. rules[1][0].push(1);
  7926. rules[1][0].push(2);
  7927. for (var i = 2; i < firstDimensionLength; i++) {
  7928. rules[i] = [];
  7929. rules[i][0] = [];
  7930. rules[i][0].push(i);
  7931. rules[i][0].push(1);
  7932. rules[i][1] = [];
  7933. rules[i][1].push(i + k);
  7934. rules[i][1].push(2);
  7935. }
  7936. return rules;
  7937. }
  7938. function buildListOfBaseElements() {
  7939. var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
  7940. var baseElements = [];
  7941. baseElements.push(group.getGenerator());
  7942. baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
  7943. baseElements.addAll(invertedSecondaryKeyValues);
  7944. return baseElements;
  7945. }
  7946. function buildSecondaryInvertedPublicKey() {
  7947. var listInvertedElements = [];
  7948. var keys = _secondaryPublicKey.getGroupElementsArray();
  7949. for (var i = 0; i < keys.length; i++) {
  7950. listInvertedElements.push(keys[i].invert());
  7951. }
  7952. return listInvertedElements;
  7953. }
  7954. var numKeyElements = primaryPublicKey.getGroupElementsArray().length;
  7955. var _numOutputs = numKeyElements + 2;
  7956. var rules = buildComputationRules(numKeyElements);
  7957. var phiFunctionPlaintextEquality = new box.proofs.PhiFunction(
  7958. group, 2, _numOutputs, buildListOfBaseElements(), rules);
  7959. var _prover = new box.proofs.Prover(group, phiFunctionPlaintextEquality);
  7960. this.getPrimaryPublicKey = function() {
  7961. return _primaryPublicKey;
  7962. };
  7963. this.getSecondaryPublicKey = function() {
  7964. return _secondaryPublicKey;
  7965. };
  7966. this.getGroup = function() {
  7967. return _group;
  7968. };
  7969. this._getProgressMeter = function() {
  7970. return _progressMeter;
  7971. };
  7972. this.initProgressMeter = function(
  7973. progressCallback, progressPercentMinCheckInterval) {
  7974. _progressMeter = createProgressMeter(
  7975. numKeyElements * 2 + 2, progressCallback,
  7976. progressPercentMinCheckInterval);
  7977. return this;
  7978. };
  7979. this._getProver = function() {
  7980. return _prover;
  7981. };
  7982. this.check = function(numPrimaryCiphertextElements) {
  7983. if (numPrimaryCiphertextElements !== (numPrimaryPublicKeyElements + 1)) {
  7984. throw new exceptions.CryptoLibException(
  7985. 'The number of ciphertext elements is not equal to the number public key elements plus one.');
  7986. }
  7987. };
  7988. };
  7989. box.proofs.PlaintextEqualityProofGenerator.prototype = {
  7990. preCompute: function() {
  7991. return this._getProver().preCompute(2, this._getProgressMeter());
  7992. },
  7993. generate: function(
  7994. primaryCiphertext, primaryWitness, secondaryCiphertext,
  7995. secondaryWitness, preComputedValues) {
  7996. checkDefined('primary ciphertext', primaryCiphertext);
  7997. checkDefined('primary witness', primaryWitness);
  7998. checkDefined('secondary ciphertext', secondaryCiphertext);
  7999. checkDefined('secondary witness', secondaryWitness);
  8000. var numPrimaryCiphertextElements = primaryCiphertext.getPhis().length + 1;
  8001. var numSecondaryCiphertextElements =
  8002. secondaryCiphertext.getPhis().length + 1;
  8003. if (numPrimaryCiphertextElements !== numSecondaryCiphertextElements) {
  8004. throw new exceptions.CryptoLibException(
  8005. 'The primary and secondary ciphertexts contain different numbers of elements: ' +
  8006. numPrimaryCiphertextElements + ', ' +
  8007. numSecondaryCiphertextElements);
  8008. }
  8009. this.check(numPrimaryCiphertextElements);
  8010. if (!preComputedValues) {
  8011. preComputedValues = this.preCompute();
  8012. }
  8013. return this._getProver().prove(
  8014. this._buildInputList(primaryCiphertext, secondaryCiphertext),
  8015. this._buildListExponents(primaryWitness, secondaryWitness),
  8016. box.PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA, preComputedValues);
  8017. }
  8018. };
  8019. /**
  8020. * Plaintext exponent equality proof generator.
  8021. */
  8022. box.proofs.PlaintextExponentEqualityProofGenerator = function(
  8023. baseElements, group) {
  8024. var buildComputationRules = function(k) {
  8025. var rules = [];
  8026. var firstDimensionLength = k + 1;
  8027. rules[0] = [];
  8028. rules[0][0] = [];
  8029. rules[0][0].push(1);
  8030. rules[0][0].push(1);
  8031. for (var i = 1; i < firstDimensionLength; i++) {
  8032. rules[i] = [];
  8033. rules[i][0] = [];
  8034. rules[i][1] = [];
  8035. rules[i][0].push(i + 1);
  8036. rules[i][0].push(1);
  8037. rules[i][1].push(i + 1 + k);
  8038. rules[i][1].push(2);
  8039. }
  8040. return rules;
  8041. };
  8042. checkDefined('base elements', baseElements);
  8043. checkDefined('group', group);
  8044. var _numBaseElements = baseElements.length;
  8045. var _progressMeter;
  8046. var k = (_numBaseElements - 1) / 2;
  8047. var numOutputs = k + 1;
  8048. var phiFunctionPlaintextExponentEquality = new box.proofs.PhiFunction(
  8049. group, 2, numOutputs, baseElements, buildComputationRules(k));
  8050. var _prover =
  8051. new box.proofs.Prover(group, phiFunctionPlaintextExponentEquality);
  8052. this._buildListExponents = function(witness1, witness2) {
  8053. var exponentList = [];
  8054. exponentList.push(witness1);
  8055. exponentList.push(witness2);
  8056. return exponentList;
  8057. };
  8058. this._buildListPublicValues = function(ciphertext) {
  8059. var list = [];
  8060. list.push(ciphertext.getGamma());
  8061. list.addAll(ciphertext.getPhis());
  8062. return list;
  8063. };
  8064. this._getProver = function() {
  8065. return _prover;
  8066. };
  8067. this._getProgressMeter = function() {
  8068. return _progressMeter;
  8069. };
  8070. this.initProgressMeter = function(
  8071. progressCallback, progressPercentMinCheckInterval) {
  8072. _progressMeter = createProgressMeter(
  8073. _numBaseElements, progressCallback, progressPercentMinCheckInterval);
  8074. return this;
  8075. };
  8076. this._checkLengthOf = function(ciphertext) {
  8077. var k = ciphertext.getPhis().length;
  8078. var expectedNumBaseElements = (2 * k) + 1;
  8079. if (_numBaseElements !== expectedNumBaseElements) {
  8080. throw new exceptions.CryptoLibException(
  8081. 'The lengths of the ciphertext and the base elements do not have the expected relationship.');
  8082. }
  8083. };
  8084. };
  8085. box.proofs.PlaintextExponentEqualityProofGenerator.prototype = {
  8086. preCompute: function() {
  8087. return this._getProver().preCompute(2, this._getProgressMeter());
  8088. },
  8089. generate: function(ciphertext, witness1, witness2, preComputedValues) {
  8090. checkDefined('ciphertext', ciphertext);
  8091. checkDefined('witness1', witness1);
  8092. checkDefined('witness2', witness2);
  8093. this._checkLengthOf(ciphertext);
  8094. if (!preComputedValues) {
  8095. preComputedValues = this.preCompute();
  8096. }
  8097. return this._getProver().prove(
  8098. this._buildListPublicValues(ciphertext),
  8099. this._buildListExponents(witness1, witness2),
  8100. box.PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA,
  8101. preComputedValues);
  8102. }
  8103. };
  8104. /**
  8105. * OR-proof generator.
  8106. */
  8107. box.proofs.ORProofGenerator = function(publicKey, numElements, group) {
  8108. checkPublicKey(publicKey);
  8109. checkNumElements(numElements);
  8110. checkGroup(group);
  8111. var _publicKey = publicKey;
  8112. var _numElements = numElements;
  8113. var _group = group;
  8114. var _numOutputs = _numElements * 2;
  8115. var _progressMeter;
  8116. function checkPublicKey(publicKey) {
  8117. checkDefined('public key', publicKey);
  8118. checkNotNull('public key', publicKey);
  8119. var publicKeyLength = publicKey.getGroupElementsArray().length;
  8120. if (publicKeyLength !== 1) {
  8121. throw new exceptions.CryptoLibException(
  8122. 'Expected public key length: 1 ; Found: ' + publicKeyLength);
  8123. }
  8124. }
  8125. function checkNumElements(numElements) {
  8126. checkDefined('numElements', numElements);
  8127. checkNotNull('numElements', numElements);
  8128. if (numElements < 2) {
  8129. throw new exceptions.CryptoLibException(
  8130. 'Expected number of elements to be greater than 1 ; Found: ' +
  8131. numElements);
  8132. }
  8133. }
  8134. function checkGroup(group) {
  8135. checkDefined('group', group);
  8136. checkNotNull('group', group);
  8137. }
  8138. function buildBaseElements() {
  8139. var baseElements = [];
  8140. baseElements.push(_group.getGenerator());
  8141. baseElements.push(_publicKey.getGroupElementsArray()[0]);
  8142. return baseElements;
  8143. }
  8144. function buildComputationRules(numOutputs) {
  8145. var rules = [];
  8146. var index1;
  8147. var index2 = 0;
  8148. for (var i = 0; i < numOutputs; i++) {
  8149. index1 = 1 + (i % 2);
  8150. if (i % 2 === 0) {
  8151. index2++;
  8152. }
  8153. rules[i] = [];
  8154. rules[i][0] = [];
  8155. rules[i][0].push(index1);
  8156. rules[i][0].push(index2);
  8157. }
  8158. return rules;
  8159. }
  8160. var phiFunctionOR = new box.proofs.PhiFunction(
  8161. group, _numElements, _numOutputs, buildBaseElements(),
  8162. buildComputationRules(_numOutputs));
  8163. var _prover = new box.proofs.Prover(_group, phiFunctionOR);
  8164. this.getNumElements = function() {
  8165. return _numElements;
  8166. };
  8167. this.getProver = function() {
  8168. return _prover;
  8169. };
  8170. this.buildPublicValues = function(ciphertext) {
  8171. var publicValues = [];
  8172. publicValues.push(ciphertext.getGamma());
  8173. publicValues.push(ciphertext.getPhis()[0]);
  8174. return publicValues;
  8175. };
  8176. this.getProgressMeter = function() {
  8177. return _progressMeter;
  8178. };
  8179. this.initProgressMeter = function(
  8180. progressCallback, progressPercentMinCheckInterval) {
  8181. _progressMeter = createProgressMeter(
  8182. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  8183. return this;
  8184. };
  8185. };
  8186. box.proofs.ORProofGenerator.prototype = {
  8187. preCompute: function() {
  8188. return this.getProver().preCompute(
  8189. this.getNumElements(), this.getProgressMeter());
  8190. },
  8191. generate: function(
  8192. ciphertext, witness, elements, index, data, preComputedValues) {
  8193. checkCiphertext(ciphertext);
  8194. checkWitness(witness);
  8195. checkElements(elements, this.getNumElements());
  8196. checkIndex(index, this.getNumElements());
  8197. checkDefined('data', data);
  8198. function checkCiphertext(ciphertext) {
  8199. checkDefined('ciphertext', ciphertext);
  8200. checkNotNull('ciphertext', ciphertext);
  8201. var ciphertextLength = ciphertext.getPhis().length + 1;
  8202. if (ciphertextLength !== 2) {
  8203. throw new exceptions.CryptoLibException(
  8204. 'Expected ciphertext length: 2 ; Found: ' + ciphertextLength);
  8205. }
  8206. }
  8207. function checkWitness(witness) {
  8208. checkDefined('witness', witness);
  8209. checkNotNull('witness', witness);
  8210. }
  8211. function checkElements(elements, numElementsExpected) {
  8212. checkDefined('elements', elements);
  8213. checkNotNull('elements', elements);
  8214. var numElementsFound = elements.length;
  8215. if (numElementsFound !== numElementsExpected) {
  8216. throw new exceptions.CryptoLibException(
  8217. 'Expected number of elements: ' + numElementsExpected +
  8218. ' ; Found: ' + numElementsFound);
  8219. }
  8220. }
  8221. function checkIndex(index, numElements) {
  8222. checkDefined('index', index);
  8223. checkNotNull('index', index);
  8224. if (index < 0) {
  8225. throw new exceptions.CryptoLibException(
  8226. 'Expected index of encrypted element to be positive ; Found: ' +
  8227. index);
  8228. }
  8229. if (index >= numElements) {
  8230. throw new exceptions.CryptoLibException(
  8231. 'Expected index of encrypted element to be less than number of elements: ' +
  8232. numElements + ' ; Found: ' + index);
  8233. }
  8234. }
  8235. var publicValues = this.buildPublicValues(ciphertext);
  8236. var privateValues = [];
  8237. privateValues.push(witness);
  8238. if (data === null) {
  8239. data = '';
  8240. }
  8241. if (!preComputedValues) {
  8242. preComputedValues = this.preCompute();
  8243. }
  8244. return this.getProver().prove(
  8245. publicValues, privateValues, data, preComputedValues, elements,
  8246. index);
  8247. }
  8248. };
  8249. /**
  8250. * Schnorr proof verifier.
  8251. */
  8252. box.proofs.SchnorrProofVerifier = function(
  8253. exponentiatedElement, voterID, electionID, proof, group) {
  8254. checkDefined('exponentiated element', exponentiatedElement);
  8255. checkNotEmpty('voter ID', voterID);
  8256. checkNotEmpty('election ID', electionID);
  8257. checkDefined('proof', proof);
  8258. checkDefined('group', group);
  8259. var _exponentiatedElement = exponentiatedElement;
  8260. var _voterID = voterID;
  8261. var _electionID = electionID;
  8262. var _proof = proof;
  8263. var _group = group;
  8264. var _progressMeter;
  8265. this._buildListOfBaseElements = function() {
  8266. var baseElements = [];
  8267. baseElements.push(_group.getGenerator());
  8268. return baseElements;
  8269. };
  8270. this._buildExponentiatedElementsList = function() {
  8271. var exponentiatedElements = [];
  8272. exponentiatedElements.push(_exponentiatedElement);
  8273. return exponentiatedElements;
  8274. };
  8275. this._buildDataString = function() {
  8276. return 'SchnorrProof:VoterID=' + _voterID +
  8277. 'ElectionEventID=' + _electionID;
  8278. };
  8279. var computationRules = [[[1, 1]]];
  8280. var _numOutputs = 1;
  8281. var phiFunction = new box.proofs.PhiFunction(
  8282. _group, 1, _numOutputs, this._buildListOfBaseElements(),
  8283. computationRules);
  8284. var _verifier = new box.proofs.Verifier(_group, phiFunction);
  8285. this._getProof = function() {
  8286. return _proof;
  8287. };
  8288. this._getVerifier = function() {
  8289. return _verifier;
  8290. };
  8291. this._getProgressMeter = function() {
  8292. return _progressMeter;
  8293. };
  8294. this.initProgressMeter = function(
  8295. progressCallback, progressPercentMinCheckInterval) {
  8296. _progressMeter = createProgressMeter(
  8297. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  8298. return this;
  8299. };
  8300. };
  8301. box.proofs.SchnorrProofVerifier.prototype = {
  8302. verify: function() {
  8303. return this._getVerifier().verify(
  8304. this._buildExponentiatedElementsList(), this._getProof(),
  8305. this._buildDataString(), this._getProgressMeter());
  8306. }
  8307. };
  8308. /**
  8309. * Exponentiation proof verifier.
  8310. */
  8311. box.proofs.ExponentiationProofVerifier = function(
  8312. exponentiatedElements, baseElements, proof, group) {
  8313. checkDefined('exponentiated elements', exponentiatedElements);
  8314. checkDefined('base elements', baseElements);
  8315. checkDefined('proof', proof);
  8316. checkDefined('group', group);
  8317. var _exponentiatedElements = exponentiatedElements;
  8318. var _proof = proof;
  8319. var _progressMeter;
  8320. this._buildComputationRules = function(k) {
  8321. var rules = [];
  8322. for (var i = 0; i < k; i++) {
  8323. rules[i] = [];
  8324. rules[i][0] = [];
  8325. rules[i][0].push(i + 1);
  8326. rules[i][0].push(1);
  8327. }
  8328. return rules;
  8329. };
  8330. var _numOutputs = exponentiatedElements.length;
  8331. var phiFunctionExponentiation = new box.proofs.PhiFunction(
  8332. group, 1, _numOutputs, baseElements,
  8333. this._buildComputationRules(_numOutputs));
  8334. var _verifier = new box.proofs.Verifier(group, phiFunctionExponentiation);
  8335. this._getProof = function() {
  8336. return _proof;
  8337. };
  8338. this.getExponentiatedElements = function() {
  8339. return _exponentiatedElements;
  8340. };
  8341. this._getVerifier = function() {
  8342. return _verifier;
  8343. };
  8344. this._getProgressMeter = function() {
  8345. return _progressMeter;
  8346. };
  8347. this.initProgressMeter = function(
  8348. progressCallback, progressPercentMinCheckInterval) {
  8349. _progressMeter = createProgressMeter(
  8350. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  8351. return this;
  8352. };
  8353. };
  8354. box.proofs.ExponentiationProofVerifier.prototype = {
  8355. verify: function() {
  8356. return this._getVerifier().verify(
  8357. this.getExponentiatedElements(), this._getProof(),
  8358. box.EXPONENTIATION_PROOF_AUXILIARY_DATA, this._getProgressMeter());
  8359. }
  8360. };
  8361. /**
  8362. * Plaintext proof verifier.
  8363. */
  8364. box.proofs.PlaintextProofVerifier = function(publicKey, group) {
  8365. checkDefined('public key', publicKey);
  8366. checkDefined('group', group);
  8367. var _publicKey = publicKey;
  8368. var _group = group;
  8369. var _progressMeter;
  8370. this._buildListOfBaseElements = function() {
  8371. var list = [];
  8372. list.push(_group.getGenerator());
  8373. list.addAll(_publicKey.getGroupElementsArray());
  8374. return list;
  8375. };
  8376. this._buildListPublicValues = function(ciphertext, plaintext) {
  8377. var dividedCiphertext =
  8378. mathematical.groupUtils.divide(ciphertext.getPhis(), plaintext);
  8379. var publicValues = [];
  8380. publicValues.push(ciphertext.getGamma());
  8381. publicValues.addAll(dividedCiphertext);
  8382. return publicValues;
  8383. };
  8384. this._buildComputationRules = function(k) {
  8385. var rules = [];
  8386. for (var i = 0; i < (k + 1); i++) {
  8387. rules[i] = [];
  8388. rules[i][0] = [];
  8389. rules[i][0].push(i + 1);
  8390. rules[i][0].push(1);
  8391. }
  8392. return rules;
  8393. };
  8394. var _publicKeyLength = _publicKey.getGroupElementsArray().length;
  8395. var numOutputs = _publicKeyLength + 1;
  8396. var phiFunctionPlaintext = new box.proofs.PhiFunction(
  8397. _group, 1, numOutputs, this._buildListOfBaseElements(),
  8398. this._buildComputationRules(_publicKeyLength));
  8399. var _verifier = new box.proofs.Verifier(_group, phiFunctionPlaintext);
  8400. this.getPublicKey = function() {
  8401. return _publicKey;
  8402. };
  8403. this.getGroup = function() {
  8404. return _group;
  8405. };
  8406. this._getVerifier = function() {
  8407. return _verifier;
  8408. };
  8409. this._getProgressMeter = function() {
  8410. return _progressMeter;
  8411. };
  8412. this.initProgressMeter = function(
  8413. progressCallback, progressPercentMinCheckInterval) {
  8414. _progressMeter = createProgressMeter(
  8415. _publicKeyLength + 1, progressCallback,
  8416. progressPercentMinCheckInterval);
  8417. return this;
  8418. };
  8419. };
  8420. box.proofs.PlaintextProofVerifier.prototype = {
  8421. verify: function(ciphertext, plaintext, proof) {
  8422. checkDefined('ciphertext', ciphertext);
  8423. checkDefined('plaintext', plaintext);
  8424. checkDefined('proof', proof);
  8425. return this._getVerifier().verify(
  8426. this._buildListPublicValues(ciphertext, plaintext), proof,
  8427. box.PLAINTEXT_PROOF_AUXILIARY_DATA, this._getProgressMeter());
  8428. }
  8429. };
  8430. /**
  8431. * Simple plaintext equality proof verifier.
  8432. */
  8433. box.proofs.SimplePlaintextEqualityProofVerifier = function(
  8434. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8435. secondaryPublicKey, proof, group) {
  8436. checkDefined('primary ciphertext', primaryCiphertext);
  8437. checkDefined('primary public key', primaryPublicKey);
  8438. checkDefined('secondary ciphertext', secondaryCiphertext);
  8439. checkDefined('secondary public key', secondaryPublicKey);
  8440. checkDefined('proof', proof);
  8441. checkDefined('group', group);
  8442. var numPrimaryCiphertextElements = primaryCiphertext.getPhis().length + 1;
  8443. var numPrimaryPublicKeyElements =
  8444. primaryPublicKey.getGroupElementsArray().length;
  8445. var numSecondaryCiphertextElements =
  8446. secondaryCiphertext.getPhis().length + 1;
  8447. var numSecondaryPublicKeyElements =
  8448. secondaryPublicKey.getGroupElementsArray().length;
  8449. if (numPrimaryCiphertextElements !== numSecondaryCiphertextElements) {
  8450. throw new exceptions.CryptoLibException(
  8451. 'The primary and secondary ciphertexts contain different numbers of elements: ' +
  8452. numPrimaryCiphertextElements + ', ' + numSecondaryCiphertextElements);
  8453. }
  8454. if (numPrimaryPublicKeyElements !== numSecondaryPublicKeyElements) {
  8455. throw new exceptions.CryptoLibException(
  8456. 'The primary and secondary public keys contain different numbers of elements: ' +
  8457. numPrimaryPublicKeyElements + ', ' + numSecondaryPublicKeyElements);
  8458. }
  8459. if (numPrimaryCiphertextElements !== (numPrimaryPublicKeyElements + 1)) {
  8460. throw new exceptions.CryptoLibException(
  8461. 'The number of ciphertext elements is not equal to the number public key elements plus one.');
  8462. }
  8463. var _primaryCiphertext = primaryCiphertext;
  8464. var _primaryPublicKey = primaryPublicKey;
  8465. var _secondaryCiphertext = secondaryCiphertext;
  8466. var _secondaryPublicKey = secondaryPublicKey;
  8467. var _proof = proof;
  8468. var _progressMeter;
  8469. function buildComputationRules(k) {
  8470. var rules = [];
  8471. var firstDimensionLength = k + 1;
  8472. rules[0] = [];
  8473. rules[0][0] = [];
  8474. rules[0][0].push(1);
  8475. rules[0][0].push(1);
  8476. for (var i = 1; i < firstDimensionLength; i++) {
  8477. rules[i] = [];
  8478. rules[i][0] = [];
  8479. rules[i][1] = [];
  8480. rules[i][0].push(i + 1);
  8481. rules[i][0].push(1);
  8482. rules[i][1].push(i + 1 + k);
  8483. rules[i][1].push(1);
  8484. }
  8485. return rules;
  8486. }
  8487. function buildListOfBaseElements() {
  8488. var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
  8489. var baseElements = [];
  8490. baseElements.push(group.getGenerator());
  8491. baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
  8492. baseElements.addAll(invertedSecondaryKeyValues);
  8493. return baseElements;
  8494. }
  8495. function buildSecondaryInvertedPublicKey() {
  8496. var listInvertedElements = [];
  8497. var keys = _secondaryPublicKey.getGroupElementsArray();
  8498. for (var i = 0; i < keys.length; i++) {
  8499. listInvertedElements.push(keys[i].invert());
  8500. }
  8501. return listInvertedElements;
  8502. }
  8503. var _primarySubCiphertext = _primaryCiphertext.getPhis();
  8504. var _secondarySubCiphertext = _secondaryCiphertext.getPhis();
  8505. var _numKeyElements = _primaryPublicKey.getGroupElementsArray().length;
  8506. var numOutputs = _numKeyElements + 1;
  8507. var phiFunctionSimplePlaintextEquality = new box.proofs.PhiFunction(
  8508. group, 1, numOutputs, buildListOfBaseElements(),
  8509. buildComputationRules(_numKeyElements));
  8510. var _verifier =
  8511. new box.proofs.Verifier(group, phiFunctionSimplePlaintextEquality);
  8512. this._buildInputList = function() {
  8513. var dividedSubCiphertext = mathematical.groupUtils.divide(
  8514. _primarySubCiphertext, _secondarySubCiphertext);
  8515. var generatedList = [];
  8516. generatedList.push(_primaryCiphertext.getGamma());
  8517. generatedList.addAll(dividedSubCiphertext);
  8518. return generatedList;
  8519. };
  8520. this._getProof = function() {
  8521. return _proof;
  8522. };
  8523. this._getProgressMeter = function() {
  8524. return _progressMeter;
  8525. };
  8526. this.initProgressMeter = function(
  8527. progressCallback, progressPercentMinCheckInterval) {
  8528. _progressMeter = createProgressMeter(
  8529. _numKeyElements * 2 + 1, progressCallback,
  8530. progressPercentMinCheckInterval);
  8531. return this;
  8532. };
  8533. this._getVerifier = function() {
  8534. return _verifier;
  8535. };
  8536. };
  8537. box.proofs.SimplePlaintextEqualityProofVerifier.prototype = {
  8538. verify: function() {
  8539. return this._getVerifier().verify(
  8540. this._buildInputList(), this._getProof(),
  8541. box.SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
  8542. this._getProgressMeter());
  8543. }
  8544. };
  8545. /**
  8546. * Plaintext equality proof verifier.
  8547. */
  8548. box.proofs.PlaintextEqualityProofVerifier = function(
  8549. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8550. secondaryPublicKey, proof, group) {
  8551. checkDefined('primary ciphertext', primaryCiphertext);
  8552. checkDefined('primary public key', primaryPublicKey);
  8553. checkDefined('secondary ciphertext', secondaryCiphertext);
  8554. checkDefined('secondary public key', secondaryPublicKey);
  8555. checkDefined('proof', proof);
  8556. checkDefined('group', group);
  8557. var _primaryCiphertext = primaryCiphertext;
  8558. var _primaryPublicKey = primaryPublicKey;
  8559. var _secondaryCiphertext = secondaryCiphertext;
  8560. var _secondaryPublicKey = secondaryPublicKey;
  8561. var _proof = proof;
  8562. var buildComputationRules = function(k) {
  8563. var firstDimensionLength = k + 2;
  8564. var rules = [];
  8565. rules[0] = [];
  8566. rules[0][0] = [];
  8567. rules[0][0].push(1);
  8568. rules[0][0].push(1);
  8569. rules[1] = [];
  8570. rules[1][0] = [];
  8571. rules[1][0].push(1);
  8572. rules[1][0].push(2);
  8573. for (var i = 2; i < firstDimensionLength; i++) {
  8574. rules[i] = [];
  8575. rules[i][0] = [];
  8576. rules[i][1] = [];
  8577. rules[i][0].push(i);
  8578. rules[i][0].push(1);
  8579. rules[i][1].push(i + k);
  8580. rules[i][1].push(2);
  8581. }
  8582. return rules;
  8583. };
  8584. function buildListOfBaseElements() {
  8585. var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
  8586. var baseElements = [];
  8587. baseElements.push(group.getGenerator());
  8588. baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
  8589. baseElements.addAll(invertedSecondaryKeyValues);
  8590. return baseElements;
  8591. }
  8592. function buildSecondaryInvertedPublicKey() {
  8593. var listInvertedElements = [];
  8594. var keys = _secondaryPublicKey.getGroupElementsArray();
  8595. for (var i = 0; i < keys.length; i++) {
  8596. listInvertedElements.push(keys[i].invert());
  8597. }
  8598. return listInvertedElements;
  8599. }
  8600. var _progressMeter;
  8601. var _primarySubCiphertext = _primaryCiphertext.getPhis();
  8602. var _secondarySubCiphertext = _secondaryCiphertext.getPhis();
  8603. var _numKeyElements = primaryPublicKey.getGroupElementsArray().length;
  8604. var numOutputs = _numKeyElements + 2;
  8605. var phiFunctionPlaintextEquality = new box.proofs.PhiFunction(
  8606. group, 2, numOutputs, buildListOfBaseElements(),
  8607. buildComputationRules(_numKeyElements));
  8608. var _verifier =
  8609. new box.proofs.Verifier(group, phiFunctionPlaintextEquality);
  8610. this._buildInputList = function() {
  8611. var dividedSubCiphertext = mathematical.groupUtils.divide(
  8612. _primarySubCiphertext, _secondarySubCiphertext);
  8613. var generatedList = [];
  8614. generatedList.push(_primaryCiphertext.getGamma());
  8615. generatedList.push(_secondaryCiphertext.getGamma());
  8616. generatedList.addAll(dividedSubCiphertext);
  8617. return generatedList;
  8618. };
  8619. this._getProof = function() {
  8620. return _proof;
  8621. };
  8622. this._getProgressMeter = function() {
  8623. return _progressMeter;
  8624. };
  8625. this.initProgressMeter = function(
  8626. progressCallback, progressPercentMinCheckInterval) {
  8627. _progressMeter = createProgressMeter(
  8628. _numKeyElements * 2 + 2, progressCallback,
  8629. progressPercentMinCheckInterval);
  8630. return this;
  8631. };
  8632. this._getVerifier = function() {
  8633. return _verifier;
  8634. };
  8635. };
  8636. box.proofs.PlaintextEqualityProofVerifier.prototype = {
  8637. verify: function() {
  8638. return this._getVerifier().verify(
  8639. this._buildInputList(), this._getProof(),
  8640. box.PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
  8641. this._getProgressMeter());
  8642. }
  8643. };
  8644. /**
  8645. * Plaintext exponent equality proof verifier.
  8646. */
  8647. box.proofs.PlaintextExponentEqualityProofVerifier = function(
  8648. ciphertext, baseElements, proof, group) {
  8649. checkDefined('ciphertext', ciphertext);
  8650. checkDefined('base elements', baseElements);
  8651. checkDefined('proof', proof);
  8652. checkDefined('group', group);
  8653. var _ciphertext = ciphertext;
  8654. var _baseElements = baseElements;
  8655. var _proof = proof;
  8656. var _group = group;
  8657. var _progressMeter;
  8658. this._buildComputationRules = function(k) {
  8659. var rules = [];
  8660. var firstDimensionLength = k + 1;
  8661. rules[0] = [];
  8662. rules[0][0] = [];
  8663. rules[0][0].push(1);
  8664. rules[0][0].push(1);
  8665. for (var i = 1; i < firstDimensionLength; i++) {
  8666. rules[i] = [];
  8667. rules[i][0] = [];
  8668. rules[i][1] = [];
  8669. rules[i][0].push(i + 1);
  8670. rules[i][0].push(1);
  8671. rules[i][1].push(i + 1 + k);
  8672. rules[i][1].push(2);
  8673. }
  8674. return rules;
  8675. };
  8676. this._buildListPublicValues = function() {
  8677. var list = [];
  8678. list.push(_ciphertext.getGamma());
  8679. list.addAll(_ciphertext.getPhis());
  8680. return list;
  8681. };
  8682. var _k = _ciphertext.getPhis().length;
  8683. var numOutputs = _k + 1;
  8684. var phiFunctionPlaintextExponentEquality = new box.proofs.PhiFunction(
  8685. _group, 2, numOutputs, _baseElements, this._buildComputationRules(_k));
  8686. var _verifier =
  8687. new box.proofs.Verifier(_group, phiFunctionPlaintextExponentEquality);
  8688. this._getProof = function() {
  8689. return _proof;
  8690. };
  8691. this._getVerifier = function() {
  8692. return _verifier;
  8693. };
  8694. this._getProgressMeter = function() {
  8695. return _progressMeter;
  8696. };
  8697. this.initProgressMeter = function(
  8698. progressCallback, progressPercentMinCheckInterval) {
  8699. _progressMeter = createProgressMeter(
  8700. _k * 2 + 1, progressCallback, progressPercentMinCheckInterval);
  8701. return this;
  8702. };
  8703. };
  8704. box.proofs.PlaintextExponentEqualityProofVerifier.prototype = {
  8705. verify: function() {
  8706. return this._getVerifier().verify(
  8707. this._buildListPublicValues(), this._getProof(),
  8708. box.PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA,
  8709. this._getProgressMeter());
  8710. }
  8711. };
  8712. /**
  8713. * OR-proof verifier.
  8714. */
  8715. box.proofs.ORProofVerifier = function(publicKey, numElements, group) {
  8716. checkPublicKey(publicKey);
  8717. checkNumElements(numElements);
  8718. checkGroup(group);
  8719. var _publicKey = publicKey;
  8720. var _numElements = numElements;
  8721. var _group = group;
  8722. var _numOutputs = _numElements * 2;
  8723. var _progressMeter;
  8724. function checkPublicKey(publicKey) {
  8725. checkDefined('public key', publicKey);
  8726. checkNotNull('public key', publicKey);
  8727. var publicKeyLength = publicKey.getGroupElementsArray().length;
  8728. if (publicKeyLength !== 1) {
  8729. throw new exceptions.CryptoLibException(
  8730. 'Expected public key length: 1 ; Found: ' + publicKeyLength);
  8731. }
  8732. }
  8733. function checkNumElements(numElements) {
  8734. checkDefined('numElements', numElements);
  8735. checkNotNull('numElements', numElements);
  8736. if (numElements < 2) {
  8737. throw new exceptions.CryptoLibException(
  8738. 'Expected number of elements to be greater than 1 ; Found: ' +
  8739. numElements);
  8740. }
  8741. }
  8742. function checkGroup(group) {
  8743. checkDefined('group', group);
  8744. checkNotNull('group', group);
  8745. }
  8746. function buildBaseElements() {
  8747. var baseElements = [];
  8748. baseElements.push(_group.getGenerator());
  8749. baseElements.push(_publicKey.getGroupElementsArray()[0]);
  8750. return baseElements;
  8751. }
  8752. function buildComputationRules(numOutputs) {
  8753. var rules = [];
  8754. var index1;
  8755. var index2 = 0;
  8756. for (var i = 0; i < numOutputs; i++) {
  8757. index1 = 1 + (i % 2);
  8758. if (i % 2 === 0) {
  8759. index2++;
  8760. }
  8761. rules[i] = [];
  8762. rules[i][0] = [];
  8763. rules[i][0].push(index1);
  8764. rules[i][0].push(index2);
  8765. }
  8766. return rules;
  8767. }
  8768. var phiFunctionOR = new box.proofs.PhiFunction(
  8769. _group, _numElements, _numOutputs, buildBaseElements(),
  8770. buildComputationRules(_numOutputs));
  8771. var _verifier = new box.proofs.Verifier(_group, phiFunctionOR);
  8772. this.buildPublicValues = function(ciphertext) {
  8773. var publicValues = [];
  8774. publicValues.push(ciphertext.getGamma());
  8775. publicValues.push(ciphertext.getPhis()[0]);
  8776. return publicValues;
  8777. };
  8778. this.getNumElements = function() {
  8779. return _numElements;
  8780. };
  8781. this.getVerifier = function() {
  8782. return _verifier;
  8783. };
  8784. this.getProgressMeter = function() {
  8785. return _progressMeter;
  8786. };
  8787. this.initProgressMeter = function(
  8788. progressCallback, progressPercentMinCheckInterval) {
  8789. _progressMeter = createProgressMeter(
  8790. _numOutputs, progressCallback, progressPercentMinCheckInterval);
  8791. return this;
  8792. };
  8793. };
  8794. box.proofs.ORProofVerifier.prototype = {
  8795. verify: function(ciphertext, elements, data, proof) {
  8796. checkCiphertext(ciphertext);
  8797. checkElements(elements, this.getNumElements());
  8798. checkDefined('data', data);
  8799. checkProof(proof);
  8800. function checkCiphertext(ciphertext) {
  8801. checkDefined('ciphertext', ciphertext);
  8802. checkNotNull('ciphertext', ciphertext);
  8803. var ciphertextLength = ciphertext.getPhis().length + 1;
  8804. if (ciphertextLength !== 2) {
  8805. throw new exceptions.CryptoLibException(
  8806. 'Expected ciphertext length: 2 ; Found: ' + ciphertextLength);
  8807. }
  8808. }
  8809. function checkElements(elements, numElementsExpected) {
  8810. checkDefined('elements', elements);
  8811. checkNotNull('elements', elements);
  8812. var numElementsFound = elements.length;
  8813. if (numElementsFound !== numElementsExpected) {
  8814. throw new exceptions.CryptoLibException(
  8815. 'Expected number of elements: ' + numElementsExpected +
  8816. ' ; Found: ' + numElementsFound);
  8817. }
  8818. }
  8819. function checkProof(proof) {
  8820. checkDefined('proof', proof);
  8821. checkNotNull('proof', proof);
  8822. }
  8823. if (data === null) {
  8824. data = '';
  8825. }
  8826. return this.getVerifier().verify(
  8827. this.buildPublicValues(ciphertext), proof, data, elements,
  8828. this.getProgressMeter());
  8829. }
  8830. };
  8831. /**
  8832. * Proofs factory, can be used for creating proof generators and verifiers.
  8833. */
  8834. box.proofs.ProofsFactory = function() {
  8835. };
  8836. box.proofs.ProofsFactory.prototype = {
  8837. createSchnorrProofGenerator: function(voterID, electionID, group) {
  8838. return new box.proofs.SchnorrProofGenerator(voterID, electionID, group);
  8839. },
  8840. createExponentiationProofGenerator: function(baseElements, group) {
  8841. return new box.proofs.ExponentiationProofGenerator(baseElements, group);
  8842. },
  8843. createPlaintextProofGenerator: function(publicKey, group) {
  8844. return new box.proofs.PlaintextProofGenerator(publicKey, group);
  8845. },
  8846. createSimplePlaintextEqualityProofGenerator: function(
  8847. primaryPublicKey, secondaryPublicKey, group) {
  8848. return new box.proofs.SimplePlaintextEqualityProofGenerator(
  8849. primaryPublicKey, secondaryPublicKey, group);
  8850. },
  8851. createPlaintextEqualityProofGenerator: function(
  8852. primaryPublicKey, secondaryPublicKey, group) {
  8853. return new box.proofs.PlaintextEqualityProofGenerator(
  8854. primaryPublicKey, secondaryPublicKey, group);
  8855. },
  8856. createPlaintextExponentEqualityProofGenerator: function(
  8857. baseElements, group) {
  8858. return new box.proofs.PlaintextExponentEqualityProofGenerator(
  8859. baseElements, group);
  8860. },
  8861. createORProofGenerator: function(publicKey, numElements, group) {
  8862. return new box.proofs.ORProofGenerator(publicKey, numElements, group);
  8863. },
  8864. createSchnorrProofVerifier: function(
  8865. element, voterID, electionEventID, proof, group) {
  8866. return new box.proofs.SchnorrProofVerifier(
  8867. element, voterID, electionEventID, proof, group);
  8868. },
  8869. createExponentiationProofVerifier: function(
  8870. exponentiatedElements, baseElements, proof, group) {
  8871. return new box.proofs.ExponentiationProofVerifier(
  8872. exponentiatedElements, baseElements, proof, group);
  8873. },
  8874. createPlaintextProofVerifier: function(
  8875. publicKey, ciphertext, plaintext, proof, group) {
  8876. return new box.proofs.PlaintextProofVerifier(
  8877. publicKey, ciphertext, plaintext, proof, group);
  8878. },
  8879. createSimplePlaintextEqualityProofVerifier: function(
  8880. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8881. secondaryPublicKey, proof, group) {
  8882. return new box.proofs.SimplePlaintextEqualityProofVerifier(
  8883. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8884. secondaryPublicKey, proof, group);
  8885. },
  8886. createPlaintextEqualityProofVerifier: function(
  8887. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8888. secondaryPublicKey, proof, group) {
  8889. return new box.proofs.PlaintextEqualityProofVerifier(
  8890. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  8891. secondaryPublicKey, proof, group);
  8892. },
  8893. createPlaintextExponentEqualityProofVerifier: function(
  8894. ciphertext, baseElements, proof, group) {
  8895. return new box.proofs.PlaintextExponentEqualityProofVerifier(
  8896. ciphertext, baseElements, proof, group);
  8897. },
  8898. createORProofVerifier: function(publicKey, numElements, group) {
  8899. return new box.proofs.ORProofVerifier(publicKey, numElements, group);
  8900. }
  8901. };
  8902. /**
  8903. * Represents the PHI function of Maurer's Unified Zero-Knowledge Proof of
  8904. * Knowledge (ZK-PoK) scheme.
  8905. */
  8906. box.proofs.PhiFunction = function(
  8907. group, numInputs, numOutputs, baseElements, computationRules) {
  8908. var validateComputationRules = function(
  8909. numInputs, numOutputs, baseElements, computationRules) {
  8910. // Validate that both of the values in each of the
  8911. // pairs of rules have values in the correct ranges
  8912. var numBaseElements = baseElements.length;
  8913. for (var i = 0; i < numOutputs; i++) {
  8914. for (var j = 0; j < computationRules[i].length; j++) {
  8915. // Validate the first value of the pair
  8916. var pairValue1 = computationRules[i][j][0];
  8917. if ((pairValue1 < 1) || (pairValue1 > numBaseElements)) {
  8918. throw new exceptions.CryptoLibException(
  8919. 'Invalid first value in index pair - should be in the range 1 to ' +
  8920. numBaseElements + ', but it was ' + pairValue1);
  8921. }
  8922. // Validate the second value of the pair
  8923. var pairValue2 = computationRules[i][j][1];
  8924. if ((pairValue2 < 1) || (pairValue2 > numInputs)) {
  8925. throw new exceptions.CryptoLibException(
  8926. 'Invalid second value in index pair - should be in the range 1 to ' +
  8927. numInputs + ', but it was ' + pairValue2);
  8928. }
  8929. }
  8930. }
  8931. };
  8932. checkDefined('group', group);
  8933. checkIsPositive('number of inputs', numInputs);
  8934. checkIsPositive('number of outputs', numOutputs);
  8935. checkInitializedArray('base elements', baseElements);
  8936. checkDefined('computation rules', computationRules);
  8937. validateComputationRules(
  8938. numInputs, numOutputs, baseElements, computationRules);
  8939. var _numInputs = numInputs;
  8940. var _numOutputs = numOutputs;
  8941. var _baseElements = baseElements;
  8942. var _computationRules = computationRules;
  8943. /**
  8944. * @return The number of inputs
  8945. */
  8946. this.getNumInputs = function() {
  8947. return _numInputs;
  8948. };
  8949. /**
  8950. * @return The number of outputs
  8951. */
  8952. this.getNumOutputs = function() {
  8953. return _numOutputs;
  8954. };
  8955. /**
  8956. * @return The list of base elements
  8957. */
  8958. this.getBaseElements = function() {
  8959. return _baseElements;
  8960. };
  8961. /**
  8962. * @return The computation rules.
  8963. */
  8964. this.getComputationRules = function() {
  8965. return _computationRules;
  8966. };
  8967. };
  8968. box.proofs.PhiFunction.prototype = {
  8969. calculatePhi: function(inputs, progressMeter) {
  8970. checkDefined('inputs', inputs);
  8971. if (progressMeter === undefined) {
  8972. progressMeter = new utils.ProgressMeter();
  8973. }
  8974. checkDefined('progressMeter', progressMeter);
  8975. var computationsRules = this.getComputationRules();
  8976. var baseElements = this.getBaseElements();
  8977. var partialResult;
  8978. var resultForThisListOfPairs;
  8979. var result = [];
  8980. var progress = 0;
  8981. for (var i = 0; i < computationsRules.length; i++) {
  8982. var numPairsInList = computationsRules[i].length;
  8983. resultForThisListOfPairs =
  8984. baseElements[computationsRules[i][0][0] - 1].exponentiate(
  8985. inputs[computationsRules[i][0][1] - 1]);
  8986. progressMeter.update(++progress);
  8987. for (var j = 1; j < numPairsInList; j++) {
  8988. var index1 = computationsRules[i][j][0];
  8989. index1 = index1 - 1;
  8990. var index2 = computationsRules[i][j][1];
  8991. index2 = index2 - 1;
  8992. partialResult = baseElements[index1].exponentiate(inputs[index2]);
  8993. resultForThisListOfPairs =
  8994. resultForThisListOfPairs.multiply(partialResult);
  8995. progressMeter.update(++progress);
  8996. }
  8997. result.push(resultForThisListOfPairs);
  8998. }
  8999. return result;
  9000. }
  9001. };
  9002. /**
  9003. * Acts as a prover in a Zero-Knowledge Proof of Knowledge (ZK-PoK) exchange
  9004. * using Maurer's unified PHI function.
  9005. */
  9006. box.proofs.Prover = function(group, phiFunction) {
  9007. checkDefined('group', group);
  9008. checkDefined('phiFunction', phiFunction);
  9009. var _group = group;
  9010. var _phiFunction = phiFunction;
  9011. var _cryptoRandomInteger = secureRandomFactory.getCryptoRandomInteger();
  9012. /**
  9013. * @return Get the group.
  9014. */
  9015. this.getGroup = function() {
  9016. return _group;
  9017. };
  9018. /**
  9019. * @return Get the phi function.
  9020. */
  9021. this.getPhiFunction = function() {
  9022. return _phiFunction;
  9023. };
  9024. this._calculateRandomExponents = function(numExponentsNeeded) {
  9025. var exponentsArray = [];
  9026. for (var i = 0; i < numExponentsNeeded; i++) {
  9027. var randomExponent = mathematical.groupUtils.generateRandomExponent(
  9028. _group, _cryptoRandomInteger);
  9029. exponentsArray.push(randomExponent);
  9030. }
  9031. return exponentsArray;
  9032. };
  9033. this._generateHash = function(publicValues, phiOutputs, data) {
  9034. var hashBuilder = new box.proofs.HashBuilder();
  9035. var hashB64 =
  9036. hashBuilder.buildHashForProof(publicValues, phiOutputs, data);
  9037. var hash = converters.base64Decode(hashB64);
  9038. var hashBytes = converters.bytesFromString(hash);
  9039. hashBytes.unshift(0);
  9040. var value = new box.forge.jsbn.BigInteger(hashBytes);
  9041. return new mathematical.Exponent(_group.getQ(), value);
  9042. };
  9043. this._generateValuesList = function(
  9044. privateValues, hash, randomExponents, index) {
  9045. var proofValues = [];
  9046. var proofValue;
  9047. if (typeof index === 'undefined') {
  9048. for (var i = 0; i < privateValues.length; i++) {
  9049. proofValue = randomExponents[i].getValue().add(
  9050. privateValues[i].getValue().multiply(hash.getValue()));
  9051. proofValues.push(
  9052. new mathematical.Exponent(_group.getQ(), proofValue));
  9053. }
  9054. } else {
  9055. var numElements = randomExponents.length / 2;
  9056. var updatedHash = hash;
  9057. for (var j = 0; j < numElements; j++) {
  9058. if (j === index) {
  9059. for (var k = 0; k < numElements; k++) {
  9060. if (k !== index) {
  9061. updatedHash = updatedHash.subtract(randomExponents[k]);
  9062. }
  9063. }
  9064. proofValues.push(updatedHash);
  9065. } else {
  9066. proofValues.push(randomExponents[j]);
  9067. }
  9068. }
  9069. for (var m = numElements; m < (numElements * 2); m++) {
  9070. if (m === (numElements + index)) {
  9071. proofValue = randomExponents[m].getValue().add(
  9072. privateValues[0].getValue().multiply(updatedHash.getValue()));
  9073. proofValues.push(
  9074. new mathematical.Exponent(_group.getQ(), proofValue));
  9075. } else {
  9076. proofValues.push(randomExponents[m]);
  9077. }
  9078. }
  9079. }
  9080. return proofValues;
  9081. };
  9082. this._updatePreComputedValues = function(
  9083. preComputedValues, publicValues, elements, index) {
  9084. var gamma = publicValues[0];
  9085. var phi = publicValues[1];
  9086. var numElements = elements.length;
  9087. var challenges = this._calculateRandomExponents(numElements);
  9088. var updatedExponents = [];
  9089. updatedExponents.addAll(challenges);
  9090. updatedExponents.addAll(preComputedValues.getExponents());
  9091. var updatedPhiOutputs = [];
  9092. var phiOutputs = preComputedValues.getPhiOutputs();
  9093. for (var j = 0; j < numElements; j++) {
  9094. var offset = 2 * j;
  9095. if (j === index) {
  9096. updatedPhiOutputs.push(phiOutputs[offset]);
  9097. updatedPhiOutputs.push(phiOutputs[offset + 1]);
  9098. } else {
  9099. var gammaFactor = gamma.invert().exponentiate(challenges[j]);
  9100. var phiFactor =
  9101. (phi.invert().multiply(elements[j])).exponentiate(challenges[j]);
  9102. updatedPhiOutputs.push(phiOutputs[offset].multiply(gammaFactor));
  9103. updatedPhiOutputs.push(phiOutputs[offset + 1].multiply(phiFactor));
  9104. }
  9105. }
  9106. return new box.proofs.ProofPreComputedValues(
  9107. updatedExponents, updatedPhiOutputs);
  9108. };
  9109. };
  9110. box.proofs.Prover.prototype = {
  9111. /**
  9112. * Pre-compute time-consuming values, so they can be used later for
  9113. * method prove().
  9114. */
  9115. preCompute: function(privateValuesLength, progressMeter) {
  9116. var randomExponents = this._calculateRandomExponents(privateValuesLength);
  9117. var phiOutputs =
  9118. this.getPhiFunction().calculatePhi(randomExponents, progressMeter);
  9119. return new box.proofs.ProofPreComputedValues(randomExponents, phiOutputs);
  9120. },
  9121. /**
  9122. * Performs prover steps in a ZK-PoK exchange using Maurer's unified PHI
  9123. * function. This involves generating a proof, using the received inputs
  9124. * and this Prover's internal fields.
  9125. */
  9126. prove: function(
  9127. publicValues, privateValues, data, preComputedValues, elements, index) {
  9128. checkDefined('public values', publicValues);
  9129. checkDefined('private values', privateValues);
  9130. checkDefined('data', data);
  9131. if (!preComputedValues ||
  9132. typeof preComputedValues.getPhiOutputs() === 'undefined' ||
  9133. typeof preComputedValues.getExponents() === 'undefined') {
  9134. throw new exceptions.CryptoLibException(
  9135. 'The precomputed values must be initialized');
  9136. }
  9137. if (typeof elements !== 'undefined') {
  9138. preComputedValues = this._updatePreComputedValues(
  9139. preComputedValues, publicValues, elements, index);
  9140. }
  9141. var hash = this._generateHash(
  9142. publicValues, preComputedValues.getPhiOutputs(), data);
  9143. var proofValues = this._generateValuesList(
  9144. privateValues, hash, preComputedValues.getExponents(), index);
  9145. return new box.proofs.Proof(hash, proofValues);
  9146. }
  9147. };
  9148. /**
  9149. * Acts as a verifier in a Zero-Knowledge Proof of Knowledge (ZK-PoK)
  9150. * exchange using Maurer's unified PHI function.
  9151. */
  9152. box.proofs.Verifier = function(group, phiFunction) {
  9153. checkDefined('group', group);
  9154. checkDefined('phiFunction', phiFunction);
  9155. var _group = group;
  9156. var _phiFunction = phiFunction;
  9157. /**
  9158. * @return Get the group.
  9159. */
  9160. this.getGroup = function() {
  9161. return _group;
  9162. };
  9163. /**
  9164. * @return Get the phi function.
  9165. */
  9166. this.getPhiFunction = function() {
  9167. return _phiFunction;
  9168. };
  9169. this._calculateComputedValues = function(
  9170. publicValues, phiOutputs, proofHashValueOrElements, challenges) {
  9171. var proofHashValue;
  9172. var elements;
  9173. if (!isArray(proofHashValueOrElements)) {
  9174. proofHashValue = proofHashValueOrElements;
  9175. } else {
  9176. elements = proofHashValueOrElements;
  9177. }
  9178. var computedValues = [];
  9179. if (typeof proofHashValue !== 'undefined') {
  9180. for (var i = 0; i < phiOutputs.length; i++) {
  9181. computedValues.push(phiOutputs[i].multiply(
  9182. publicValues[i].exponentiate(proofHashValue.negate())));
  9183. }
  9184. } else {
  9185. var gamma = publicValues[0];
  9186. var phi = publicValues[1];
  9187. for (var j = 0; j < challenges.length; j++) {
  9188. var offset = 2 * j;
  9189. var gammaFactor = gamma.invert().exponentiate(challenges[j]);
  9190. var phiFactor =
  9191. (phi.invert().multiply(elements[j])).exponentiate(challenges[j]);
  9192. computedValues.push(phiOutputs[offset].multiply(gammaFactor));
  9193. computedValues.push(phiOutputs[offset + 1].multiply(phiFactor));
  9194. }
  9195. }
  9196. return computedValues;
  9197. };
  9198. this._calculateHash = function(publicValues, computedValues, data) {
  9199. var hashBuilder = new box.proofs.HashBuilder();
  9200. var hashB64 =
  9201. hashBuilder.buildHashForProof(publicValues, computedValues, data);
  9202. var hash = converters.base64Decode(hashB64);
  9203. var hashBytes = converters.bytesFromString(hash);
  9204. hashBytes.unshift(0);
  9205. var value = new box.forge.jsbn.BigInteger(hashBytes);
  9206. return new mathematical.Exponent(_group.getQ(), value);
  9207. };
  9208. };
  9209. box.proofs.Verifier.prototype = {
  9210. /**
  9211. * Verifies the received input as being true or false.
  9212. */
  9213. verify: function(
  9214. publicValues, proof, data, elementsOrProgressMeter, progressMeter) {
  9215. checkDefined('public values', publicValues);
  9216. checkDefined('proof', proof);
  9217. checkDefined('data', data);
  9218. var elements;
  9219. if (!isArray(elementsOrProgressMeter)) {
  9220. progressMeter = elementsOrProgressMeter;
  9221. } else {
  9222. elements = elementsOrProgressMeter;
  9223. }
  9224. var proofHashValue = proof.getHash();
  9225. var phiOutputs;
  9226. var computedValues;
  9227. if (typeof elements === 'undefined') {
  9228. phiOutputs = this.getPhiFunction().calculatePhi(
  9229. proof.getValues(), progressMeter);
  9230. computedValues = this._calculateComputedValues(
  9231. publicValues, phiOutputs, proofHashValue);
  9232. } else {
  9233. var numElements = elements.length;
  9234. var proofValues = proof.getValues();
  9235. var challenges = proofValues.slice(0, numElements);
  9236. var phiInputs = proofValues.slice(numElements, numElements * 2);
  9237. phiOutputs =
  9238. this.getPhiFunction().calculatePhi(phiInputs, progressMeter);
  9239. computedValues = this._calculateComputedValues(
  9240. publicValues, phiOutputs, elements, challenges);
  9241. }
  9242. var calculatedHash =
  9243. this._calculateHash(publicValues, computedValues, data);
  9244. return proofHashValue.equals(calculatedHash);
  9245. }
  9246. };
  9247. /**
  9248. * @class ProofPreComputedValues stores randomly created exponents and
  9249. * outputs of box.proofs.PhiFunction.calculatePhi().
  9250. */
  9251. box.proofs.ProofPreComputedValues = function(exponents, phiOutputs) {
  9252. this.className = 'ProofPreComputedValues';
  9253. var _exponents = exponents;
  9254. var _phiOutputs = phiOutputs;
  9255. /**
  9256. * @return the exponents.
  9257. */
  9258. this.getExponents = function() {
  9259. return _exponents;
  9260. };
  9261. /**
  9262. * @return the phi function output.
  9263. */
  9264. this.getPhiOutputs = function() {
  9265. return _phiOutputs;
  9266. };
  9267. };
  9268. box.proofs.ProofPreComputedValues.prototype = {
  9269. stringify: function() {
  9270. var exponentValues = Array();
  9271. var phiOutputValues = Array();
  9272. for (var i = 0; i < this.getExponents().length; i++) {
  9273. exponentValues[i] =
  9274. converters.base64FromBigInteger(this.getExponents()[i].getValue());
  9275. }
  9276. for (var j = 0; j < this.getPhiOutputs().length; j++) {
  9277. phiOutputValues[j] = converters.base64FromBigInteger(
  9278. this.getPhiOutputs()[j].getElementValue());
  9279. }
  9280. return JSON.stringify({
  9281. preComputed: {
  9282. p: converters.base64FromBigInteger(this.getPhiOutputs()[0].getP()),
  9283. q: converters.base64FromBigInteger(this.getPhiOutputs()[0].getQ()),
  9284. exponents: exponentValues,
  9285. phiOutputs: phiOutputValues
  9286. }
  9287. });
  9288. }
  9289. };
  9290. /**
  9291. * Represents a proof in a ZKP exchange.
  9292. */
  9293. box.proofs.Proof = function(hashValue, values) {
  9294. checkDefined('hash value', hashValue);
  9295. checkDefined('values', values);
  9296. var _hashValue = hashValue;
  9297. var _values = values;
  9298. /**
  9299. * @return Get the hash value of this proof.
  9300. */
  9301. this.getHash = function() {
  9302. return _hashValue;
  9303. };
  9304. /**
  9305. * @return Get the list of values of this proof.
  9306. */
  9307. this.getValues = function() {
  9308. return _values;
  9309. };
  9310. };
  9311. box.proofs.Proof.prototype = {
  9312. /**
  9313. * @return true if the given proof has the same hash and values.
  9314. */
  9315. equals: function(proof) {
  9316. return proof.getHash().equals(this.getHash()) &&
  9317. proof.getValues().equals(this.getValues());
  9318. },
  9319. /**
  9320. * Displays a string representation of this proof JSON.
  9321. * <p>
  9322. * Note: in order to permit interoperability between libraries, this
  9323. * representation should match the equivalent representation in Java.
  9324. *
  9325. * @function
  9326. * @returns a string representation of this proof JSON.
  9327. */
  9328. stringify: function() {
  9329. var values = Array();
  9330. for (var i = 0; i < this.getValues().length; i++) {
  9331. values[i] =
  9332. converters.base64FromBigInteger(this.getValues()[i].getValue());
  9333. }
  9334. return JSON.stringify({
  9335. zkProof: {
  9336. q: converters.base64FromBigInteger(this.getHash().getQ()),
  9337. hash: converters.base64FromBigInteger(this.getHash().getValue()),
  9338. values: values
  9339. }
  9340. });
  9341. }
  9342. };
  9343. /**
  9344. * A class which provides utility methods for generating a hash from a set
  9345. * of inputs.
  9346. */
  9347. box.proofs.HashBuilder = function() {
  9348. /**
  9349. * Convert an integer to a byte array
  9350. */
  9351. this._getInt64Bytes = function(x) {
  9352. var bytes = [];
  9353. var i = 8;
  9354. do {
  9355. bytes[--i] = x & (255);
  9356. x = x >> 8;
  9357. } while (i);
  9358. return bytes;
  9359. };
  9360. /**
  9361. * Converts an array to a String.
  9362. */
  9363. this._arrayElementValuesToString = function(groupElements) {
  9364. var str = '';
  9365. for (var i = 0; i < groupElements.length; i++) {
  9366. if (groupElements[i].getElementValue() !== undefined) {
  9367. str += groupElements[i].getElementValue();
  9368. } else {
  9369. throw new exceptions.CryptoLibException(
  9370. 'Group Element must implement getElementValue() method.');
  9371. }
  9372. }
  9373. return str;
  9374. };
  9375. };
  9376. box.proofs.HashBuilder.prototype = {
  9377. /**
  9378. * Generates a hash value based on the element values of publicValues
  9379. * and generatedValues and the data.
  9380. *
  9381. * @function
  9382. * @param publicValues
  9383. * {array} group elements representing public values.
  9384. * @param generatedValues
  9385. * {array} group elements representing generated values.
  9386. * @param data
  9387. * {string} some data encoded as a String.
  9388. * @returns a generated hash code.
  9389. * @throws CryptoLibException
  9390. * if any of the received objects has unsupported type.
  9391. */
  9392. buildHashForProof: function(publicValues, generatedValues, data) {
  9393. checkInitializedArray('public values', publicValues);
  9394. checkInitializedArray('generated values', generatedValues);
  9395. var messageDigester = messageDigestFactory.getCryptoMessageDigest();
  9396. messageDigester.start();
  9397. messageDigester = update(
  9398. messageDigester, this._arrayElementValuesToString(publicValues));
  9399. messageDigester = update(
  9400. messageDigester, this._arrayElementValuesToString(generatedValues));
  9401. messageDigester = update(messageDigester, data);
  9402. return messageDigester.digest();
  9403. }
  9404. };
  9405. /**
  9406. * Utility method that updates messageDigester with the provided string.
  9407. */
  9408. function update(messageDigester, str) {
  9409. var stringRepresentationB64 = converters.base64Encode(str);
  9410. var arrayToHash = [];
  9411. arrayToHash.push(stringRepresentationB64);
  9412. messageDigester.update(arrayToHash);
  9413. return messageDigester;
  9414. }
  9415. /**
  9416. * Utility method that checks that value is defined and not null and throws
  9417. * related exception otherwise.
  9418. */
  9419. function checkDefined(key, value) {
  9420. if (typeof value === 'undefined') {
  9421. throw new exceptions.CryptoLibException(
  9422. 'The ' + key + ' must be defined');
  9423. }
  9424. }
  9425. /**
  9426. * Utility method that checks that value is initialized array and throws
  9427. * related exception otherwise.
  9428. */
  9429. function checkInitializedArray(key, value) {
  9430. checkDefined(key, value);
  9431. if (!isArray(value)) {
  9432. throw new exceptions.CryptoLibException(
  9433. 'The ' + key + ' must be an initialized array');
  9434. }
  9435. }
  9436. /**
  9437. * Utility method that checks that value is not null and throws related
  9438. * exception otherwise.
  9439. */
  9440. function checkNotNull(key, value) {
  9441. checkDefined(key, value);
  9442. if (value === null) {
  9443. throw new exceptions.CryptoLibException(
  9444. 'The ' + key + ' must not be null');
  9445. }
  9446. }
  9447. /**
  9448. * Utility method that checks that value is not empty and throws related
  9449. * exception otherwise.
  9450. */
  9451. function checkNotEmpty(key, value) {
  9452. checkDefined(key, value);
  9453. if (value.length === 0) {
  9454. throw new exceptions.CryptoLibException(
  9455. 'The ' + key + ' must not be empty');
  9456. }
  9457. }
  9458. /**
  9459. * Utility method that checks that value is positive and throws related
  9460. * exception otherwise.
  9461. */
  9462. function checkIsPositive(key, value) {
  9463. checkDefined(key, value);
  9464. if (isNaN(value)) {
  9465. throw new exceptions.CryptoLibException(
  9466. 'The ' + key + ' must be a number; Found ' + value);
  9467. }
  9468. if (value <= 0) {
  9469. throw new exceptions.CryptoLibException(
  9470. 'The ' + key + ' must be positive; Found ' + value);
  9471. }
  9472. }
  9473. /**
  9474. * Utility method that checks that values are defined and throws related
  9475. * exception otherwise.
  9476. */
  9477. var checkDefinedProgressParams = function(
  9478. progressCallback, progressPercentMinCheckInterval) {
  9479. if (typeof progressCallback !== 'undefined' &&
  9480. typeof progressCallback !== 'function') {
  9481. throw new exceptions.CryptoLibException(
  9482. 'The progress callback function provided as input is not a function');
  9483. }
  9484. if (typeof progressPercentMinCheckInterval !== 'undefined' &&
  9485. isNaN(progressPercentMinCheckInterval)) {
  9486. throw new exceptions.CryptoLibException(
  9487. 'The progress percentage check interval provided as input is not a number');
  9488. }
  9489. };
  9490. function isArray(a) {
  9491. return (!!a) && (a.constructor === Array);
  9492. }
  9493. /**
  9494. * Utility method that creates a new instance of ProgressMeter.
  9495. */
  9496. function createProgressMeter(
  9497. progressMax, progressCallback, progressPercentMinCheckInterval) {
  9498. checkDefinedProgressParams(
  9499. progressCallback, progressPercentMinCheckInterval);
  9500. return new utils.ProgressMeter(
  9501. progressMax, progressCallback, progressPercentMinCheckInterval);
  9502. }
  9503. /**
  9504. * Provides utility functionality for working with proofs.
  9505. *
  9506. * @class utils
  9507. * @memberof proofs
  9508. */
  9509. box.proofs.utils = (function() {
  9510. /**
  9511. * Deserializes a Proof JSON string representation to a Proof object.
  9512. *
  9513. * @function
  9514. * @memberof proofs.utils
  9515. * @param jsonAsString
  9516. * {JSON} a JSON representation of a proof.
  9517. * @returns a new Proof, created from the received string.
  9518. */
  9519. function deserializeProof(jsonAsString) {
  9520. var proofJson = JSON.parse(jsonAsString).zkProof;
  9521. var q = converters.base64ToBigInteger(proofJson.q);
  9522. var hash = new box.commons.mathematical.Exponent(
  9523. q, converters.base64ToBigInteger(proofJson.hash));
  9524. var values = [];
  9525. for (var i = 0; i < proofJson.values.length; i++) {
  9526. values.push(new box.commons.mathematical.Exponent(
  9527. q, converters.base64ToBigInteger(proofJson.values[i])));
  9528. }
  9529. return new box.proofs.Proof(hash, values);
  9530. }
  9531. /**
  9532. * Deserializes a ProofPreComputedValues JSON string representation to a
  9533. * ProofPreComputedValues object.
  9534. *
  9535. * @function
  9536. * @memberof proofs.utils
  9537. * @param jsonAsString
  9538. * {JSON} a JSON representation of a pre-computed value.
  9539. * @returns a new ProofPreComputedValues, created from the received
  9540. * string.
  9541. */
  9542. function deserializeProofPreComputedValues(jsonAsString) {
  9543. var proofPreComputedValuesJson = JSON.parse(jsonAsString).preComputed;
  9544. var p = converters.base64ToBigInteger(proofPreComputedValuesJson.p);
  9545. var q = converters.base64ToBigInteger(proofPreComputedValuesJson.q);
  9546. var exponentValues = proofPreComputedValuesJson.exponents;
  9547. var exponents = [];
  9548. var value;
  9549. for (var i = 0; i < exponentValues.length; i++) {
  9550. value = converters.base64ToBigInteger(exponentValues[i]);
  9551. exponents.push(new box.commons.mathematical.Exponent(q, value));
  9552. }
  9553. var phiOutputValues = proofPreComputedValuesJson.phiOutputs;
  9554. var phiOutputs = [];
  9555. for (var j = 0; j < phiOutputValues.length; j++) {
  9556. value = converters.base64ToBigInteger(phiOutputValues[j]);
  9557. phiOutputs.push(
  9558. new box.commons.mathematical.ZpGroupElement(value, p, q));
  9559. }
  9560. return new box.proofs.ProofPreComputedValues(exponents, phiOutputs);
  9561. }
  9562. return {
  9563. deserializeProof: deserializeProof,
  9564. deserializeProofPreComputedValues: deserializeProofPreComputedValues
  9565. };
  9566. })();
  9567. };
  9568. /*
  9569. * Copyright 2018 Scytl Secure Electronic Voting SA
  9570. *
  9571. * All rights reserved
  9572. *
  9573. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  9574. */
  9575. cryptolib.modules.proofs = cryptolib.modules.proofs || {};
  9576. /**
  9577. * Allows several cryptographic proofs to be generated and verified.
  9578. * <P>
  9579. */
  9580. cryptolib.modules.proofs.service = function(box) {
  9581. 'use strict';
  9582. box.proofs = box.proofs || {};
  9583. box.proofs.service = {};
  9584. var proofsFactory;
  9585. var f = function(box) {
  9586. proofsFactory = new box.proofs.ProofsFactory();
  9587. };
  9588. f.policies = {
  9589. proofs: {
  9590. messagedigest: {
  9591. algorithm: box.policies.proofs.messagedigest.algorithm,
  9592. provider: box.policies.proofs.messagedigest.provider
  9593. },
  9594. secureRandom: {provider: box.policies.proofs.secureRandom.provider},
  9595. charset: box.policies.proofs.charset
  9596. },
  9597. primitives: {
  9598. secureRandom: {provider: box.policies.primitives.secureRandom.provider}
  9599. }
  9600. };
  9601. cryptolib(
  9602. 'proofs.implementation', 'primitives.securerandom', 'commons.exceptions',
  9603. 'commons.mathematical', f);
  9604. /**
  9605. * Creates a Schnorr proof.
  9606. *
  9607. * @param voterID
  9608. * The voter ID. This should be a string.
  9609. * @param electionID
  9610. * The election event ID. This should be a string.
  9611. * @param exponentiatedElement
  9612. * The exponentiated element. This should be an element of the
  9613. * received group.
  9614. * @param witness
  9615. * The witness. This should be an Exponent of the received group.
  9616. * @param group
  9617. * The mathematical group. This should be a Zp subgroup.
  9618. * @param progressCallbackOrPreComputedValues
  9619. * Progress callback function or pre-computed values (optional).
  9620. * @param progressPercentMinCheckInterval
  9621. * Progress percentage minimum check interval, if the previous
  9622. * parameter is a progressCallback function (optional).
  9623. *
  9624. * @returns The Schnorr proof.
  9625. */
  9626. box.proofs.service.createSchnorrProof = function(
  9627. voterID, electionID, exponentiatedElement, witness, group,
  9628. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9629. var proofGenerator =
  9630. proofsFactory.createSchnorrProofGenerator(voterID, electionID, group);
  9631. if (!progressCallbackOrPreComputedValues) {
  9632. return proofGenerator.generate(exponentiatedElement, witness);
  9633. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9634. var preComputedValues = progressCallbackOrPreComputedValues;
  9635. return proofGenerator.generate(
  9636. exponentiatedElement, witness, preComputedValues);
  9637. } else {
  9638. var progressCallback = progressCallbackOrPreComputedValues;
  9639. return proofGenerator
  9640. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9641. .generate(exponentiatedElement, witness);
  9642. }
  9643. };
  9644. /**
  9645. * Creates an exponentiation proof.
  9646. *
  9647. * @param exponentiatedElements
  9648. * The exponentiated elements. These should consist of the
  9649. * following base elements, exponentiated with the specified
  9650. * exponent.
  9651. * @param baseElements
  9652. * The base elements used for the exponentiations. These should
  9653. * correspond to elements of the specified group.
  9654. * @param exponent
  9655. * The exponent for which this proof is to be generated. It
  9656. * should be an exponent of the specified group.
  9657. * @param group
  9658. * The mathematical group. This should be a Zp subgroup.
  9659. * @param progressCallbackOrPreComputedValues
  9660. * Progress callback function or pre-computed values (optional).
  9661. * @param progressPercentMinCheckInterval
  9662. * Progress percentage minimum check interval, if the previous
  9663. * parameter is a progressCallback function (optional).
  9664. *
  9665. * @returns The exponentiation proof.
  9666. */
  9667. box.proofs.service.createExponentiationProof = function(
  9668. exponentiatedElements, baseElements, exponent, group,
  9669. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9670. var proofGenerator =
  9671. proofsFactory.createExponentiationProofGenerator(baseElements, group);
  9672. if (!progressCallbackOrPreComputedValues) {
  9673. return proofGenerator.generate(exponentiatedElements, exponent);
  9674. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9675. var preComputedValues = progressCallbackOrPreComputedValues;
  9676. return proofGenerator.generate(
  9677. exponentiatedElements, exponent, preComputedValues);
  9678. } else {
  9679. var progressCallback = progressCallbackOrPreComputedValues;
  9680. return proofGenerator
  9681. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9682. .generate(exponentiatedElements, exponent);
  9683. }
  9684. };
  9685. /**
  9686. * Creates a plaintext proof.
  9687. *
  9688. * @param publicKey
  9689. * The primary public key. This should be an ElGamal public key.
  9690. * @param ciphertext
  9691. * The ciphertext. This should be the output from ElGamal
  9692. * encryption.
  9693. * @param plaintext
  9694. * The plaintext. This should be an array of elements of the
  9695. * received group.
  9696. * @param witness
  9697. * The witness. This should be an Exponent of the received group.
  9698. * @param group
  9699. * The mathematical group. This should be a Zp subgroup.
  9700. * @param progressCallbackOrPreComputedValues
  9701. * Progress callback function or pre-computed values (optional).
  9702. * @param progressPercentMinCheckInterval
  9703. * Progress percentage minimum check interval, if the previous
  9704. * parameter is a progressCallback function (optional).
  9705. *
  9706. * @returns The plaintext proof.
  9707. */
  9708. box.proofs.service.createPlaintextProof = function(
  9709. publicKey, ciphertext, plaintext, witness, group,
  9710. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9711. var proofGenerator =
  9712. proofsFactory.createPlaintextProofGenerator(publicKey, group);
  9713. if (!progressCallbackOrPreComputedValues) {
  9714. return proofGenerator.generate(ciphertext, plaintext, witness);
  9715. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9716. var preComputedValues = progressCallbackOrPreComputedValues;
  9717. return proofGenerator.generate(
  9718. ciphertext, plaintext, witness, preComputedValues);
  9719. } else {
  9720. var progressCallback = progressCallbackOrPreComputedValues;
  9721. return proofGenerator
  9722. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9723. .generate(ciphertext, plaintext, witness);
  9724. }
  9725. };
  9726. /**
  9727. * Creates a simple plaintext equality Proof.
  9728. *
  9729. * @param primaryCiphertext
  9730. * The primary ciphertext. This should be the output from ElGamal
  9731. * encryption.
  9732. * @param primaryPublicKey
  9733. * The primary public key. This should be an ElGamal public key.
  9734. * @param witness
  9735. * The witness of the proof. This should be an Exponent of the
  9736. * received group.
  9737. * @param secondaryCiphertext
  9738. * The secondary ciphertext. This should be the output from
  9739. * ElGamal encryption.
  9740. * @param secondaryPublicKey
  9741. * The secondary public key. This should be an ElGamal public
  9742. * key.
  9743. * @param group
  9744. * The mathematical group. This should be a Zp subgroup.
  9745. * @param progressCallbackOrPreComputedValues
  9746. * Progress callback function or pre-computed values (optional).
  9747. * @param progressPercentMinCheckInterval
  9748. * Progress percentage minimum check interval, if the previous
  9749. * parameter is a progressCallback function (optional).
  9750. *
  9751. * @returns The simple plaintext equality proof.
  9752. */
  9753. box.proofs.service.createSimplePlaintextEqualityProof = function(
  9754. primaryCiphertext, primaryPublicKey, witness, secondaryCiphertext,
  9755. secondaryPublicKey, group, progressCallbackOrPreComputedValues,
  9756. progressPercentMinCheckInterval) {
  9757. var proofGenerator =
  9758. proofsFactory.createSimplePlaintextEqualityProofGenerator(
  9759. primaryPublicKey, secondaryPublicKey, group);
  9760. if (!progressCallbackOrPreComputedValues) {
  9761. return proofGenerator.generate(
  9762. primaryCiphertext, secondaryCiphertext, witness);
  9763. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9764. var preComputedValues = progressCallbackOrPreComputedValues;
  9765. return proofGenerator.generate(
  9766. primaryCiphertext, secondaryCiphertext, witness, preComputedValues);
  9767. } else {
  9768. var progressCallback = progressCallbackOrPreComputedValues;
  9769. return proofGenerator
  9770. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9771. .generate(primaryCiphertext, secondaryCiphertext, witness);
  9772. }
  9773. };
  9774. /**
  9775. * Creates a plaintext equality proof.
  9776. *
  9777. * @param primaryCiphertext
  9778. * The primary ciphertext. This should be the output from ElGamal
  9779. * encryption.
  9780. * @param primaryPublicKey
  9781. * The primary public key. This should be an ElGamal public key.
  9782. * @param primaryWitness
  9783. * The primary witness of the proof. This should be an Exponent
  9784. * of the received group.
  9785. * @param secondaryCiphertext
  9786. * The secondary ciphertext. This should be the output from
  9787. * ElGamal encryption.
  9788. * @param secondaryPublicKey
  9789. * The secondary public key. This should be an ElGamal public
  9790. * key.
  9791. * @param secondaryWitness
  9792. * The secondary witness of the proof. This should be an Exponent
  9793. * of the received group.
  9794. * @param group
  9795. * The mathematical group. This should be a Zp subgroup.
  9796. * @param progressCallbackOrPreComputedValues
  9797. * Progress callback function or pre-computed values (optional).
  9798. * @param progressPercentMinCheckInterval
  9799. * Progress percentage minimum check interval, if the previous
  9800. * parameter is a progressCallback function (optional).
  9801. *
  9802. * @returns The plaintext equality proof.
  9803. */
  9804. box.proofs.service.createPlaintextEqualityProof = function(
  9805. primaryCiphertext, primaryPublicKey, primaryWitness, secondaryCiphertext,
  9806. secondaryPublicKey, secondaryWitness, group,
  9807. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9808. var proofGenerator = proofsFactory.createPlaintextEqualityProofGenerator(
  9809. primaryPublicKey, secondaryPublicKey, group);
  9810. if (!progressCallbackOrPreComputedValues) {
  9811. return proofGenerator.generate(
  9812. primaryCiphertext, primaryWitness, secondaryCiphertext,
  9813. secondaryWitness);
  9814. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9815. var preComputedValues = progressCallbackOrPreComputedValues;
  9816. return proofGenerator.generate(
  9817. primaryCiphertext, primaryWitness, secondaryCiphertext,
  9818. secondaryWitness, preComputedValues);
  9819. } else {
  9820. var progressCallback = progressCallbackOrPreComputedValues;
  9821. return proofGenerator
  9822. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9823. .generate(
  9824. primaryCiphertext, primaryWitness, secondaryCiphertext,
  9825. secondaryWitness);
  9826. }
  9827. };
  9828. /**
  9829. * Creates a plaintext exponent equality proof.
  9830. *
  9831. * @param ciphertext
  9832. * The ciphertext. This should be the output from ElGamal
  9833. * encryption.
  9834. * @param plaintext
  9835. * The plaintext. It should be an array of members of the
  9836. * received group.
  9837. * @param primaryWitness
  9838. * The primary witness. This should be an Exponent of the
  9839. * received group.
  9840. * @param secondaryWitness
  9841. * The secondary witness. This should be an Exponent of the
  9842. * received group.
  9843. * @param group
  9844. * The mathematical group. This should be a Zp subgroup.
  9845. * @param progressCallbackOrPreComputedValues
  9846. * Progress callback function or pre-computed values (optional).
  9847. * @param progressPercentMinCheckInterval
  9848. * Progress percentage minimum check interval, if the previous
  9849. * parameter is a progressCallback function (optional).
  9850. *
  9851. * @returns The plaintext exponent equality proof.
  9852. */
  9853. box.proofs.service.createPlaintextExponentEqualityProof = function(
  9854. ciphertext, plaintext, primaryWitness, secondaryWitness, group,
  9855. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9856. var proofGenerator =
  9857. proofsFactory.createPlaintextExponentEqualityProofGenerator(
  9858. plaintext, group);
  9859. if (!progressCallbackOrPreComputedValues) {
  9860. return proofGenerator.generate(
  9861. ciphertext, primaryWitness, secondaryWitness);
  9862. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9863. var preComputedValues = progressCallbackOrPreComputedValues;
  9864. return proofGenerator.generate(
  9865. ciphertext, primaryWitness, secondaryWitness, preComputedValues);
  9866. } else {
  9867. var progressCallback = progressCallbackOrPreComputedValues;
  9868. return proofGenerator
  9869. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9870. .generate(ciphertext, primaryWitness, secondaryWitness);
  9871. }
  9872. };
  9873. /**
  9874. * Creates an OR-proof.
  9875. *
  9876. * @param publicKey
  9877. * The public key. This should be an ElGamal public key.
  9878. * @param ciphertext
  9879. * The ciphertext of the mathematical group element that was
  9880. * encrypted. This should be the output from ElGamal encryption.
  9881. * @param witness
  9882. * The witness used to generate the ciphertext. This should be an
  9883. * Exponent of the received group.
  9884. * @param elements
  9885. * The mathematical group elements, one of which was encrypted.
  9886. * This should be an array of elements of the received group.
  9887. * @param index
  9888. * The index of the mathematical group element that was
  9889. * encrypted. This should be an integer.
  9890. * @param data
  9891. * Any extra data to use for the proof generation. This should be
  9892. * a String. NOTE: If this parameter is null, then data will be set
  9893. * to empty string.
  9894. * @param group
  9895. * The mathematical group. This should be a Zp subgroup.
  9896. * @param progressCallbackOrPreComputedValues
  9897. * Progress callback function or pre-computed values (optional).
  9898. * @param progressPercentMinCheckInterval
  9899. * Progress percentage minimum check interval, if the previous
  9900. * parameter is a progressCallback function (optional).
  9901. *
  9902. * @returns The OR-proof.
  9903. */
  9904. box.proofs.service.createORProof = function(
  9905. publicKey, ciphertext, witness, elements, index, data, group,
  9906. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  9907. var proofGenerator =
  9908. proofsFactory.createORProofGenerator(publicKey, elements.length, group);
  9909. if (!progressCallbackOrPreComputedValues) {
  9910. return proofGenerator.generate(
  9911. ciphertext, witness, elements, index, data);
  9912. } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
  9913. var preComputedValues = progressCallbackOrPreComputedValues;
  9914. return proofGenerator.generate(
  9915. ciphertext, witness, elements, index, data, preComputedValues);
  9916. } else {
  9917. var progressCallback = progressCallbackOrPreComputedValues;
  9918. return proofGenerator
  9919. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9920. .generate(ciphertext, witness, elements, index, data);
  9921. }
  9922. };
  9923. /**
  9924. * Verifies a Schnorr proof.
  9925. *
  9926. * @param exponentiatedElement
  9927. * The exponentiated element. This should be an element of the
  9928. * specified group.
  9929. * @param voterID
  9930. * The voter IS. This should be a string.
  9931. * @param electionID
  9932. * The election event ID. This should be a string.
  9933. * @param proof
  9934. * The proof that is to be verified.
  9935. * @param group
  9936. * The mathematical group. This should be a Zp subgroup.
  9937. * @param progressCallback
  9938. * Progress callback function (optional).
  9939. * @param progressPercentMinCheckInterval
  9940. * Progress percentage minimum check interval (optional).
  9941. *
  9942. * @returns true if the Schnorr Proof can be verified, false otherwise.
  9943. */
  9944. box.proofs.service.verifySchnorrProof = function(
  9945. element, voterID, electionEventID, proof, group, progressCallback,
  9946. progressPercentMinCheckInterval) {
  9947. return proofsFactory
  9948. .createSchnorrProofVerifier(
  9949. element, voterID, electionEventID, proof, group)
  9950. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9951. .verify();
  9952. };
  9953. /**
  9954. * Verifies an exponentiation proof.
  9955. *
  9956. * @param exponentiatedElements
  9957. * The exponentiated elements. These should consist of the
  9958. * following base elements, exponentiated with the specified
  9959. * exponent.
  9960. * @param baseElements
  9961. * The base elements used for the exponentiations. These should
  9962. * correspond to elements of the specified group.
  9963. * @param proof
  9964. * The proof that is to be verified.
  9965. * @param group
  9966. * The mathematical group. This should be a Zp subgroup.
  9967. * @param progressCallback
  9968. * Progress callback function (optional).
  9969. * @param progressPercentMinCheckInterval
  9970. * Progress percentage minimum check interval (optional).
  9971. *
  9972. * @returns true if the exponentiation proof can be verified, false
  9973. * otherwise.
  9974. */
  9975. box.proofs.service.verifyExponentiationProof = function(
  9976. exponentiatedElements, baseElements, proof, group, progressCallback,
  9977. progressPercentMinCheckInterval) {
  9978. return proofsFactory
  9979. .createExponentiationProofVerifier(
  9980. exponentiatedElements, baseElements, proof, group)
  9981. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  9982. .verify();
  9983. };
  9984. /**
  9985. * Verifies a plaintext proof.
  9986. *
  9987. * @param publicKey
  9988. * The primary public key. This should be an ElGamal public key.
  9989. * @param ciphertext
  9990. * The ciphertext. This should be the output from ElGamal
  9991. * encryption.
  9992. * @param plaintext
  9993. * The plaintext. This should be an array of elements of the
  9994. * received group.
  9995. * @param proof
  9996. * The proof that is to be verified.
  9997. * @param group
  9998. * The mathematical group. This should be a Zp subgroup.
  9999. * @param progressCallback
  10000. * Progress callback function (optional).
  10001. * @param progressPercentMinCheckInterval
  10002. * Progress percentage minimum check interval (optional).
  10003. * @returns true if the plaintext proof can be verified, false otherwise.
  10004. */
  10005. box.proofs.service.verifyPlaintextProof = function(
  10006. publicKey, ciphertext, plaintext, proof, group, progressCallback,
  10007. progressPercentMinCheckInterval) {
  10008. return proofsFactory.createPlaintextProofVerifier(publicKey, group)
  10009. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  10010. .verify(ciphertext, plaintext, proof);
  10011. };
  10012. /**
  10013. * Verifies a simple plaintext equality proof.
  10014. *
  10015. * @param primaryCiphertext
  10016. * The primary ciphertext. This should be the output from ElGamal
  10017. * encryption.
  10018. * @param primaryPublicKey
  10019. * The primary public key. This should be an ElGamal public key.
  10020. * @param secondaryCiphertext
  10021. * The secondary ciphertext. This should be the output from
  10022. * ElGamal encryption.
  10023. * @param secondaryPublicKey
  10024. * The secondary public key. This should be an ElGamal public
  10025. * key.
  10026. * @param proof
  10027. * The proof that is to be verified.
  10028. * @param group
  10029. * The mathematical group. This should be a Zp subgroup.
  10030. * @param progressCallback
  10031. * Progress callback function (optional).
  10032. * @param progressPercentMinCheckInterval
  10033. * Progress percentage minimum check interval (optional).
  10034. *
  10035. * @returns true if the simple plaintext equality proof can be verified,
  10036. * false otherwise.
  10037. */
  10038. box.proofs.service.verifySimplePlaintextEqualityProof = function(
  10039. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  10040. secondaryPublicKey, proof, group, progressCallback,
  10041. progressPercentMinCheckInterval) {
  10042. return proofsFactory
  10043. .createSimplePlaintextEqualityProofVerifier(
  10044. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  10045. secondaryPublicKey, proof, group)
  10046. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  10047. .verify();
  10048. };
  10049. /**
  10050. * Verifies a plaintext equality proof.
  10051. *
  10052. * @param primaryCiphertext
  10053. * The primary ciphertext. This should be the output from ElGamal
  10054. * encryption.
  10055. * @param primaryPublicKey
  10056. * The primary public key. This should be an ElGamal public key.
  10057. * @param secondaryCiphertext
  10058. * The secondary ciphertext. This should be the output from
  10059. * ElGamal encryption.
  10060. * @param secondaryPublicKey
  10061. * The secondary public key. This should be an ElGamal public
  10062. * key.
  10063. * @param proof
  10064. * The proof that is to be verified.
  10065. * @param group
  10066. * The mathematical group. This should be a Zp subgroup.
  10067. * @param progressCallback
  10068. * Progress callback function (optional).
  10069. * @param progressPercentMinCheckInterval
  10070. * Progress percentage minimum check interval (optional).
  10071. *
  10072. * @returns true if the plaintext equality proof can be verified, false
  10073. * otherwise.
  10074. */
  10075. box.proofs.service.verifyPlaintextEqualityProof = function(
  10076. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  10077. secondaryPublicKey, proof, group, progressCallback,
  10078. progressPercentMinCheckInterval) {
  10079. return proofsFactory
  10080. .createPlaintextEqualityProofVerifier(
  10081. primaryCiphertext, primaryPublicKey, secondaryCiphertext,
  10082. secondaryPublicKey, proof, group)
  10083. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  10084. .verify();
  10085. };
  10086. /**
  10087. * Verifies a plaintext exponent equality proof.
  10088. *
  10089. * @param ciphertext
  10090. * The ciphertext. This should be the output from ElGamal
  10091. * encryption.
  10092. * @param baseElements
  10093. * The array of base elements. All of these elements should be
  10094. * members of the received group.
  10095. * @param witness1
  10096. * The primary witness. This should be an Exponent.
  10097. * @param witness2
  10098. * The secondary witness. This should be an Exponent.
  10099. * @param proof
  10100. * The proof that is to be verified.
  10101. * @param group
  10102. * The mathematical group. This should be a Zp subgroup.
  10103. * @param progressCallback
  10104. * Progress callback function (optional).
  10105. * @param progressPercentMinCheckInterval
  10106. * Progress percentage minimum check interval (optional).
  10107. *
  10108. * @returns true if the plaintext exponent equality proof can be verified,
  10109. * false otherwise.
  10110. */
  10111. box.proofs.service.verifyPlaintextExponentEqualityProof = function(
  10112. ciphertext, baseElements, proof, group, progressCallback,
  10113. progressPercentMinCheckInterval) {
  10114. return proofsFactory
  10115. .createPlaintextExponentEqualityProofVerifier(
  10116. ciphertext, baseElements, proof, group)
  10117. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  10118. .verify();
  10119. };
  10120. /**
  10121. * Verifies an OR-proof.
  10122. *
  10123. * @param publicKey
  10124. * The public key. This should be an ElGamal public key.
  10125. * @param ciphertext
  10126. * The ciphertext of the mathematical group element that was
  10127. * encrypted. This should be the output from ElGamal encryption.
  10128. * @param elements
  10129. * The mathematical group elements, one of which was encrypted.
  10130. * This should be an array of elements of the received group.
  10131. * @param data
  10132. * Any extra data used for the proof generation. This should be a
  10133. * String. NOTE: If this parameter is null, then data will be set
  10134. * to empty string.
  10135. * @param proof
  10136. * The proof that is to be verified.
  10137. * @param group
  10138. * The mathematical group. This should be a Zp subgroup.
  10139. * @param progressCallback
  10140. * Progress callback function (optional).
  10141. * @param progressPercentMinCheckInterval
  10142. * Progress percentage minimum check interval (optional).
  10143. * @returns true if the OR-proof can be verified, false otherwise.
  10144. */
  10145. box.proofs.service.verifyORProof = function(
  10146. publicKey, ciphertext, elements, data, proof, group, progressCallback,
  10147. progressPercentMinCheckInterval) {
  10148. return proofsFactory
  10149. .createORProofVerifier(publicKey, elements.length, group)
  10150. .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
  10151. .verify(ciphertext, elements, data, proof);
  10152. };
  10153. /**
  10154. * Pre-computes a Schnorr proof. IMPORTANT: The same pre-computed values
  10155. * must not be used twice.
  10156. *
  10157. * @param voterID
  10158. * The voter ID. This should be a string.
  10159. * @param electionID
  10160. * The election event ID. This should be a string.
  10161. * @param group
  10162. * The mathematical group. This should be a Zp subgroup.
  10163. * @param progressCallback
  10164. * Progress callback function or pre-computed values (optional).
  10165. * @param progressPercentMinCheckInterval
  10166. * Progress percentage minimum check interval, if the previous
  10167. * parameter is a progressCallback function (optional).
  10168. *
  10169. * @returns The Schnorr proof pre-computed values.
  10170. */
  10171. box.proofs.service.preComputeSchnorrProof = function(
  10172. voterID, electionID, group, progressCallbackOrPreComputedValues,
  10173. progressPercentMinCheckInterval) {
  10174. return proofsFactory.createSchnorrProofGenerator(voterID, electionID, group)
  10175. .initProgressMeter(
  10176. progressCallbackOrPreComputedValues,
  10177. progressPercentMinCheckInterval)
  10178. .preCompute();
  10179. };
  10180. /**
  10181. * Pre-computes an exponentiation proof. IMPORTANT: The same pre-computed
  10182. * values must not be used twice.
  10183. *
  10184. * @param baseElements
  10185. * The base elements used for the exponentiations. These should
  10186. * correspond to elements of the specified group.
  10187. * @param group
  10188. * The mathematical group. This should be a Zp subgroup.
  10189. * @param progressCallback
  10190. * Progress callback function or pre-computed values (optional).
  10191. * @param progressPercentMinCheckInterval
  10192. * Progress percentage minimum check interval, if the previous
  10193. * parameter is a progressCallback function (optional).
  10194. *
  10195. * @returns The exponentiation proof pre-computed values.
  10196. */
  10197. box.proofs.service.preComputeExponentiationProof = function(
  10198. baseElements, group, progressCallbackOrPreComputedValues,
  10199. progressPercentMinCheckInterval) {
  10200. return proofsFactory.createExponentiationProofGenerator(baseElements, group)
  10201. .initProgressMeter(
  10202. progressCallbackOrPreComputedValues,
  10203. progressPercentMinCheckInterval)
  10204. .preCompute();
  10205. };
  10206. /**
  10207. * Pre-computes a plaintext proof. IMPORTANT: The same pre-computed values
  10208. * must not be used twice.
  10209. *
  10210. * @param publicKey
  10211. * The primary public key. This should be an ElGamal public key.
  10212. * @param group
  10213. * The mathematical group. This should be a Zp subgroup.
  10214. * @param progressCallback
  10215. * Progress callback function or pre-computed values (optional).
  10216. * @param progressPercentMinCheckInterval
  10217. * Progress percentage minimum check interval, if the previous
  10218. * parameter is a progressCallback function (optional).
  10219. *
  10220. * @returns The plaintext proof pre-computed values.
  10221. */
  10222. box.proofs.service.preComputePlaintextProof = function(
  10223. publicKey, group, progressCallbackOrPreComputedValues,
  10224. progressPercentMinCheckInterval) {
  10225. return proofsFactory.createPlaintextProofGenerator(publicKey, group)
  10226. .initProgressMeter(
  10227. progressCallbackOrPreComputedValues,
  10228. progressPercentMinCheckInterval)
  10229. .preCompute();
  10230. };
  10231. /**
  10232. * Pre-computes values for a simple plaintext equality proof. IMPORTANT: The
  10233. * same pre-computed values must not be used twice.
  10234. *
  10235. * @param primaryPublicKey
  10236. * The primary public key. This should be an ElGamal public key.
  10237. * @param secondaryPublicKey
  10238. * The secondary public key. This should be an ElGamal public
  10239. * key.
  10240. * @param group
  10241. * The mathematical group. This should be a Zp subgroup.
  10242. * @param progressCallback
  10243. * Progress callback function or pre-computed values (optional).
  10244. * @param progressPercentMinCheckInterval
  10245. * Progress percentage minimum check interval, if the previous
  10246. * parameter is a progressCallback function (optional).
  10247. *
  10248. * @returns The simple plaintext equality proof pre-computed values.
  10249. */
  10250. box.proofs.service.preComputeSimplePlaintextEqualityProof = function(
  10251. primaryPublicKey, secondaryPublicKey, group,
  10252. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  10253. return proofsFactory
  10254. .createSimplePlaintextEqualityProofGenerator(
  10255. primaryPublicKey, secondaryPublicKey, group)
  10256. .initProgressMeter(
  10257. progressCallbackOrPreComputedValues,
  10258. progressPercentMinCheckInterval)
  10259. .preCompute();
  10260. };
  10261. /**
  10262. * Pre-computes values for a plaintext equality proof. IMPORTANT: The same
  10263. * pre-computed values must not be used twice.
  10264. *
  10265. * @param primaryPublicKey
  10266. * The primary public key. This should be an ElGamal public key.
  10267. * @param secondaryPublicKey
  10268. * The secondary public key. This should be an ElGamal public
  10269. * key.
  10270. * @param group
  10271. * The mathematical group. This should be a Zp subgroup.
  10272. * @param progressCallback
  10273. * Progress callback function or pre-computed values (optional).
  10274. * @param progressPercentMinCheckInterval
  10275. * Progress percentage minimum check interval, if the previous
  10276. * parameter is a progressCallback function (optional).
  10277. *
  10278. * @returns The plaintext equality proof pre-computed values.
  10279. */
  10280. box.proofs.service.preComputePlaintextEqualityProof = function(
  10281. primaryPublicKey, secondaryPublicKey, group,
  10282. progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
  10283. return proofsFactory
  10284. .createPlaintextEqualityProofGenerator(
  10285. primaryPublicKey, secondaryPublicKey, group)
  10286. .initProgressMeter(
  10287. progressCallbackOrPreComputedValues,
  10288. progressPercentMinCheckInterval)
  10289. .preCompute();
  10290. };
  10291. /**
  10292. * Returns pre-computed values for a plaintext exponent equality proof.
  10293. * IMPORTANT: The same pre-computed values must not be used twice.
  10294. *
  10295. * @param plaintext
  10296. * The plaintext. It should be an array of members of the
  10297. * received group.
  10298. * @param group
  10299. * The mathematical group. This should be a Zp subgroup.
  10300. * @param progressCallback
  10301. * Progress callback function or pre-computed values (optional).
  10302. * @param progressPercentMinCheckInterval
  10303. * Progress percentage minimum check interval, if the previous
  10304. * parameter is a progressCallback function (optional).
  10305. *
  10306. * @returns The plaintext exponent equality proof pre-computed values.
  10307. */
  10308. box.proofs.service.preComputePlaintextExponentEqualityProof = function(
  10309. plaintext, group, progressCallbackOrPreComputedValues,
  10310. progressPercentMinCheckInterval) {
  10311. return proofsFactory
  10312. .createPlaintextExponentEqualityProofGenerator(plaintext, group)
  10313. .initProgressMeter(
  10314. progressCallbackOrPreComputedValues,
  10315. progressPercentMinCheckInterval)
  10316. .preCompute();
  10317. };
  10318. /**
  10319. * Pre-computes an OR-proof. IMPORTANT: The same pre-computed values must
  10320. * not be used twice.
  10321. *
  10322. * @param publicKey
  10323. * The public key. This should be an ElGamal public key.
  10324. * @param numElements
  10325. * The number of elements belonging to the received mathematical
  10326. * group that will be used for the proof, one of which will be
  10327. * encrypted.
  10328. * @param group
  10329. * The mathematical group. This should be a Zp subgroup.
  10330. * @param progressCallback
  10331. * Progress callback function or pre-computed values (optional).
  10332. * @param progressPercentMinCheckInterval
  10333. * Progress percentage minimum check interval, if the previous
  10334. * parameter is a progressCallback function (optional).
  10335. *
  10336. * @returns The OR-proof pre-computed values.
  10337. */
  10338. box.proofs.service.preComputeORProof = function(
  10339. publicKey, numElements, group, progressCallbackOrPreComputedValues,
  10340. progressPercentMinCheckInterval) {
  10341. return proofsFactory.createORProofGenerator(publicKey, numElements, group)
  10342. .initProgressMeter(
  10343. progressCallbackOrPreComputedValues,
  10344. progressPercentMinCheckInterval)
  10345. .preCompute();
  10346. };
  10347. /**
  10348. * Utility method that checks if the argument is instance of type
  10349. * ProofPreComputedValues.
  10350. *
  10351. * @param values
  10352. * argument to check.
  10353. * @returns {boolean} true if values is instance of ProofPreComputedValues.
  10354. */
  10355. function isPreComputedValues(values) {
  10356. return !!(values) && values.className === 'ProofPreComputedValues';
  10357. }
  10358. };
  10359. /*
  10360. * Copyright 2018 Scytl Secure Electronic Voting SA
  10361. *
  10362. * All rights reserved
  10363. *
  10364. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  10365. */
  10366. cryptolib.modules.stores = cryptolib.modules.stores || {};
  10367. /**
  10368. * Defines a pkcs12 store.
  10369. */
  10370. cryptolib.modules.stores.pkcs12 = function(box) {
  10371. 'use strict';
  10372. box.stores = box.stores || {};
  10373. box.stores.pkcs12 = {};
  10374. var converters;
  10375. var exceptions;
  10376. cryptolib('commons', function(box) {
  10377. converters = new box.commons.utils.Converters();
  10378. exceptions = box.commons.exceptions;
  10379. });
  10380. /**
  10381. * Defines a PKCS12.
  10382. *
  10383. * @param pkcs12DerB64
  10384. * PKCS12, as string in Base64 encoded DER format.
  10385. */
  10386. box.stores.pkcs12.Pkcs12 = function(pkcs12DerB64) {
  10387. this.pkcs12Der = converters.base64Decode(pkcs12DerB64);
  10388. this.pkcs12Asn1 = forge.asn1.fromDer(this.pkcs12Der, false);
  10389. };
  10390. box.stores.pkcs12.Pkcs12.prototype = {
  10391. /**
  10392. * Retrieves the private key of the PKCS12.
  10393. *
  10394. * @param passwordB64
  10395. * Password as string in Base64 encoded format.
  10396. * @return Private key of PKCS12, as string in PEM format.
  10397. */
  10398. getPrivateKey: function(passwordB64) {
  10399. var aliases = Array.prototype.slice.call(arguments, 1);
  10400. function isAliasInList(alias) {
  10401. var returnValue = false;
  10402. if (aliases.indexOf(alias) >= 0) {
  10403. returnValue = true;
  10404. }
  10405. return returnValue;
  10406. }
  10407. var privateKeyAlias = '';
  10408. try {
  10409. var password = converters.base64Decode(passwordB64);
  10410. var pkcs12 =
  10411. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10412. // Retrieve private key safe bag from PKCS12.
  10413. var privateKeys = {};
  10414. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10415. var safeContents = pkcs12.safeContents[i];
  10416. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10417. var safeBag = safeContents.safeBags[j];
  10418. if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
  10419. privateKeyAlias = safeBag.attributes.friendlyName[0];
  10420. if (aliases.length === 0 || isAliasInList(privateKeyAlias)) {
  10421. privateKeys[privateKeyAlias] =
  10422. forge.pki.privateKeyToPem(safeBag.key);
  10423. }
  10424. }
  10425. }
  10426. }
  10427. // Check whether any private key safe bags were found.
  10428. if (Object.getOwnPropertyNames(privateKeys).length === 0) {
  10429. throw new exceptions.CryptoLibException(
  10430. 'Could not find any private key safe bags in PKCS12.');
  10431. }
  10432. return privateKeys;
  10433. } catch (error) {
  10434. var errorMsg = 'Could not retrieve private key from PKCS12.';
  10435. if (privateKeyAlias.length > 0) {
  10436. errorMsg = 'Could not retrieve private key with alias ' +
  10437. privateKeyAlias + ' from PKCS12.';
  10438. }
  10439. throw new exceptions.CryptoLibException(errorMsg);
  10440. }
  10441. },
  10442. /**
  10443. * Retrieves the private key chain from the PKCS12.
  10444. *
  10445. * @param passwordB64
  10446. * Password as string in Base64 encoded format.
  10447. * @return Private key chain of PKCS12, as PrivateKeyChain object.
  10448. */
  10449. getPrivateKeyChain: function(passwordB64) {
  10450. try {
  10451. var password = converters.base64Decode(passwordB64);
  10452. var pkcs12 =
  10453. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10454. // Retrieve private key safe bags from PKCS12.
  10455. var privateKeyChain = new box.stores.pkcs12.PrivateKeyChain();
  10456. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10457. var safeContents = pkcs12.safeContents[i];
  10458. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10459. var safeBag = safeContents.safeBags[j];
  10460. if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
  10461. var alias = safeBag.attributes.friendlyName[0];
  10462. var privateKeyPem = forge.pki.privateKeyToPem(safeBag.key);
  10463. privateKeyChain.add(alias, privateKeyPem);
  10464. }
  10465. }
  10466. }
  10467. // Check whether any private key safe bags were found.
  10468. if (privateKeyChain.length === 0) {
  10469. throw new exceptions.CryptoLibException(
  10470. 'Could not find any private key safe bags in PKCS12.');
  10471. }
  10472. return privateKeyChain;
  10473. } catch (error) {
  10474. throw new exceptions.CryptoLibException(
  10475. 'Could not retrieve private key chain from PKCS12.', error);
  10476. }
  10477. },
  10478. /**
  10479. * Retrieves the certificate chain of the PKCS12.
  10480. *
  10481. * @param passwordB64
  10482. * Password as string in Base64 encoded format.
  10483. * @return Certificate chain of PKCS12, as array of strings in PEM
  10484. * format.
  10485. */
  10486. getCertificateChain: function(passwordB64) {
  10487. try {
  10488. var password = converters.base64Decode(passwordB64);
  10489. var pkcs12 =
  10490. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10491. // Retrieve certificate safe bags from PKCS12.
  10492. var certificatePemChain = [];
  10493. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10494. var safeContents = pkcs12.safeContents[i];
  10495. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10496. var safeBag = safeContents.safeBags[j];
  10497. if (safeBag.type === forge.pki.oids.certBag) {
  10498. var certificatePem = forge.pki.certificateToPem(safeBag.cert);
  10499. certificatePemChain.push(certificatePem);
  10500. }
  10501. }
  10502. }
  10503. // Check whether any certificate safe bags were found.
  10504. if (certificatePemChain.length === 0) {
  10505. throw new exceptions.CryptoLibException(
  10506. 'Could not find any certificate safe bags in PKCS12.');
  10507. }
  10508. return certificatePemChain;
  10509. } catch (error) {
  10510. throw new exceptions.CryptoLibException(
  10511. 'Could not retrieve certificate chain from PKCS12.', error);
  10512. }
  10513. },
  10514. /**
  10515. * Retrieves the certificate chain of the PKCS12 filtered by alias.
  10516. *
  10517. * @param passwordB64
  10518. * Password as string in Base64 encoded format.
  10519. * @param alias
  10520. * Alias to filter
  10521. * @return Certificate chain of PKCS12, as array of strings in PEM
  10522. * format.
  10523. */
  10524. getCertificateChainByAlias: function(passwordB64, alias) {
  10525. try {
  10526. var password = converters.base64Decode(passwordB64);
  10527. var pkcs12 =
  10528. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10529. var discardedBags = {};
  10530. var nextBagId = null;
  10531. // Retrieve certificate safe bags from PKCS12.
  10532. var certificatePemChain = [];
  10533. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10534. var safeContents = pkcs12.safeContents[i];
  10535. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10536. var safeBag = safeContents.safeBags[j];
  10537. if (safeBag.type === forge.pki.oids.certBag) {
  10538. var bagFound = null;
  10539. // if not initializated the chain, find the one with alias
  10540. // or if is the one that goes next into the list take it
  10541. if ((!nextBagId && safeBag.attributes &&
  10542. safeBag.attributes.friendlyName &&
  10543. safeBag.attributes.friendlyName[0] === alias) ||
  10544. (nextBagId && nextBagId === safeBag.cert.subject.hash)) {
  10545. bagFound = safeBag;
  10546. }
  10547. // otherwise, if not initializated and it's not the alias, save it
  10548. // for later use
  10549. else {
  10550. discardedBags[safeBag.cert.subject.hash] = safeBag;
  10551. }
  10552. // add the bag and check if we have the next one in the list we
  10553. // had
  10554. while (bagFound) {
  10555. // transform the current to PEM and save it
  10556. var certificatePem = forge.pki.certificateToPem(bagFound.cert);
  10557. certificatePemChain.push(certificatePem);
  10558. // we arrived to the root so we are done!
  10559. if (bagFound.cert.subject.hash === bagFound.cert.issuer.hash) {
  10560. return certificatePemChain;
  10561. }
  10562. // save which is the next bag we need
  10563. nextBagId = bagFound.cert.issuer.hash;
  10564. // go for the next in the list of discarded ones
  10565. bagFound = discardedBags[nextBagId];
  10566. }
  10567. }
  10568. }
  10569. }
  10570. // Check whether any certificate safe bags were found.
  10571. if (certificatePemChain.length === 0) {
  10572. throw new exceptions.CryptoLibException(
  10573. 'Could not find any certificates for that alias.');
  10574. }
  10575. return certificatePemChain;
  10576. } catch (error) {
  10577. throw new exceptions.CryptoLibException(
  10578. 'Could not retrieve certificate chain from PKCS12.', error);
  10579. }
  10580. },
  10581. /**
  10582. * Retrieves an issuer certificate from the certificate chain of the
  10583. * PKCS12, given the issuer common name.
  10584. *
  10585. * @param passwordB64
  10586. * Password as string in Base64 encoded format.
  10587. * @param issuerCn
  10588. * Issuer common name of certificate to retrieve, as string.
  10589. * @return Certificate with given issuer common name, as string in PEM
  10590. * format.
  10591. */
  10592. getCertificateByIssuer: function(passwordB64, issuerCn) {
  10593. try {
  10594. var password = converters.base64Decode(passwordB64);
  10595. var pkcs12 =
  10596. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10597. // Retrieve certificate from PKCS12.
  10598. var certificate = null;
  10599. var certificateFound = false;
  10600. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10601. var safeContents = pkcs12.safeContents[i];
  10602. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10603. var safeBag = safeContents.safeBags[j];
  10604. if (safeBag.type === forge.pki.oids.certBag &&
  10605. safeBag.cert.issuer.getField('CN').value === issuerCn) {
  10606. certificate = safeBag.cert;
  10607. certificateFound = true;
  10608. break;
  10609. }
  10610. }
  10611. if (certificateFound) {
  10612. break;
  10613. }
  10614. }
  10615. // Check whether certificate was found.
  10616. if (certificate === null) {
  10617. throw new exceptions.CryptoLibException(
  10618. 'Could not find certificate in PKCS12 with issuer common name ' +
  10619. issuerCn);
  10620. }
  10621. return forge.pki.certificateToPem(certificate);
  10622. } catch (error) {
  10623. throw new exceptions.CryptoLibException(
  10624. 'Could not retrieve certificate with issuer common name ' +
  10625. issuerCn + ' from PKCS12.',
  10626. error);
  10627. }
  10628. },
  10629. /**
  10630. * Retrieves the subject certificate from the certificate chain of the
  10631. * PKCS12, given the subject common name.
  10632. *
  10633. * @param passwordB64
  10634. * Password as string in Base64 encoded format.
  10635. * @param subjectCn
  10636. * Subject common name of certificate to retrieve, as string.
  10637. * @return Certificate with given issuer common name, as string in PEM
  10638. * format.
  10639. */
  10640. getCertificateBySubject: function(passwordB64, subjectCn) {
  10641. try {
  10642. var password = converters.base64Decode(passwordB64);
  10643. var pkcs12 =
  10644. forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
  10645. // Retrieve subject certificate from PKCS12.
  10646. var certificate = null;
  10647. var certificateFound = false;
  10648. for (var i = 0; i < pkcs12.safeContents.length; i++) {
  10649. var safeContents = pkcs12.safeContents[i];
  10650. for (var j = 0; j < safeContents.safeBags.length; j++) {
  10651. var safeBag = safeContents.safeBags[j];
  10652. if (safeBag.type === forge.pki.oids.certBag &&
  10653. safeBag.cert.subject.getField('CN').value === subjectCn) {
  10654. certificate = safeBag.cert;
  10655. certificateFound = true;
  10656. break;
  10657. }
  10658. }
  10659. if (certificateFound) {
  10660. break;
  10661. }
  10662. }
  10663. // Check whether certificate was found.
  10664. if (certificate === null) {
  10665. throw new exceptions.CryptoLibException(
  10666. 'Could not find certificate in PKCS12 with subject common name ' +
  10667. subjectCn);
  10668. }
  10669. return forge.pki.certificateToPem(certificate);
  10670. } catch (error) {
  10671. throw new exceptions.CryptoLibException(
  10672. 'Could not retrieve certificate with subject common name ' +
  10673. subjectCn + ' from PKCS12.',
  10674. error);
  10675. }
  10676. },
  10677. /**
  10678. * Retrieves the PKCS12 as a Base64 encoded DER string.
  10679. *
  10680. * @return PKCS12, as Base64 encoded DER string.
  10681. */
  10682. getBase64Encoded: function() {
  10683. return converters.base64Encode(this.pkcs12Der);
  10684. }
  10685. };
  10686. /**
  10687. * Container class for a chain of private keys to be inserted in a key
  10688. * store.
  10689. */
  10690. box.stores.pkcs12.PrivateKeyChain = function() {
  10691. this.map = {};
  10692. };
  10693. box.stores.pkcs12.PrivateKeyChain.prototype = {
  10694. /**
  10695. * Adds a private key to the chain.
  10696. *
  10697. * @param alias
  10698. * Alias of private key, as string.
  10699. * @param privateKeyPem
  10700. * Private key to add, as string in PEM format.
  10701. */
  10702. add: function(alias, privateKeyPem) {
  10703. this.map[alias] = privateKeyPem;
  10704. },
  10705. /**
  10706. * Retrieves a private key from the chain.
  10707. *
  10708. * @return Private key chain, as array of strings in PEM format.
  10709. */
  10710. get: function(alias) {
  10711. return this.map[alias];
  10712. }
  10713. };
  10714. };
  10715. /*
  10716. * Copyright 2018 Scytl Secure Electronic Voting SA
  10717. *
  10718. * All rights reserved
  10719. *
  10720. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  10721. */
  10722. cryptolib.modules.stores = cryptolib.modules.stores || {};
  10723. /**
  10724. * A module that provides stores services.
  10725. * <P>
  10726. */
  10727. cryptolib.modules.stores.service = function(box) {
  10728. 'use strict';
  10729. box.stores = box.stores || {};
  10730. box.stores.service = {};
  10731. var sks;
  10732. cryptolib('stores.sks', function(box) {
  10733. sks = box.stores.sks;
  10734. });
  10735. /**
  10736. * @static
  10737. *
  10738. * @returns a Sks object.
  10739. */
  10740. box.stores.service.loadStore = function(store) {
  10741. return new sks.SksReader(store);
  10742. };
  10743. };
  10744. /*
  10745. * Copyright 2018 Scytl Secure Electronic Voting SA
  10746. *
  10747. * All rights reserved
  10748. *
  10749. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  10750. */
  10751. /**
  10752. * Scytl Key Store. It is a custom keystore.
  10753. */
  10754. cryptolib.modules.stores.sks = function(box) {
  10755. 'use strict';
  10756. box.stores = box.stores || {};
  10757. box.stores.sks = {};
  10758. var converters;
  10759. var secretKeyGeneratorFactory;
  10760. var cipher;
  10761. var pkcs12Module;
  10762. var exceptions;
  10763. var homomorphicKeyFactory;
  10764. var f = function(box) {
  10765. converters = new box.commons.utils.Converters();
  10766. cipher = (new box.symmetric.cipher.factory.SymmetricCipherFactory())
  10767. .getCryptoSymmetricCipher();
  10768. secretKeyGeneratorFactory =
  10769. new box.primitives.derivation.factory.SecretKeyGeneratorFactory();
  10770. pkcs12Module = box.stores.pkcs12;
  10771. exceptions = box.commons.exceptions;
  10772. homomorphicKeyFactory = new box.homomorphic.keypair.factory.KeyFactory();
  10773. };
  10774. f.policies = {
  10775. symmetric: {
  10776. secretkey: {
  10777. encryption:
  10778. {length: box.policies.symmetric.secretkey.encryption.length},
  10779. mac: {length: box.policies.symmetric.secretkey.mac.length},
  10780. secureRandom:
  10781. {provider: box.policies.symmetric.secretkey.secureRandom.provider}
  10782. },
  10783. cipher: {
  10784. provider: box.policies.symmetric.cipher.provider,
  10785. algorithm: box.policies.symmetric.cipher.algorithm,
  10786. initializationVectorLengthBytes:
  10787. box.policies.symmetric.cipher.initializationVectorLengthBytes,
  10788. secureRandom:
  10789. {provider: box.policies.symmetric.cipher.secureRandom.provider}
  10790. }
  10791. },
  10792. primitives: {
  10793. derivation: {
  10794. pbkdf: {
  10795. provider: box.policies.primitives.derivation.pbkdf.provider,
  10796. hash: box.policies.primitives.derivation.pbkdf.hash,
  10797. saltLengthBytes:
  10798. box.policies.primitives.derivation.pbkdf.saltLengthBytes,
  10799. keyLengthBytes:
  10800. box.policies.primitives.derivation.pbkdf.keyLengthBytes,
  10801. iterations: box.policies.primitives.derivation.pbkdf.iterations
  10802. }
  10803. }
  10804. }
  10805. };
  10806. cryptolib(
  10807. 'commons', 'primitives.derivation', 'symmetric.cipher', 'stores.pkcs12',
  10808. 'homomorphic.keypair', f);
  10809. /**
  10810. * Defines a SksReader.
  10811. *
  10812. * @param data.
  10813. */
  10814. box.stores.sks.SksReader = function(data) {
  10815. // A cache of keys derived from store passwords, to prevent consecutive
  10816. // operations on a keystore to derive keys each time.
  10817. var bigintKeys = {};
  10818. var derivedKeys = {};
  10819. // Create the PBKDF generator.
  10820. var cryptoPbkdfSecretKeyGenerator = secretKeyGeneratorFactory.createPBKDF();
  10821. try {
  10822. var loadKeyStore = function(data) {
  10823. var keyStore;
  10824. if (data) {
  10825. if (typeof data === 'string') {
  10826. keyStore = JSON.parse(data);
  10827. } else if (typeof data === 'object') {
  10828. keyStore = data;
  10829. }
  10830. }
  10831. return keyStore;
  10832. };
  10833. var validateKeyStoreStructure = function(keyStore) {
  10834. if (typeof keyStore.salt === 'undefined') {
  10835. throw new Error('Missing salt');
  10836. }
  10837. if (typeof keyStore.store === 'undefined') {
  10838. throw new Error('Missing store');
  10839. }
  10840. };
  10841. this.keyStore = loadKeyStore(data);
  10842. validateKeyStoreStructure(this.keyStore);
  10843. this.store = new pkcs12Module.Pkcs12(this.keyStore.store);
  10844. } catch (error) {
  10845. throw new Error('Invalid keyStore: ' + error.message);
  10846. }
  10847. function validateEncryptedKey(encryptedKey, keyType) {
  10848. if (!encryptedKey) {
  10849. throw new exceptions.CryptoLibException(
  10850. 'The keyStore does not contain a key of type ' + keyType);
  10851. }
  10852. }
  10853. /**
  10854. * Derive a key from the keystore password.
  10855. *
  10856. * @param {string} passwordB64 the Base64-encoded keystore password
  10857. * @returns the Base64-encoded key derived from the password
  10858. */
  10859. this._deriveKey = function(passwordB64) {
  10860. return cryptoPbkdfSecretKeyGenerator.generateSecret(
  10861. passwordB64, this.keyStore.salt);
  10862. };
  10863. /**
  10864. * Get the Base64-encoded key derived from the store password.
  10865. *
  10866. * @param {string} passwordB64 the Base64-encoded store password
  10867. * @return the Base64-encoded key derived from the store password
  10868. */
  10869. this._getDerivedKey = function(passwordB64) {
  10870. if (!derivedKeys.hasOwnProperty(passwordB64)) {
  10871. derivedKeys[passwordB64] = this._deriveKey(passwordB64);
  10872. }
  10873. return derivedKeys[passwordB64];
  10874. };
  10875. /**
  10876. * Get the Base64-encoded BigInteger representation of the key derived from
  10877. * the store password.
  10878. *
  10879. * @param {string} passwordB64 the Base64-encoded store password
  10880. * @returns the Base64-encoded BigInteger representation of the key derived
  10881. * from the store password
  10882. */
  10883. this._getBigIntKey = function(passwordB64) {
  10884. if (!bigintKeys.hasOwnProperty(passwordB64)) {
  10885. var derivedPasswordBase64 = this._getDerivedKey(passwordB64);
  10886. var derivedPassword = converters.bytesFromString(
  10887. converters.base64Decode(derivedPasswordBase64));
  10888. var derivedPasswordString =
  10889. new box.forge.jsbn.BigInteger(derivedPassword);
  10890. var longPasswordB64 =
  10891. converters.base64Encode(derivedPasswordString.toString(36));
  10892. bigintKeys[passwordB64] = longPasswordB64;
  10893. }
  10894. return bigintKeys[passwordB64];
  10895. };
  10896. this._getKey = function(alias, encryptedKey, passwordB64, keyType) {
  10897. validateEncryptedKey(encryptedKey, keyType);
  10898. var aliasAndKeyBase64 = this.decryptKey(encryptedKey, passwordB64);
  10899. var aliasAndKey = converters.base64Decode(aliasAndKeyBase64);
  10900. var decryptedAlias = aliasAndKey.slice(0, alias.length);
  10901. if (decryptedAlias !== alias) {
  10902. throw new exceptions.CryptoLibException(
  10903. 'The decrypted ' + keyType +
  10904. ' key does not correspond to the given alias.');
  10905. }
  10906. var key = aliasAndKey.slice(alias.length, aliasAndKey.length);
  10907. var keyBase64 = converters.base64Encode(key);
  10908. return keyBase64;
  10909. };
  10910. };
  10911. box.stores.sks.SksReader.prototype = {
  10912. getPrivateKeys: function(passwordB64) {
  10913. var updateArguments = function(bigIntKey, args) {
  10914. var argumentsCopy = Array.prototype.slice.call(args, 1);
  10915. argumentsCopy.unshift(bigIntKey);
  10916. return argumentsCopy;
  10917. };
  10918. return this.store.getPrivateKey.apply(
  10919. this.store,
  10920. updateArguments(this._getBigIntKey(passwordB64), arguments));
  10921. },
  10922. getSecretKey: function(alias, passwordB64) {
  10923. var encryptedKey = this.keyStore.secrets[alias];
  10924. return this._getKey(alias, encryptedKey, passwordB64, 'secret');
  10925. },
  10926. getElGamalPrivateKey: function(alias, passwordB64) {
  10927. var encryptedKey = this.keyStore.egPrivKeys[alias];
  10928. var keyBase64 =
  10929. this._getKey(alias, encryptedKey, passwordB64, 'ElGamal private');
  10930. return homomorphicKeyFactory.createPrivateKey(keyBase64);
  10931. },
  10932. decryptKey: function(encryptedKey, passwordB64) {
  10933. return cipher.decrypt(this._getDerivedKey(passwordB64), encryptedKey);
  10934. },
  10935. /**
  10936. * Retrieves the private key chain
  10937. *
  10938. * @param passwordB64
  10939. * Password as string in Base64 encoded format.
  10940. * @return Private key chain of as PrivateKeyChain object, which
  10941. * contains aliases and their related private keys in PEM
  10942. * format.
  10943. */
  10944. getPrivateKeyChain: function(passwordB64) {
  10945. return this.store.getPrivateKeyChain(this._getBigIntKey(passwordB64));
  10946. },
  10947. /**
  10948. * Retrieves the full certificate chain.
  10949. *
  10950. * @param passwordB64
  10951. * Password as string in Base64 encoded format.
  10952. * @return Certificate chain as array of strings in PEM format.
  10953. */
  10954. getCertificateChain: function(passwordB64) {
  10955. return this.store.getCertificateChain(this._getBigIntKey(passwordB64));
  10956. },
  10957. /**
  10958. * Retrieves a certificate chain by private key alias
  10959. *
  10960. * @param passwordB64
  10961. * Password as string in Base64 encoded format.
  10962. * @param alias
  10963. * Alias to filter
  10964. * @return Certificate chain as array of strings in PEM format.
  10965. */
  10966. getCertificateChainByAlias: function(passwordB64, alias) {
  10967. return this.store.getCertificateChainByAlias(
  10968. this._getBigIntKey(passwordB64), alias);
  10969. },
  10970. /**
  10971. * Retrieves a certificate by subject common name.
  10972. *
  10973. * @param passwordB64
  10974. * Password as string in Base64 encoded format.
  10975. * @param subjectCn
  10976. * Subject common name of certificate to retrieve, as string.
  10977. * @return Certificate with given subject common name, as string in PEM
  10978. * format.
  10979. */
  10980. getCertificateBySubject: function(passwordB64, subjectCn) {
  10981. return this.store.getCertificateBySubject(
  10982. this._getBigIntKey(passwordB64), subjectCn);
  10983. }
  10984. };
  10985. };
  10986. /*
  10987. * Copyright 2018 Scytl Secure Electronic Voting SA
  10988. *
  10989. * All rights reserved
  10990. *
  10991. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  10992. */
  10993. cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
  10994. /**
  10995. * Defines the symmetric ciphers.
  10996. *
  10997. * @namespace symmetric/cipher
  10998. */
  10999. cryptolib.modules.symmetric.cipher = function(box) {
  11000. 'use strict';
  11001. box.symmetric = box.symmetric || {};
  11002. box.symmetric.cipher = {};
  11003. /**
  11004. * Allows a symmetric cipher factory to be obtained.
  11005. *
  11006. * @exports symmetric/cipher/factory
  11007. */
  11008. box.symmetric.cipher.factory = {};
  11009. var policies = {
  11010. cipher: {
  11011. algorithm: box.policies.symmetric.cipher.algorithm,
  11012. provider: box.policies.symmetric.cipher.provider,
  11013. initializationVectorLengthBytes:
  11014. box.policies.symmetric.cipher.initializationVectorLengthBytes
  11015. }
  11016. };
  11017. for (var prop in policies.cipher.algorithm) {
  11018. if (typeof prop !== 'undefined') {
  11019. policies.cipher.algorithm = policies.cipher.algorithm[prop];
  11020. }
  11021. }
  11022. var utils, exceptions, randomFactory;
  11023. var f = function(box) {
  11024. utils = box.commons.utils;
  11025. exceptions = box.commons.exceptions;
  11026. randomFactory =
  11027. new box.primitives.securerandom.factory.SecureRandomFactory();
  11028. };
  11029. f.policies = {
  11030. primitives: {
  11031. secureRandom:
  11032. {provider: box.policies.symmetric.cipher.secureRandom.provider}
  11033. }
  11034. };
  11035. cryptolib('commons', 'primitives.securerandom', f);
  11036. /**
  11037. * Factory class that allows a symmetric cipher to be obtained.
  11038. *
  11039. * @class
  11040. */
  11041. box.symmetric.cipher.factory.SymmetricCipherFactory = function() {};
  11042. box.symmetric.cipher.factory.SymmetricCipherFactory.prototype = {
  11043. /**
  11044. * Create a new symmetric cipher.
  11045. * <p>
  11046. * The particular cipher that is returned depends on the policies.
  11047. *
  11048. * @function
  11049. * @returns a new symmetric cipher.
  11050. */
  11051. getCryptoSymmetricCipher: function() {
  11052. var secureRandom;
  11053. try {
  11054. if (policies.cipher.provider ===
  11055. Config.symmetric.cipher.provider.FORGE) {
  11056. secureRandom = randomFactory.getCryptoRandomBytes();
  11057. return this.getCryptoForgeSymmetricCipher(secureRandom);
  11058. } else {
  11059. throw new exceptions.CryptoLibException(
  11060. 'No suitable provider was provided.');
  11061. }
  11062. } catch (error) {
  11063. throw new exceptions.CryptoLibException(
  11064. 'A CryptoSymmetricCipher could not be obtained.', error);
  11065. }
  11066. },
  11067. /**
  11068. * Create a new CryptoForgeSymmetricCipher.
  11069. *
  11070. * @function
  11071. * @param secureRandom
  11072. * {CryptoScytlRandomBytes} a secure source of random bytes.
  11073. * @returns {symmetric/cipher.CryptoForgeSymmetricCipher} a new
  11074. * CryptoForgeSymmetricCipher.
  11075. */
  11076. getCryptoForgeSymmetricCipher: function(secureRandom) {
  11077. return new CryptoForgeSymmetricCipher(secureRandom);
  11078. }
  11079. };
  11080. /**
  11081. * @class
  11082. * @param randomGenerator
  11083. * {CryptoScytlRandomBytes} a secure random bytes generator.
  11084. * @memberof symmetric/cipher
  11085. */
  11086. function CryptoForgeSymmetricCipher(randomGenerator) {
  11087. this.converters = new utils.Converters();
  11088. this.bitOperators = new utils.BitOperators();
  11089. this.randomGenerator = randomGenerator;
  11090. }
  11091. CryptoForgeSymmetricCipher.prototype = {
  11092. /**
  11093. * Encrypts some data.
  11094. *
  11095. * @function
  11096. * @param data
  11097. * {String} Data to be encrypted, as string in Base64 encoded
  11098. * format.
  11099. * @param keyB64
  11100. * {String} Key, as string in Base64 encoded format.
  11101. * @returns Initialization vector concatenated with the encrypted data,
  11102. * as string in Base64 encoded format.
  11103. */
  11104. encrypt: function(keyB64, dataB64) {
  11105. try {
  11106. var key = this.converters.base64Decode(keyB64);
  11107. var data = this.converters.base64Decode(dataB64);
  11108. if (key.length !== policies.cipher.algorithm.keyLengthBytes) {
  11109. throw new exceptions.CryptolibException(
  11110. 'Key length does not match the required by the algorithm.');
  11111. }
  11112. var initVec = this.randomGenerator.nextRandom(
  11113. policies.cipher.initializationVectorLengthBytes);
  11114. // Create a byte buffer for data.
  11115. var dataBuffer = new box.forge.util.ByteBuffer(data);
  11116. var cipher =
  11117. box.forge.cipher.createCipher(policies.cipher.algorithm.name, key);
  11118. // Only for the GCM mode
  11119. var gcmAuthTagByteLength = policies.cipher.algorithm.tagLengthBytes;
  11120. if (typeof gcmAuthTagBitLength !== 'undefined') {
  11121. cipher.start({iv: initVec, tagLength: gcmAuthTagByteLength});
  11122. } else {
  11123. cipher.start({iv: initVec});
  11124. }
  11125. cipher.update(dataBuffer);
  11126. cipher.finish();
  11127. var encryptedData = cipher.output.getBytes().toString();
  11128. if (typeof gcmAuthTagByteLength !== 'undefined') {
  11129. var gcmAuthTag = cipher.mode.tag.getBytes();
  11130. encryptedData = encryptedData + gcmAuthTag.toString();
  11131. }
  11132. var initVectorAndEncryptedData = initVec + encryptedData;
  11133. var initVectorAndEncryptedDataBase64 =
  11134. this.converters.base64Encode(initVectorAndEncryptedData);
  11135. return initVectorAndEncryptedDataBase64;
  11136. } catch (error) {
  11137. throw new exceptions.CryptoLibException(
  11138. 'Data could not be symmetrically encrypted.', error);
  11139. }
  11140. },
  11141. /**
  11142. * Decrypts some encrypted data, using the initialization vector that is
  11143. * provided
  11144. *
  11145. * @function
  11146. * @param keyB64
  11147. * {String} the key as a string in Base64 encoded format.
  11148. * @param initVectorAndEncryptedDataBase64
  11149. * {String} Initialization vector concatenated with the
  11150. * encrypted data, as string in Base64 encoded format.
  11151. * @returns Decrypted data, as string in Base64 encoded format.
  11152. */
  11153. decrypt: function(keyB64, initVectorAndEncryptedDataBase64) {
  11154. try {
  11155. var key = this.converters.base64Decode(keyB64);
  11156. if (key.length !== policies.cipher.algorithm.keyLengthBytes) {
  11157. throw new exceptions.CryptolibException(
  11158. 'Key length does not match the required by the algorithm.');
  11159. }
  11160. var cipher = box.forge.cipher.createDecipher(
  11161. policies.cipher.algorithm.name, key);
  11162. var initVectorAndEncryptedData =
  11163. this.converters.base64Decode(initVectorAndEncryptedDataBase64);
  11164. var initVector = this.bitOperators.extract(
  11165. initVectorAndEncryptedData, 0,
  11166. policies.cipher.initializationVectorLengthBytes);
  11167. var encryptedData = this.bitOperators.extract(
  11168. initVectorAndEncryptedData,
  11169. policies.cipher.initializationVectorLengthBytes,
  11170. initVectorAndEncryptedData.length);
  11171. // Only for the GCM mode
  11172. var gcmAuthTagByteLength = policies.cipher.algorithm.tagLengthBytes;
  11173. if (typeof gcmAuthTagByteLength !== 'undefined') {
  11174. var offset = encryptedData.length - gcmAuthTagByteLength;
  11175. var gcmAuthTag = this.bitOperators.extract(
  11176. encryptedData, offset, encryptedData.length);
  11177. encryptedData = this.bitOperators.extract(encryptedData, 0, offset);
  11178. var gcmAuthTagBitLength =
  11179. gcmAuthTagByteLength * box.NUMBER_OF_BITS_PER_BYTE;
  11180. cipher.start({
  11181. iv: initVector,
  11182. tagLength: gcmAuthTagBitLength,
  11183. tag: gcmAuthTag
  11184. });
  11185. } else {
  11186. cipher.start({iv: initVector});
  11187. }
  11188. var encryptedDataBuffer = new box.forge.util.ByteBuffer(encryptedData);
  11189. cipher.update(encryptedDataBuffer);
  11190. cipher.finish();
  11191. var outputBase64 =
  11192. this.converters.base64Encode(cipher.output.getBytes().toString());
  11193. return outputBase64;
  11194. } catch (error) {
  11195. throw new exceptions.CryptoLibException(
  11196. 'Data could not be symmetrically decrypted.', error);
  11197. }
  11198. }
  11199. };
  11200. };
  11201. /*
  11202. * Copyright 2018 Scytl Secure Electronic Voting SA
  11203. *
  11204. * All rights reserved
  11205. *
  11206. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  11207. */
  11208. cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
  11209. /**
  11210. * Defines the MACs of the module.
  11211. *
  11212. * @namespace symmetric/mac
  11213. */
  11214. cryptolib.modules.symmetric.mac = function(box) {
  11215. 'use strict';
  11216. box.symmetric = box.symmetric || {};
  11217. box.symmetric.mac = {};
  11218. /**
  11219. * Allows a symmetric MAC factory to be obtained.
  11220. *
  11221. * @exports symmetric/mac/factory
  11222. */
  11223. box.symmetric.mac.factory = {};
  11224. var policies = {
  11225. mac: {
  11226. hash: box.policies.symmetric.mac.hash,
  11227. provider: box.policies.symmetric.mac.provider
  11228. }
  11229. };
  11230. var converters;
  11231. var exceptions;
  11232. cryptolib('commons', function(box) {
  11233. converters = new box.commons.utils.Converters();
  11234. exceptions = box.commons.exceptions;
  11235. });
  11236. /**
  11237. * Factory class that allows a MAC to be obtained.
  11238. *
  11239. * @class
  11240. */
  11241. box.symmetric.mac.factory.MacFactory = function() {};
  11242. box.symmetric.mac.factory.MacFactory.prototype = {
  11243. /**
  11244. * Create a new MAC.
  11245. * <p>
  11246. * The particular MAC that is returned depends on the policies.
  11247. *
  11248. * @function
  11249. * @returns a new MAC.
  11250. */
  11251. create: function() {
  11252. try {
  11253. if (policies.mac.provider === Config.symmetric.mac.provider.FORGE) {
  11254. return this.createCryptoForgeMac();
  11255. } else {
  11256. throw new exceptions.CryptoLibException(
  11257. 'No suitable provider was provided.');
  11258. }
  11259. } catch (error) {
  11260. throw new exceptions.CryptoLibException(
  11261. 'A CryptoMac could not be obtained.', error);
  11262. }
  11263. },
  11264. /**
  11265. * Create a new CryptoForgeMac.
  11266. *
  11267. * @function
  11268. * @returns {symmetric/mac.CryptoForgeMac} a new CryptoForgeMac.
  11269. */
  11270. createCryptoForgeMac: function() {
  11271. return new CryptoForgeMac();
  11272. }
  11273. };
  11274. /**
  11275. * Represents a MAC.
  11276. *
  11277. * @class
  11278. * @memberof symmetric/mac
  11279. */
  11280. function CryptoForgeMac() {
  11281. this.hmacDigester = forge.hmac.create();
  11282. }
  11283. CryptoForgeMac.prototype = {
  11284. /**
  11285. * Generates MAC for some data.
  11286. *
  11287. * @function
  11288. * @param secretKeyBase64
  11289. * {String} Secret key, as string in Base64 encoded format
  11290. * @param arrayDataBase64
  11291. * {String} The input data for the MAC, as an array of string
  11292. * in Base64 encoded format. It is assumed that the array is
  11293. * not empty.
  11294. * @returns The generated MAC, in Base64 encoded format.
  11295. */
  11296. generate: function(secretKeyBase64, arrayDataBase64) {
  11297. var secretKey = converters.base64Decode(secretKeyBase64);
  11298. var secretKeyBuffer = new forge.util.ByteBuffer(secretKey);
  11299. try {
  11300. this.hmacDigester.start(policies.mac.hash, secretKeyBuffer);
  11301. } catch (error) {
  11302. throw new exceptions.CryptoLibException(
  11303. 'MAC message digester could not be initialized.', error);
  11304. }
  11305. try {
  11306. if (arrayDataBase64.length < 1) {
  11307. throw new exceptions.CryptoLibException(
  11308. 'The array of data should have at least one element');
  11309. }
  11310. var dataB64;
  11311. for (var i = 0; i < arrayDataBase64.length; i++) {
  11312. dataB64 = arrayDataBase64[i];
  11313. var data = converters.base64Decode(dataB64);
  11314. this.hmacDigester.update(data);
  11315. }
  11316. } catch (error) {
  11317. throw new exceptions.CryptoLibException(
  11318. 'MAC message digester could not be updated.', error);
  11319. }
  11320. try {
  11321. var hmacMessageDigest = this.hmacDigester.digest();
  11322. return converters.base64Encode(hmacMessageDigest.getBytes());
  11323. } catch (error) {
  11324. throw new exceptions.CryptoLibException(
  11325. 'MAC message digest could not be generated.', error);
  11326. }
  11327. },
  11328. /**
  11329. * Verify that a given MAC is indeed the MAC for the given data, using
  11330. * the given secret key.
  11331. *
  11332. * @function
  11333. * @param macBase64
  11334. * {String} The MAC to be verified, as string in Base64
  11335. * encoded format.
  11336. * @param secretKeyBase64
  11337. * {String} Secret key, as string in Base64 encoded format
  11338. * @param arrayDataBase64
  11339. * {String} The input data for the MAC, as an array of string
  11340. * in Base64 encoded format. It is assumed that the array is
  11341. * not empty.
  11342. *
  11343. * @returns True if the MAC is the MAC of the given data and SecretKey,
  11344. * false otherwise.
  11345. */
  11346. verify: function(macBase64, secretKeyBase64, arrayDataBase64) {
  11347. if (typeof macBase64 === 'undefined' || macBase64 === null) {
  11348. return false;
  11349. }
  11350. var macBase64ToVerify = this.generate(secretKeyBase64, arrayDataBase64);
  11351. if (macBase64.length !== macBase64ToVerify.length) {
  11352. return false;
  11353. }
  11354. var equals = true;
  11355. for (var i = 0; i < macBase64ToVerify.length; i++) {
  11356. if (macBase64ToVerify.charCodeAt(i) !== macBase64.charCodeAt(i)) {
  11357. equals = false;
  11358. }
  11359. }
  11360. return equals;
  11361. }
  11362. };
  11363. };
  11364. /*
  11365. * Copyright 2018 Scytl Secure Electronic Voting SA
  11366. *
  11367. * All rights reserved
  11368. *
  11369. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  11370. */
  11371. cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
  11372. /**
  11373. * Defines a symmetric secret key
  11374. *
  11375. * @namespace symmetric/secretkey
  11376. */
  11377. cryptolib.modules.symmetric.secretkey = function(box) {
  11378. 'use strict';
  11379. box.symmetric = box.symmetric || {};
  11380. box.symmetric.secretkey = {};
  11381. /**
  11382. * Allows a symmetric secret key factory to be obtained.
  11383. *
  11384. * @exports symmetric/secretkey/factory
  11385. */
  11386. box.symmetric.secretkey.factory = {};
  11387. var policies = {
  11388. secretkey: {
  11389. encryption: {
  11390. lengthBytes: box.policies.symmetric.secretkey.encryption.lengthBytes
  11391. },
  11392. mac: {lengthBytes: box.policies.symmetric.secretkey.mac.lengthBytes}
  11393. }
  11394. };
  11395. var utils, randomFactory, exceptions, secureRandom, lengthBytes;
  11396. var f = function(box) {
  11397. utils = box.commons.utils;
  11398. exceptions = box.commons.exceptions;
  11399. randomFactory =
  11400. new box.primitives.securerandom.factory.SecureRandomFactory();
  11401. };
  11402. f.policies = {
  11403. primitives: {
  11404. secureRandom:
  11405. {provider: box.policies.symmetric.secretkey.secureRandom.provider}
  11406. }
  11407. };
  11408. cryptolib('commons', 'primitives.securerandom', f);
  11409. /**
  11410. * Validates the received length argument, in bytes.
  11411. *
  11412. * Confirms that:
  11413. * <ul>
  11414. * <li>the type of <code>lengthBytes</code> is number.</li>
  11415. * <li><code>lengthBytes</code> is an integer with a value not less than
  11416. * 1.</li>
  11417. * </ul>
  11418. *
  11419. * @function validateParameter
  11420. * @param lengthBytes
  11421. * {number} the length, in bytes, to be validated.
  11422. */
  11423. var validateParameter = function(lengthBytes) {
  11424. if (typeof lengthBytes !== 'number' || lengthBytes % 1 !== 0 ||
  11425. lengthBytes < 1) {
  11426. throw new exceptions.CryptoLibException(
  11427. 'The given key length is not valid.');
  11428. }
  11429. };
  11430. /**
  11431. * Represents a secret key factory.
  11432. *
  11433. * @class
  11434. */
  11435. box.symmetric.secretkey.factory.SecretKeyFactory = function() {
  11436. secureRandom = randomFactory.getCryptoRandomBytes();
  11437. };
  11438. box.symmetric.secretkey.factory.SecretKeyFactory.prototype = {
  11439. /**
  11440. * Get a CryptoSecretKeyGenerator for encryption.
  11441. *
  11442. * @function
  11443. * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
  11444. * CryptoSecretKeyGenerator for encryption.
  11445. */
  11446. getCryptoSecretKeyGeneratorForEncryption: function() {
  11447. lengthBytes = policies.secretkey.encryption.lengthBytes;
  11448. return this.getCryptoSecretKeyGenerator();
  11449. },
  11450. /**
  11451. * Get a CryptoSecretKeyGenerator for MAC.
  11452. *
  11453. * @function
  11454. * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
  11455. * CryptoSecretKeyGenerator for MAC.
  11456. */
  11457. getCryptoSecretKeyGeneratorForMac: function() {
  11458. lengthBytes = policies.secretkey.mac.lengthBytes;
  11459. return this.getCryptoSecretKeyGenerator();
  11460. },
  11461. /**
  11462. * Create a new CryptoSecretKeyGenerator.
  11463. *
  11464. * @function
  11465. * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
  11466. * CryptoSecretKeyGenerator.
  11467. */
  11468. getCryptoSecretKeyGenerator: function() {
  11469. return new CryptoSecretKeyGenerator(secureRandom);
  11470. }
  11471. };
  11472. /**
  11473. * Defines a Secret Key generator.
  11474. *
  11475. * @class
  11476. * @memberof symmetric/secretkey
  11477. * @param randomGenerator
  11478. * {CryptoScytlRandomBytes} a secure random bytes generator.
  11479. */
  11480. function CryptoSecretKeyGenerator(randomGenerator) {
  11481. this.converters = new utils.Converters();
  11482. this.randomGenerator = randomGenerator;
  11483. }
  11484. CryptoSecretKeyGenerator.prototype = {
  11485. /**
  11486. * Generates a secret key.
  11487. *
  11488. * @function
  11489. * @return A secret key, as string in Base64 encoded format.
  11490. */
  11491. generate: function() {
  11492. try {
  11493. validateParameter(lengthBytes);
  11494. var key = this.randomGenerator.nextRandom(lengthBytes);
  11495. var keyBase64 = this.converters.base64Encode(key);
  11496. return keyBase64;
  11497. } catch (error) {
  11498. throw new exceptions.CryptoLibException(
  11499. 'CryptoSecretKey could not be generated.', error);
  11500. }
  11501. }
  11502. };
  11503. };
  11504. /*
  11505. * Copyright 2018 Scytl Secure Electronic Voting SA
  11506. *
  11507. * All rights reserved
  11508. *
  11509. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  11510. */
  11511. cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
  11512. /**
  11513. * Defines the symmetric service.
  11514. * @namespace symmetric/service
  11515. */
  11516. cryptolib.modules.symmetric.service = function(box) {
  11517. 'use strict';
  11518. box.symmetric = box.symmetric || {};
  11519. /**
  11520. * A module that provides symmetric cryptographic services.
  11521. * @exports symmetric/service
  11522. */
  11523. box.symmetric.service = {};
  11524. var cipherFactory, secretKeyFactory, macFactory;
  11525. cryptolib(
  11526. 'symmetric.cipher', 'symmetric.secretkey', 'symmetric.mac',
  11527. 'commons.exceptions', function(box) {
  11528. cipherFactory =
  11529. new box.symmetric.cipher.factory.SymmetricCipherFactory();
  11530. secretKeyFactory =
  11531. new box.symmetric.secretkey.factory.SecretKeyFactory();
  11532. macFactory = new box.symmetric.mac.factory.MacFactory();
  11533. });
  11534. /**
  11535. * @function getSecretKeyForEncryption
  11536. * @returns {string} a secret key as a string encoded in Base64.
  11537. */
  11538. box.symmetric.service.getSecretKeyForEncryption = function() {
  11539. var secretKeyGenerator =
  11540. secretKeyFactory.getCryptoSecretKeyGeneratorForEncryption();
  11541. return secretKeyGenerator.generate();
  11542. };
  11543. /**
  11544. * @function getSecretKeyForMac
  11545. * @returns {string} a MAC as a string encoded in Base64.
  11546. */
  11547. box.symmetric.service.getSecretKeyForMac = function() {
  11548. var secretKeyGenerator =
  11549. secretKeyFactory.getCryptoSecretKeyGeneratorForMac();
  11550. return secretKeyGenerator.generate();
  11551. };
  11552. /**
  11553. * @function encrypt
  11554. * @returns {string} the initialization vector concatenated with the encrypted data,
  11555. * as string in Base64 encoded format.
  11556. */
  11557. box.symmetric.service.encrypt = function(secretKeyBase64, dataBase64) {
  11558. var cipher = cipherFactory.getCryptoSymmetricCipher();
  11559. return cipher.encrypt(secretKeyBase64, dataBase64);
  11560. };
  11561. /**
  11562. * @function decrypt
  11563. * @returns {string} the decrypted data, as a String in Base64 encoded format.
  11564. */
  11565. box.symmetric.service.decrypt = function(
  11566. secretKeyBase64, initVectorAndEncryptedDataBase64) {
  11567. var cipher = cipherFactory.getCryptoSymmetricCipher();
  11568. return cipher.decrypt(secretKeyBase64, initVectorAndEncryptedDataBase64);
  11569. };
  11570. /**
  11571. * @function getMac
  11572. * @returns {string} a string in Base64 encoded format.
  11573. */
  11574. box.symmetric.service.getMac = function(secretKeyBase64, arrayDataBase64) {
  11575. var cryptoMac = macFactory.create();
  11576. return cryptoMac.generate(secretKeyBase64, arrayDataBase64);
  11577. };
  11578. /**
  11579. * @function verifyMac
  11580. * @returns {boolean} true if the data has been verified.
  11581. */
  11582. box.symmetric.service.verifyMac = function(
  11583. macBase64, secretKeyBase64, arrayDataBase64) {
  11584. var cryptoMac = macFactory.create();
  11585. return cryptoMac.verify(macBase64, secretKeyBase64, arrayDataBase64);
  11586. };
  11587. };
  11588. if (typeof cryptoPRNG !== 'undefined') {
  11589. cryptolib.cryptoPRNG = cryptoPRNG;
  11590. cryptolib.Config = Config;
  11591. if (typeof module !== 'undefined') {
  11592. module.exports = cryptolib;
  11593. };
  11594. };