1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469 |
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- /**
- * @global
- * @description This object describes the configuration scheme for this
- * cryptographic library. The following modules are considered:
- * <ul>
- * <li> Asymmetric
- * <li> Primitives
- * <li> Stores
- * <li> Symmetric
- * <li> Digital Envelope
- * </ul>
- * @readonly
- * @property {object} asymmetric.keypair - Policies for generating keypairs.
- * @property {object} asymmetric.keypair.encryption - Policies for generating
- * encryption keypairs.
- * @property {object} asymmetric.keypair.encryption.algorithm - Algorithm.
- * @property {string} asymmetric.keypair.encryption.algorithm.RSA - RSA
- * algorithm.
- * @property {object} asymmetric.keypair.encryption.provider - Provider.
- * @property {string} asymmetric.keypair.encryption.provider.FORGE - Forge
- * provider.
- * @property {object} asymmetric.keypair.encryption.keyLength - Key length.
- * @property {number} asymmetric.keypair.encryption.keyLength.KL_2048 - 2048
- * bits.
- * @property {number} asymmetric.keypair.encryption.keyLength.KL_3072 - 3072
- * bits.
- * @property {number} asymmetric.keypair.encryption.keyLength.KL_4096 - 4096
- * bits.
- * @property {object} asymmetric.keypair.encryption.publicExponent - Public
- * exponent for generating encryption keypairs.
- * @property {number} asymmetric.keypair.encryption.publicExponent.F4 - 65537.
- *
- * @property {object} asymmetric.signer - Policies for signing and verifying
- * data.
- * @property {object} asymmetric.signer.algorithm - Algorithm.
- * @property {string} asymmetric.signer.algorithm.RSA - RSA algorithm.
- * @property {object} asymmetric.signer.provider - Provider.
- * @property {string} asymmetric.signer.provider.FORGE - Forge provider.
- * @property {object} asymmetric.signer.hash - Hash algorithm.
- * @property {string} asymmetric.signer.hash.SHA256 - SHA-256 algorithm.
- * @property {object} asymmetric.signer.padding - Padding scheme.
- * @property {object} asymmetric.signer.padding.PSS - PSS padding scheme.
- * @property {string} asymmetric.signer.padding.PSS.name - PSS.
- * @property {object} asymmetric.signer.padding.PSS.hash - Hash for the PSS
- * padding scheme.
- * @property {string} asymmetric.signer.padding.PSS.hash.SHA256 - SHA-256
- * algorithm.
- * @property {object} asymmetric.signer.padding.PSS.mask - Mask generating
- * function for the PSS padding scheme.
- * @property {object} asymmetric.signer.padding.PSS.mask.MGF1 - MGF1 for the PSS
- * padding scheme.
- * @property {string} asymmetric.signer.padding.PSS.mask.MGF1.name - MGF1.
- * @property {object} asymmetric.signer.padding.PSS.mask.MGF1.hash - Hash
- * algorithm for the MGF1 for the PSS padding scheme.
- * @property {string} asymmetric.signer.padding.PSS.mask.MGF1.hash.SHA256 -
- * SHA-256 algorithm.
- * @property {object} asymmetric.signer.padding.PSS.saltLengthBytes - Salt
- * length for the PSS padding scheme.
- * @property {number} asymmetric.signer.padding.PSS.saltLengthBytes.SL_32 - 32
- * bytes.
- * @property {object} asymmetric.signer.publicExponent - Public exponent.
- * @property {number} asymmetric.signer.publicExponent.F4 - 65537.
- * @property {object} primitives.securerandom - Policies for generating
- * securerandom.
- * @property {object} primitives.securerandom.provider - Provider.
- * @property {string} primitives.securerandom.provider.SCYTL - Scytl provider.
- * @property {object} primitives.messagedigest - Policies for generating message
- * digests.
- * @property {object} primitives.messagedigest.algorithm - Algorithm.
- * @property {string} primitives.messagedigest.algorithm.SHA256 - SHA-256
- * algorithm.
- * @property {object} primitives.messagedigest.provider - Provider.
- * @property {string} primitives.messagedigest.provider.FORGE - Forge provider.
- * @property {object} symmetric.secretkey - Policies to generate secret keys.
- * @property {number} symmetric.secretkey.length - 128 bits.
- * @property {object} symmetric.cipher - Policies to encrypt and decrypt
- * symmetrically.
- * @property {object} symmetric.cipher.algorithm - Algorithm.
- * @property {object} symmetric.cipher.algorithm.AES128_GCM - AES128-GCM
- * algorithm.
- * @property {string} symmetric.cipher.algorithm.AES128_GCM.name - AES128-GCM.
- * @property {number} symmetric.cipher.algorithm.AES128_GCM.keyLengthBytes - 16
- * bytes.
- * @property {number} symmetric.cipher.algorithm.AES128_GCM.tagLengthBytes - 16
- * bytes.
- * @property {object} symmetric.cipher.provider - Provider.
- * @property {object} symmetric.cipher.provider.FORGE - Forge provider.
- * @property {object} symmetric.cipher.initializationVectorLengthBytes -
- * Initialization vector length.
- * @property {number} symmetric.cipher.initializationVectorLengthBytes.IV_12 -
- * 12 bytes.
- */
- var Config = {
- homomorphic: {cipher: {secureRandom: {provider: {SCYTL: 'Scytl'}}}},
- asymmetric: {
- keypair: {
- encryption: {
- algorithm: {RSA: 'RSA'},
- provider: {FORGE: 'Forge'},
- keyLength: {KL_2048: 2048, KL_3072: 3072, KL_4096: 4096},
- publicExponent: {F4: 65537}
- },
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- signer: {
- algorithm: {RSA: 'RSA'},
- provider: {FORGE: 'Forge'},
- hash: {SHA256: 'SHA256'},
- padding: {
- PSS: {
- name: 'PSS',
- hash: {SHA256: 'SHA256'},
- mask: {MGF1: {name: 'MGF1', hash: {SHA256: 'SHA256'}}},
- saltLengthBytes: {SL_32: 32}
- }
- },
- publicExponent: {F4: 65537},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- cipher: {
- algorithm: {
- RSA_OAEP: {
- name: 'RSA-OAEP',
- hash: 'SHA256',
- mask: {MGF1: {name: 'MGF1', hash: 'SHA1'}}
- },
- RSA_KEM: {
- name: 'RSA-KEM',
- secretKeyLengthBytes: {KL_16: 16, KL_24: 24, KL_32: 32},
- ivLengthBytes: {IVL_12: 12, IVL_16: 16, IVL_32: 32, IVL_64: 64},
- tagLengthBytes: {TL_12: 12, TL_16: 16, TL_32: 32, TL_64: 64},
- deriver: {
- name: {KDF1: 'kdf1', KDF2: 'kdf2', MGF1: 'mgf1'},
- messagedigest: {algorithm: {SHA256: 'SHA256'}}
- },
- cipher: {AESGCM: 'AES-GCM'}
- }
- },
- provider: {FORGE: 'Forge'},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- }
- },
- primitives: {
- secureRandom: {provider: {SCYTL: 'Scytl'}},
- messagedigest: {
- algorithm: {SHA256: 'SHA256', SHA512_224: 'SHA512/224'},
- provider: {FORGE: 'Forge'}
- },
- derivation: {
- pbkdf: {
- provider: {FORGE: 'Forge'},
- hash: {SHA256: 'SHA256'},
- saltLengthBytes: {SL_20: 20, SL_32: 32},
- keyLengthBytes: {KL_16: 16, KL_32: 32},
- iterations: {
- I_1: 1,
- I_8000: 8000,
- I_16000: 16000,
- I_32000: 32000,
- I_64000: 64000
- }
- }
- }
- },
- stores: {},
- symmetric: {
- secretkey: {
- encryption: {lengthBytes: {SK_16: 16}},
- mac: {lengthBytes: {SK_32: 32}},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- cipher: {
- provider: {FORGE: 'Forge'},
- algorithm: {
- AES128_GCM: {name: 'AES-GCM', keyLengthBytes: 16, tagLengthBytes: 16}
- },
- initializationVectorLengthBytes: {IV_12: 12},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- mac: {hash: {SHA256: 'SHA256'}, provider: {FORGE: 'Forge'}}
- },
- proofs: {
- secureRandom: {provider: {SCYTL: 'Scytl'}},
- messagedigest: {
- algorithm: {SHA256: 'SHA256', SHA512_224: 'SHA512/224'},
- provider: {FORGE: 'Forge'}
- },
- charset: {UTF8: 'UTF-8'}
- },
- digitalenvelope: {
- symmetric: {
- secretkey: {
- encryption: {lengthBytes: {SK_16: 16}},
- mac: {lengthBytes: {SK_32: 32}},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- cipher: {
- provider: {FORGE: 'Forge'},
- algorithm: {
- AES128_GCM:
- {name: 'AES-GCM', keyLengthBytes: 16, tagLengthBytes: 16}
- },
- initializationVectorLengthBytes: {IV_12: 12},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- },
- mac: {hash: {SHA256: 'SHA256'}, provider: {FORGE: 'Forge'}}
- },
- asymmetric: {
- cipher: {
- algorithm: {
- RSA_OAEP: {
- name: 'RSA-OAEP',
- hash: 'SHA256',
- mask: {MGF1: {name: 'MGF1', hash: 'SHA1'}}
- },
- RSA_KEM: {
- name: 'RSA-KEM',
- secretKeyLengthBytes: {KL_16: 16, KL_24: 24, KL_32: 32},
- ivLengthBytes: {IVL_12: 12, IVL_16: 16, IVL_32: 32, IVL_64: 64},
- tagLengthBytes: {TL_12: 12, TL_16: 16, TL_32: 32, TL_64: 64},
- deriver: {
- name: {KDF1: 'kdf1', KDF2: 'kdf2', MGF1: 'mgf1'},
- messagedigest: {algorithm: {SHA256: 'SHA256'}}
- },
- cipher: {AESGCM: 'AES-GCM'}
- }
- },
- provider: {FORGE: 'Forge'},
- secureRandom: {provider: {SCYTL: 'Scytl'}}
- }
- }
- }
- };
- if (Object.freeze) {
- /**
- * Freezes an object and all its contents.
- * @param {Object} target the object to freeze.
- */
- var recursiveFreeze = function(target) {
- 'use strict';
- // Get all property names
- var propNames = Object.getOwnPropertyNames(target);
- // Freeze the object's properties.
- propNames.forEach(function(name) {
- var property = target[name];
- // Freeze the properties' properties.
- if (typeof property === 'object' && property !== null) {
- recursiveFreeze(property);
- }
- });
- // Freeze the object itself.
- return Object.freeze(target);
- };
- // Lock down the configuration
- recursiveFreeze(Config);
- }
- var cryptolibPolicies;
- /**
- * @global
- * @function cryptolib
- *
- * @description Core of the library, this module is used to sandbox the
- * requested modules.
- *
- * @example // how to load all modules cryptolib('*', function(box) { // any
- * module can be used from here. //
- * box.examplemodule.service.getExample(); });
- *
- *
- * @param modules
- * {...modules} modules to be loaded. '*' or none to load all the
- * modules.
- * @param function
- * {cryptolibSandbox} a closure for the cryptolib object.
- * @tutorial workers
- */
- function cryptolib() {
- 'use strict';
- /* Class to keep the references to polices and prng. */
- function Cryptolib(modules, callback) {
- function getAllModules(parent) {
- var modules = [];
- for (var module in parent) {
- if (parent.hasOwnProperty(module)) {
- modules.push(module);
- }
- }
- return modules;
- }
- function loadModules(box, modules, parentModule) {
- if (!modules || modules.toString() === '*'.toString()) {
- modules = getAllModules(parentModule);
- }
- for (var i = 0; i < modules.length; i += 1) {
- var firstDotIndex = modules[i].indexOf('.');
- if (firstDotIndex > -1) {
- var subModule = modules[i].substr(firstDotIndex + 1);
- var root = modules[i].substr(0, firstDotIndex);
- loadModules(box, [subModule], parentModule[root]);
- } else if (typeof parentModule[modules[i]] === 'function') {
- parentModule[modules[i]](box);
- } else if (typeof parentModule[modules[i]] === 'object') {
- loadModules(box, '*', parentModule[modules[i]]);
- }
- }
- }
- this.policies = callback.policies || cryptolibPolicies;
- cryptolibPolicies = cryptolibPolicies || this.policies;
- this.prng = callback.prng || cryptoPRNG.getPRNG();
- loadModules(this, modules, cryptolib.modules);
- callback(this);
- }
- Cryptolib.prototype = {
- getKeys: function(obj) {
- var keys = [];
- for (var key in obj) {
- if (typeof key !== 'undefined') {
- keys.push(key);
- }
- }
- return keys;
- },
- getModuleNames: function() {
- var moduleNames = '';
- for (var module in cryptolib.modules) {
- if (typeof module !== 'undefined') {
- if (moduleNames.length > 0) {
- moduleNames += ', ';
- }
- moduleNames += module;
- }
- }
- return '[' + moduleNames + ']';
- },
- forge: forge, // redefines forge global variable
- sjcl: sjcl, // redefines sjcl global variable
- // Constants.
- /** @constant */
- NUMBER_OF_BITS_PER_BYTE: 8,
- /** @constant */
- MAXIMUM_LENGTH_TO_GENERATE_DATA: 512,
- /** @constant */
- BASE_2_RADIX: 2,
- /** @constant */
- BASE_10_RADIX: 10,
- /** @constant */
- BASE_16_RADIX: 16,
- /** @constant */
- EPOCH_TIME_LENGTH: 10,
- /** @constant */
- RSA_LINE_LENGTH: 64,
- /** @constant */
- SHA_256_LENGTH: 32,
- /** @constant */
- HMAC_SHA256_KEY_LENGTH: 32,
- /** @constant */
- AES_KEY_LENGTH: 16,
- /** @constant */
- AES_CBC_IV_LENGTH: 16,
- /** @constant */
- DES3_KEY_LENGTH: 24,
- /** @constant */
- DES3_CBC_IV_LENGTH: 8,
- EQUALS: ' = ',
- NEWLINE: '\n',
- CRYPTO_SPEC_DELIM: '/',
- /** @constant */
- SHA_256: 'SHA256',
- /** @constant */
- RSA_ECB_PKCS1PADDING: 'RSA/ECB/PKCS1PADDING',
- /** @constant */
- RSA_ECB_OAEP_WITH_SHA256_AND_MGF1PADDING:
- 'RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING',
- /** @constant */
- FORGE_RSA_OAEP: 'RSA-OAEP',
- /** @constant */
- FORGE_RSAES_PKCS1_V1_5: 'RSAES-PKCS1-V1_5',
- /** @constant */
- MINIMUM_PRIME_CERTAINTY_LEVEL: 80,
- /** @constant */
- SHORT_EXPONENT_BIT_LENGTH: 256,
- /** @constant */
- EXPONENTIATION_PROOF_AUXILIARY_DATA: 'ExponentiationProof',
- /** @constant */
- PLAINTEXT_PROOF_AUXILIARY_DATA: 'PlaintextProof',
- /** @constant */
- SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA:
- 'SimplePlaintextEqualityProof',
- /** @constant */
- PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA: 'PlaintextEqualityProof',
- /** @constant */
- PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA:
- 'PlaintextExponentEqualityProof'
- };
- var args = Array.prototype.slice.call(arguments);
- var callback = args.pop();
- var modules = (args[0] && typeof args[0] === 'string') ? args : args[0];
- return new Cryptolib(modules, callback);
- }
- cryptolib.modules = {};
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- ////////////////////////////////////////////////
- //
- // Functionalities added to JavaScript types
- //
- ////////////////////////////////////////////////
- /**
- * An equals method for arrays.
- *
- * @param array
- * the array to which this array should be compared.
- * @param strict
- * a boolean value which specifies whether or not the elements must
- * be in the same order in both arrays. This parameter is optional,
- * if it is not supplied, then a default value of 'true' is assigned
- * to it.
- */
- Array.prototype.equals = function(array, strict) {
- 'use strict';
- if (!array) {
- return false;
- }
- if (arguments.length === 1) {
- strict = true;
- }
- if (this.length !== array.length) {
- return false;
- }
- for (var i = 0; i < this.length; i++) {
- if (this[i] instanceof Array && array[i] instanceof Array) {
- if (!this[i].equals(array[i], strict)) {
- return false;
- }
- } else if (strict && (!this[i].equals(array[i]))) {
- return false;
- } else if (!strict) {
- return this.sort().equals(array.sort(), true);
- }
- }
- return true;
- };
- /**
- * Allows all of the elements of one array to be added into another array.
- */
- Array.prototype.addAll = function() {
- 'use strict';
- for (var a = 0; a < arguments.length; a++) {
- var arr = arguments[a];
- for (var i = 0; i < arr.length; i++) {
- this.push(arr[i]);
- }
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
- /**
- * @namespace asymmetric/cipher
- */
- cryptolib.modules.asymmetric.cipher = function(box) {
- 'use strict';
- box.asymmetric = box.asymmetric || {};
- box.asymmetric.cipher = {};
- /**
- * A module that holds asymmetric cipher functionalities.
- *
- * @exports asymmetric/cipher/factory
- */
- box.asymmetric.cipher.factory = {};
- var policies = {
- cipher: {
- algorithm: box.policies.asymmetric.cipher.algorithm,
- secretKeyLengthBytes: box.policies.asymmetric.cipher.secretKeyLengthBytes,
- ivLengthBytes: box.policies.asymmetric.cipher.ivLengthBytes,
- tagLengthBytes: box.policies.asymmetric.cipher.tagLengthBytes,
- deriver: box.policies.asymmetric.cipher.deriver,
- hash: box.policies.asymmetric.cipher.hash,
- symmetricCipher: box.policies.asymmetric.cipher.symmetricCipher,
- provider: box.policies.asymmetric.cipher.provider
- }
- };
- var utils, converters, exceptions, randomFactory;
- var f = function(box) {
- utils = box.commons.utils;
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.asymmetric.cipher.secureRandom.provider}
- }
- };
- cryptolib('commons', 'primitives.securerandom', f);
- /** @class */
- box.asymmetric.cipher.factory.AsymmetricCipherFactory = function() {};
- box.asymmetric.cipher.factory.AsymmetricCipherFactory.prototype = {
- /**
- * @function Gets an asymmetric cipher.
- * @returns {asymmetric/cipher.CryptoForgeAsymmetricCipher}
- */
- getCryptoAsymmetricCipher: function() {
- try {
- if (policies.cipher.provider ===
- Config.asymmetric.cipher.provider.FORGE) {
- var secureRandomBytes = randomFactory.getCryptoRandomBytes();
- return this.getCryptoForgeAsymmetricCipher(secureRandomBytes);
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider for the asymmetric cipher was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoAsymmetricCipher could not be obtained.', error);
- }
- },
- /**
- * @function Gets a Forge asymmetric cipher.
- * @param secureRandom
- * {CryptoScytlRandomBytes} a source of random bytes.
- * @returns {asymmetric/cipher.CryptoForgeAsymmetricCipher}
- */
- getCryptoForgeAsymmetricCipher: function(secureRandom) {
- return new CryptoForgeAsymmetricCipher(secureRandom);
- }
- };
- /**
- * Defines a Forge asymmetric cipher
- *
- * @class
- * @param secureRandomBytes
- * {CryptoScytlRandomBytes} a source of random bytes.
- * @memberof asymmetric/cipher
- */
- function CryptoForgeAsymmetricCipher(secureRandomBytes) {
- if (!secureRandomBytes) {
- throw new exceptions.CryptoLibException(
- 'The received PRNG was not valid');
- }
- this.bitOperators = new utils.BitOperators();
- this.secureRandomBytes = secureRandomBytes;
- // We would like to use the SCYTL PRNG directly in the ciphers that are
- // created. However it is currently not possible to pass a PRNG to the
- // Forge library when creating or using a cipher. However, in some cases,
- // it is possible to pass a seed (created using the SCYTL PRNG) to FORGE
- // that is then used to seed the FORGE internal PRNG.
- this.encodingSeedLength = 32;
- try {
- if ((policies.cipher.algorithm.name !==
- Config.asymmetric.cipher.algorithm.RSA_OAEP.name) &&
- (policies.cipher.algorithm.name !==
- Config.asymmetric.cipher.algorithm.RSA_KEM.name)) {
- throw new exceptions.CryptoLibException(
- 'The specified algorithm is not supported.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoForgeAsymmetricCipher could not be created.', error);
- }
- /**
- * Parses the four parts of the data that is produced by the encrypt
- * function, and that is received by the decrypt function.
- * <p>
- * We know the length of three of these parts, and we know the total
- * length of the data, therefore we can parse out all four of the parts.
- */
- this._parseParts = function(privateKey, encryptedData) {
- var ivLengthBytes = policies.cipher.ivLengthBytes;
- var tagLengthBytes = policies.cipher.tagLengthBytes;
- var encapsulationLengthBytes = privateKey.n.bitLength() / 8;
- var totalLength = encryptedData.length;
- var totalKnownLength =
- encapsulationLengthBytes + ivLengthBytes + tagLengthBytes;
- var encryptedDataLength = totalLength - totalKnownLength;
- var startIndexOfSecondPart = encapsulationLengthBytes;
- var startIndexOfThirdPart = startIndexOfSecondPart + ivLengthBytes;
- var startIndexOfFourthPart = startIndexOfThirdPart + encryptedDataLength;
- var encapsulation =
- this.bitOperators.extract(encryptedData, 0, startIndexOfSecondPart);
- var iv = this.bitOperators.extract(
- encryptedData, startIndexOfSecondPart, startIndexOfThirdPart);
- var data = this.bitOperators.extract(
- encryptedData, startIndexOfThirdPart, startIndexOfFourthPart);
- var tag =
- this.bitOperators.extract(encryptedData, startIndexOfFourthPart);
- return {encapsulation: encapsulation, iv: iv, data: data, tag: tag};
- };
- this._validateInputs = function(keyPem, data) {
- if (!keyPem) {
- throw new exceptions.CryptoLibException(
- 'The received key was not initialized.');
- }
- if (!data) {
- throw new exceptions.CryptoLibException(
- 'The received data was not initialized.');
- }
- };
- // Note: at the moment, the options that are being used with the RSA_OAEP
- // algorithm are hardcoded (for encrypting and decrypting). This could be
- // improved so that these are read from the properties file. Doing this will
- // mean any that existing properties files (used by consumers of the
- // library) will become invalid (if the consumer uses RSA_OAEP) as they wont
- // have the mandatory new properties.
- this._getRsaOaepHash = function() {
- return box.forge.md.sha256.create();
- };
- //
- this._getRsaOaepMaskHash = function() {
- // For interoperability purposes, the MGF1 hash function must
- // remain as SHA-1.
- return box.forge.md.sha1.create();
- };
- this._getRsaOaepEncodingOptions = function() {
- var encodingOptions = {
- md: this._getRsaOaepHash(),
- mgf1: {md: this._getRsaOaepMaskHash()},
- seed: this.secureRandomBytes.nextRandom(this.encodingSeedLength)
- };
- return encodingOptions;
- };
- this._getRsaOaepDecodingOptions = function() {
- var decodingOptions = {
- md: this._getRsaOaepHash(),
- mgf1: {md: this._getRsaOaepMaskHash()}
- };
- return decodingOptions;
- };
- this._determineAndCreateHash = function(requestedHash) {
- if (requestedHash ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.messagedigest
- .algorithm.SHA256) {
- return forge.md.sha256.create();
- } else {
- throw new exceptions.CryptoLibException(
- 'Unsupported hash function specified.');
- }
- };
- this._determineAndCreateDeriver = function(requestedDeriver) {
- var hash = this._determineAndCreateHash(policies.cipher.hash);
- if (requestedDeriver ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.KDF1) {
- return new forge.kem.kdf1(hash);
- } else if (
- requestedDeriver ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.KDF2) {
- return new forge.kem.kdf2(hash);
- } else if (
- requestedDeriver ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.deriver.name.MGF1) {
- return new forge.mgf.mgf1.create(hash);
- } else {
- throw new exceptions.CryptoLibException(
- 'Unsupported deriver function specified.');
- }
- };
- }
- CryptoForgeAsymmetricCipher.prototype = {
- /**
- * Encrypts some data.
- * <p>
- * If the algorithm is RSA-KEM, then the output from this function will
- * be the base64 encoding of the following data:
- * <p>
- * [Encapsulation][IV][Encrypted Data][Tag]
- *
- * @function
- * @param publicKeyPem
- * {string} public key, as string in PEM format.
- * @param dataBase64
- * {string} data to be encrypted, as string in Base64 encoded
- * format.
- * @returns encrypted data, as string in Base 64 encoded format..
- */
- encrypt: function(publicKeyPem, dataBase64) {
- this._validateInputs(publicKeyPem, dataBase64);
- try {
- var publicKey = box.forge.pki.publicKeyFromPem(publicKeyPem);
- var data = converters.base64Decode(dataBase64);
- var output;
- if (policies.cipher.algorithm.name ===
- Config.asymmetric.cipher.algorithm.RSA_OAEP.name) {
- var encodingOptions = this._getRsaOaepEncodingOptions();
- output = publicKey.encrypt(
- data, policies.cipher.algorithm.name, encodingOptions);
- } else if (
- policies.cipher.algorithm.name ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.name) {
- var secretKeyLengthBytes = policies.cipher.secretKeyLengthBytes;
- var ivLengthBytes = policies.cipher.ivLengthBytes;
- var symmetricCipher = policies.cipher.symmetricCipher;
- var deriver =
- this._determineAndCreateDeriver(policies.cipher.deriver);
- // generate and encapsulate secret key
- var kem = forge.kem.rsa.create(deriver);
- var result = kem.encrypt(publicKey, secretKeyLengthBytes);
- var iv = forge.random.getBytesSync(ivLengthBytes);
- var cipher = forge.cipher.createCipher(symmetricCipher, result.key);
- cipher.start({iv: iv});
- cipher.update(forge.util.createBuffer(data));
- cipher.finish();
- var encryptedData = cipher.output.getBytes();
- var tag = cipher.mode.tag.getBytes();
- output = result.encapsulation.toString() + iv.toString() +
- encryptedData.toString() + tag.toString();
- } else {
- throw new exceptions.CryptoLibException(
- 'The specified algorithm is not supported.');
- }
- return converters.base64Encode(output);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoForgeAsymmetricCipher, data could not be encrypted.', error);
- }
- },
- /**
- * Decrypts some encrypted data.
- *
- * @function
- * @param privateKeyPem
- * {string} private key, as string in PEM format.
- * @param encryptedDataB64
- * {string} encrypted data, as string in Base64 encoded
- * format.
- * @returns decrypted data, as string in Base64 encoded format.
- */
- decrypt: function(privateKeyPem, encryptedDataBase64) {
- this._validateInputs(privateKeyPem, encryptedDataBase64);
- try {
- var privateKey = box.forge.pki.privateKeyFromPem(privateKeyPem);
- var encryptedData = converters.base64Decode(encryptedDataBase64);
- var decryptedData;
- if (policies.cipher.algorithm.name ===
- Config.asymmetric.cipher.algorithm.RSA_OAEP.name) {
- var decodingOptions = this._getRsaOaepDecodingOptions();
- decryptedData = privateKey.decrypt(
- encryptedData, policies.cipher.algorithm.name, decodingOptions);
- } else if (
- policies.cipher.algorithm.name ===
- Config.asymmetric.cipher.algorithm.RSA_KEM.name) {
- var symmetricCipher = policies.cipher.symmetricCipher;
- var secretKeyLengthBytes = policies.cipher.secretKeyLengthBytes;
- var encryptedDataParts = this._parseParts(privateKey, encryptedData);
- var deriver =
- this._determineAndCreateDeriver(policies.cipher.deriver);
- // decrypt encapsulated secret key
- var kem = forge.kem.rsa.create(deriver);
- var key = kem.decrypt(
- privateKey, encryptedDataParts.encapsulation,
- secretKeyLengthBytes);
- // decrypt some bytes
- var decipher = forge.cipher.createDecipher(symmetricCipher, key);
- decipher.start(
- {iv: encryptedDataParts.iv, tag: encryptedDataParts.tag});
- decipher.update(forge.util.createBuffer(encryptedDataParts.data));
- var result = decipher.finish();
- // result will be false if there was a failure
- if (result) {
- decryptedData = decipher.output.getBytes();
- } else {
- throw new exceptions.CryptoLibException(
- 'Error while decrypting data.');
- }
- } else {
- throw new exceptions.CryptoLibException(
- 'The specified algorithm is not supported.');
- }
- return converters.base64Encode(decryptedData);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoForgeAsymmetricCipher, data could not be decrypted.', error);
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
- /** @namespace asymmetric/keypair */
- cryptolib.modules.asymmetric.keypair = function(box) {
- 'use strict';
- box.asymmetric = box.asymmetric || {};
- box.asymmetric.keypair = {};
- /**
- * A module that holds certificates functionalities.
- *
- * @exports asymmetric/keypair/factory
- */
- box.asymmetric.keypair.factory = {};
- var policies = {
- encryption: {
- algorithm: box.policies.asymmetric.keypair.encryption.algorithm,
- provider: box.policies.asymmetric.keypair.encryption.provider,
- keyLength: box.policies.asymmetric.keypair.encryption.keyLength,
- publicExponent: box.policies.asymmetric.keypair.encryption.publicExponent
- }
- };
- var exceptions, randomFactory;
- var f = function(box) {
- exceptions = box.commons.exceptions;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.asymmetric.keypair.secureRandom.provider}
- }
- };
- cryptolib('commons.exceptions', 'primitives.securerandom', f);
- /**
- * A factory class for generating
- * {@link asymmetric.keypair.CryptoForgeKeyPairGenerator} objects.
- *
- * @class
- */
- box.asymmetric.keypair.factory.KeyPairGeneratorFactory = function() {};
- box.asymmetric.keypair.factory.KeyPairGeneratorFactory.prototype = {
- /**
- * @function
- * @returns CryptoForgeKeyPairGenerator
- */
- getEncryptionCryptoKeyPairGenerator: function() {
- var secureRandom;
- try {
- if (policies.encryption.provider ===
- Config.asymmetric.keypair.encryption.provider.FORGE) {
- secureRandom = randomFactory.getCryptoRandomBytes();
- return this.getCryptoForgeKeyPairGenerator(secureRandom);
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'An encryption CryptoKeyPairGenerator could not be obtained.',
- error);
- }
- },
- getCryptoForgeKeyPairGenerator: function(secureRandom) {
- return new CryptoForgeKeyPairGenerator(secureRandom);
- }
- };
- /**
- * Defines an encryption key pair generator for the FORGE provider.
- *
- * @class
- * @memberof asymmetric/keypair
- */
- function CryptoForgeKeyPairGenerator(secureRandom) {
- this.secureRandom = secureRandom;
- }
- CryptoForgeKeyPairGenerator.prototype = {
- /**
- * Generates an encryption key pair.
- *
- * @returns {asymmetric/keypair.KeyPair} an encryption key pair.
- */
- generate: function() {
- try {
- if (policies.encryption.algorithm ===
- Config.asymmetric.keypair.encryption.algorithm.RSA) {
- var options = {prng: this.secureRandom};
- var keys = forge.pki.rsa.generateKeyPair(
- policies.encryption.keyLength, policies.encryption.publicExponent,
- options);
- var forgePublicKey = keys.publicKey;
- var forgePrivateKey = keys.privateKey;
- var publicKeyPem = forge.pki.publicKeyToPem(forgePublicKey);
- var privateKeyPem = forge.pki.privateKeyToPem(forgePrivateKey);
- var publicKey = new PublicKey(
- policies.encryption.algorithm, forgePublicKey.n, forgePublicKey.e,
- publicKeyPem);
- var privateKey = new PrivateKey(
- policies.encryption.algorithm, forgePrivateKey.n,
- forgePrivateKey.e, forgePrivateKey.d, forgePrivateKey.p,
- forgePrivateKey.q, forgePrivateKey.dP, forgePrivateKey.dQ,
- forgePrivateKey.qInv, privateKeyPem);
- return new KeyPair(publicKey, privateKey);
- } else {
- throw new exceptions.CryptoLibException(
- 'The given algorithm is not supported.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Encryption key pair could not be generated.', error);
- }
- }
- };
- /**
- * Container class for an encryption key pair.
- *
- * @class
- * @param publicKey
- * public key of the encryption key pair.
- * @param privateKey
- * private key of the encryption key pair.
- * @memberof asymmetric/keypair
- */
- function KeyPair(publicKey, privateKey) {
- /**
- * Retrieves the public key of the encryption key pair.
- *
- * @function
- * @returns PrivateKey Public key of encryption key pair.
- */
- var getPublicKey = function() {
- return publicKey;
- };
- /**
- * Retrieves the private key of the encryption key pair.
- *
- * @function
- * @returns PrivateKey Private key of encryption key pair.
- */
- var getPrivateKey = function() {
- return privateKey;
- };
- return {getPublicKey: getPublicKey, getPrivateKey: getPrivateKey};
- }
- /**
- * @class PrivateKey
- * @memberof asymmetric/keypair
- */
- function PrivateKey(algorithm, n, e, d, p, q, dP, dQ, qInv, pem) {
- /**
- * @function
- * @returns {string}
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getAlgorithm = function() {
- return algorithm;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getModulus = function() {
- return n;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getPublicExponent = function() {
- return e;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getPrivateExponent = function() {
- return d;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getPrime1 = function() {
- return p;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getPrime2 = function() {
- return q;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getExponent1 = function() {
- return dP;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getExponent2 = function() {
- return dQ;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getCoefficient = function() {
- return qInv;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PrivateKey
- */
- var getPem = function() {
- return pem;
- };
- return {
- getAlgorithm: getAlgorithm,
- getModulus: getModulus,
- getPublicExponent: getPublicExponent,
- getPrivateExponent: getPrivateExponent,
- getPrime1: getPrime1,
- getPrime2: getPrime2,
- getExponent1: getExponent1,
- getExponent2: getExponent2,
- getCoefficient: getCoefficient,
- getPem: getPem
- };
- }
- /** @class PublicKey */
- function PublicKey(algorithm, n, e, pem) {
- /**
- * @function
- * @memberof asymmetric/keypair.PublicKey
- */
- var getAlgorithm = function() {
- return algorithm;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PublicKey
- */
- var getModulus = function() {
- return n;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PublicKey
- */
- var getPublicExponent = function() {
- return e;
- };
- /**
- * @function
- * @memberof asymmetric/keypair.PublicKey
- */
- var getPem = function() {
- return pem;
- };
- return {
- getAlgorithm: getAlgorithm,
- getModulus: getModulus,
- getPublicExponent: getPublicExponent,
- getPem: getPem
- };
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
- cryptolib.modules.asymmetric.service = function(box) {
- 'use strict';
- box.asymmetric = box.asymmetric || {};
- /**
- * A module that holds certificates functionalities.
- * @exports asymmetric/service
- */
- box.asymmetric.service = {};
- var keypairGeneratorFactory, signerFactory, xmlSignerFactory,
- cipherFactory;
- cryptolib(
- 'asymmetric.signer', 'asymmetric.xmlsigner', 'asymmetric.keypair',
- 'asymmetric.cipher', 'commons.exceptions', function(box) {
- keypairGeneratorFactory =
- new box.asymmetric.keypair.factory.KeyPairGeneratorFactory();
- signerFactory = new box.asymmetric.signer.factory.SignerFactory();
- xmlSignerFactory =
- new box.asymmetric.xmlsigner.factory.XmlSignerFactory();
- cipherFactory =
- new box.asymmetric.cipher.factory.AsymmetricCipherFactory();
- });
- /**
- * Generates a {@link asymmetric/keypair.KeyPair} to be used for encrypt data.
- * @function
- * @returns {asymmetric/keypair.KeyPair} it can be used for encrypt data.
- */
- box.asymmetric.service.getKeyPairForEncryption = function() {
- var cryptoKeyPairGenerator =
- keypairGeneratorFactory.getEncryptionCryptoKeyPairGenerator();
- return cryptoKeyPairGenerator.generate();
- };
- /**
- * Encrypts the given plain text using the given
- * public key.
- * @function
- * @param publicKeyPem
- * {String} public key, as string in PEM format.
- * @param dataBase64
- * {String} data to encrypt, as a string in Base64 encoded
- * format.
- * @return encrypted data in Base64 encoded format.
- */
- box.asymmetric.service.encrypt = function(publicKeyPem, dataBase64) {
- var cipher = cipherFactory.getCryptoAsymmetricCipher();
- return cipher.encrypt(publicKeyPem, dataBase64);
- };
- /**
- * Decrypts the given cipher text with the given
- * private key.
- * @function
- * @param privateKeyPem
- * {String} private key, as string in PEM format.
- * @param encryptedDataBase64
- * {String} data to decrypt, as a string in Base64 encoded
- * format.
- * @return a string in Base64 encoded format.
- */
- box.asymmetric.service.decrypt = function(
- privateKeyPem, encryptedDataBase64) {
- var cipher = cipherFactory.getCryptoAsymmetricCipher();
- return cipher.decrypt(privateKeyPem, encryptedDataBase64);
- };
- /**
- * Signs the given message using the given private key.
- * @function
- * @param privateKeyPem
- * {String} private key, as string in PEM format.
- * @param arrayDataBase64
- * {String} data to sign, as an array of string in Base64 encoded
- * format.
- * @return signature, in Base64 encoded format.
- */
- box.asymmetric.service.sign = function(privateKeyPem, ArrayDataBase64) {
- var cryptoSigner = signerFactory.getCryptoSigner();
- return cryptoSigner.sign(privateKeyPem, ArrayDataBase64);
- };
- /**
- * Verifies that the given signature is indeed the signature of the given
- * bytes, using the given public key.
- * @function
- * @param signatureB64
- * {String} signature, as string in Base64 encoded format.
- * @param publicKeyPem
- * {String} public key, as string in PEM format.
- * @param arrayDataBase64
- * {String} data that was signed, as an array of string in Base64
- * encoded format.
- *
- * @return boolean indicating whether signature verification was successful.
- */
- box.asymmetric.service.verifySignature = function(
- signatureBase64, publicKeyPem, arrayDataBase64) {
- var cryptoSigner = signerFactory.getCryptoSigner();
- return cryptoSigner.verify(signatureBase64, publicKeyPem, arrayDataBase64);
- };
- /**
- * Verifies the signature of some data that is in XML format.
- * @function
- * @param publicKey
- * {Object} Public key.
- * @param signedXml
- * {string} XML with selfcontained signature, to verify
- * @param signatureParentNode
- * {string} Node where the signature is
- *
- * @return boolean indicating whether signature verification was successful.
- */
- box.asymmetric.service.verifyXmlSignature = function(
- publicKey, signedXml, signatureParentNode) {
- var cryptoXmlSigner = xmlSignerFactory.getCryptoXmlSigner();
- return cryptoXmlSigner.verify(publicKey, signedXml, signatureParentNode);
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
- /** @namespace asymmetric/signer */
- cryptolib.modules.asymmetric.signer = function(box) {
- 'use strict';
- box.asymmetric = box.asymmetric || {};
- box.asymmetric.signer = {};
- /**
- * A module that holds asymmetric signature functionalities.
- *
- * @exports asymmetric/signer/factory
- */
- box.asymmetric.signer.factory = {};
- var policies = {
- algorithm: box.policies.asymmetric.signer.algorithm,
- provider: box.policies.asymmetric.signer.provider,
- hash: box.policies.asymmetric.signer.hash,
- padding: box.policies.asymmetric.signer.padding,
- publicExponent: box.policies.asymmetric.signer.publicExponent
- };
- var converters, exceptions, randomFactory;
- var f = function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.asymmetric.signer.secureRandom.provider}
- }
- };
- cryptolib('commons', 'primitives.securerandom', f);
- /**
- * A factory class for creating a digital signer.
- *
- * @class
- */
- box.asymmetric.signer.factory.SignerFactory = function() {};
- box.asymmetric.signer.factory.SignerFactory.prototype = {
- getCryptoSigner: function() {
- try {
- if (policies.provider === Config.asymmetric.signer.provider.FORGE) {
- var secureRandom = randomFactory.getCryptoRandomBytes();
- return this.getCryptoForgeSigner(secureRandom);
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider for the signer was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoSigner could not be obtained.', error);
- }
- },
- /**
- * @function
- * @return {asymmetric/signer.CryptoForgeSigner}
- */
- getCryptoForgeSigner: function(secureRandom) {
- return new CryptoForgeSigner(secureRandom);
- }
- };
- /**
- * A digital signer.
- *
- * @class
- * @memberof asymmetric/signer
- * @param secureRandom
- */
- function CryptoForgeSigner(secureRandom) {
- this.digester = null;
- this.secureRandom = secureRandom;
- try {
- if (policies.algorithm !== Config.asymmetric.signer.algorithm.RSA) {
- throw new exceptions.CryptoLibException(
- 'The given algorithm is not supported');
- }
- if (policies.hash === Config.asymmetric.signer.hash.SHA256) {
- this.digester = forge.md.sha256.create();
- } else {
- var errorMessage = 'Message digester type \'' + policies.hash +
- '\' not recognized by signer.';
- throw new exceptions.CryptoLibException(errorMessage);
- }
- if (typeof(policies.padding) !== 'undefined' &&
- policies.padding.PSS.name === Config.asymmetric.signer.padding.PSS.name) {
- var paddingHash;
- if (policies.padding.PSS.hash ===
- Config.asymmetric.signer.padding.PSS.hash.SHA256) {
- paddingHash = forge.md.sha256.create();
- }
- var paddingMgf;
- if (policies.padding.PSS.mask.MGF1.name ===
- Config.asymmetric.signer.padding.PSS.mask.MGF1.name &&
- policies.padding.PSS.mask.MGF1.hash ===
- Config.asymmetric.signer.padding.PSS.mask.MGF1.hash.SHA256) {
- var mgfHash = forge.md.sha256.create();
- paddingMgf = forge.mgf.mgf1.create(mgfHash);
- }
- this.padding = forge.pss.create({
- md: paddingHash,
- mgf: paddingMgf,
- saltLength: policies.padding.PSS.saltLengthBytes,
- prng: this.secureRandom
- });
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoForgeSigner could not be created.', error);
- }
- }
- CryptoForgeSigner.prototype = {
- /**
- * Digitally signs some data.
- *
- * @function
- * @param privateKeyPem
- * Private key, as string in PEM format.
- * @param arrayDataBase64
- * Data to sign, as an array of string in Base64 encoded
- * format.
- * @returns signature, in Base64 encoded format.
- */
- sign: function(privateKeyPem, arrayDataBase64) {
- try {
- var privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
- if (privateKey.e.toString() !== policies.publicExponent.toString()) {
- throw new exceptions.CryptoLibException(
- 'Private key has not been generated with the required exponent : ' +
- policies.publicExponent);
- }
- if (!arrayDataBase64 || arrayDataBase64.length < 1) {
- throw new exceptions.CryptoLibException(
- 'The array of data in Base64 should contain at least one element.');
- }
- this.digester.start();
- var dataB64;
- var data;
- for (var i = 0; i < arrayDataBase64.length; i++) {
- dataB64 = arrayDataBase64[i];
- if (dataB64 === undefined || dataB64 === null) {
- throw new exceptions.CryptoLibException(
- 'The input data contained an element that was not defined or empty.');
- }
- data = converters.base64Decode(dataB64);
- this.digester.update(data);
- }
- var signature = privateKey.sign(this.digester, this.padding);
- return converters.base64Encode(signature);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Signature could not be generated.', error);
- }
- },
- /**
- * Verifies the digital signature of some data.
- *
- * @function
- *
- * @param signatureB64
- * Signature, as string in Base64 encoded format.
- * @param publicKeyPem
- * Public key, as string in PEM format.
- * @param arrayDataBase64
- * Data that was signed, as an array of string in Base64
- * encoded format.
- *
- * @returns boolean indicating whether signature verification was
- * successful.
- */
- verify: function(signatureB64, publicKeyPem, arrayDataBase64) {
- try {
- var publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
- if (publicKey.e.toString() !== policies.publicExponent.toString()) {
- throw new exceptions.CryptoLibException(
- 'Public key has not been generated with the required exponent : ' +
- policies.publicExponent);
- }
- if (!arrayDataBase64 || arrayDataBase64.length < 1) {
- throw new exceptions.CryptoLibException(
- 'The array of data in Base64 should contain at least one element.');
- }
- this.digester.start();
- var dataB64;
- for (var i = 0; i < arrayDataBase64.length; i++) {
- dataB64 = arrayDataBase64[i];
- if (dataB64 === undefined || dataB64 === null) {
- throw new exceptions.CryptoLibException(
- 'The input data contained an element that was not defined or empty.');
- }
- var data = converters.base64Decode(dataB64);
- this.digester.update(data);
- }
- var signature = converters.base64Decode(signatureB64);
- return publicKey.verify(
- this.digester.digest().getBytes(), signature, this.padding);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Signature could not be verified.', error);
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.asymmetric = cryptolib.modules.asymmetric || {};
- /**
- * Defines the asymmetric signers.
- *
- * @namespace asymmetric/xmlsigner
- */
- cryptolib.modules.asymmetric.xmlsigner = function(box) {
- 'use strict';
- box.asymmetric = box.asymmetric || {};
- box.asymmetric.xmlsigner = {};
- /**
- * A module that holds certificates functionalities.
- *
- * @exports asymmetric/xmlsigner/factory
- */
- box.asymmetric.xmlsigner.factory = {};
- var policies = {
- algorithm: box.policies.asymmetric.signer.algorithm,
- provider: box.policies.asymmetric.signer.provider,
- hash: box.policies.asymmetric.signer.hash
- };
- var utils, exceptions, converters, parsers, stringUtils;
- var f = function(box) {
- exceptions = box.commons.exceptions;
- utils = box.commons.utils;
- converters = new box.commons.utils.Converters();
- parsers = new utils.Parsers();
- stringUtils = new utils.StringUtils();
- };
- cryptolib('commons', f);
- /**
- * A factory class for creating an XML digital signature verifier.
- *
- * @class
- */
- box.asymmetric.xmlsigner.factory.XmlSignerFactory = function() {};
- box.asymmetric.xmlsigner.factory.XmlSignerFactory.prototype = {
- /**
- * Gets a {@link asymmetric/xmlsigner.CryptoForgeXmlSigner}.
- *
- * @function
- * @return {asymmetric/xmlsigner.CryptoForgeXmlSigner}
- */
- getCryptoXmlSigner: function() {
- try {
- if (policies.provider === Config.asymmetric.signer.provider.FORGE) {
- return new CryptoForgeXmlSigner();
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider for the signer was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoXmlSigner could not be obtained.', error);
- }
- }
- };
- /**
- * Holds xml signature properties.
- *
- * @class
- * @memberof asymmetric/xmlsigner
- */
- function XmlSignature(signatureNode) {
- // go through all the nodes to load all relevant information
- var signedInfoNode;
- var signatureValueNode;
- var canonicalizationMethodNode;
- var signatureMethodNode;
- var referenceNode;
- var digestMethodNode;
- var digestValueNode;
- var transformsNode;
- try {
- signedInfoNode = new utils.XPath(signatureNode.getXml(), 'SignedInfo');
- signatureValueNode =
- new utils.XPath(signatureNode.getXml(), 'SignatureValue');
- canonicalizationMethodNode =
- new utils.XPath(signedInfoNode.getXml(), 'CanonicalizationMethod');
- signatureMethodNode =
- new utils.XPath(signedInfoNode.getXml(), 'SignatureMethod');
- referenceNode = new utils.XPath(signedInfoNode.getXml(), 'Reference');
- digestMethodNode =
- new utils.XPath(referenceNode.getXml(), 'DigestMethod');
- digestValueNode = new utils.XPath(referenceNode.getXml(), 'DigestValue');
- transformsNode = new utils.XPath(referenceNode.getXml(), 'Transforms');
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not parse signed XML file', error);
- }
- // there are signatures without key, so we ignore them
- var rsaKeyValueNode;
- var modulusNode;
- var exponentNode;
- try {
- rsaKeyValueNode = new utils.XPath(
- signatureNode.getXml(), 'KeyInfo/KeyValue/RSAKeyValue');
- modulusNode = new utils.XPath(rsaKeyValueNode.getXml(), 'Modulus');
- exponentNode = new utils.XPath(rsaKeyValueNode.getXml(), 'Exponent');
- } catch (error) {
- // ignore if this part fails
- }
- // build the object structure
- /** @property {object} */
- this.info = {
- method: signatureMethodNode.getAttribute('Algorithm'),
- value: signatureValueNode.getValue(),
- meta: signatureNode.getAttribute('xmlns')
- };
- /** @property {object} */
- this.canonicalization = {
- method: canonicalizationMethodNode.getAttribute('Algorithm')
- };
- /** @property {object} */
- this.reference = {
- uri: referenceNode.getAttribute('URI'),
- transforms: [],
- digest: {
- method: digestMethodNode.getAttribute('Algorithm'),
- value: digestValueNode.getValue()
- }
- };
- /** @property {object} */
- this.rsakey = {
- modulus: modulusNode ? modulusNode.getValue() : '',
- exponent: exponentNode ? exponentNode.getValue() : ''
- };
- // update the transforms references
- var transforms = transformsNode.getChildren();
- for (var i = 0; i < transforms.length; i++) {
- if (transforms[i].nodeType === Node.ELEMENT_NODE) {
- var transformNode = new utils.XPath(transforms[i]);
- this.reference.transforms.push(transformNode.getAttribute('Algorithm'));
- }
- }
- }
- /**
- * @class
- * @memberof asymmetric/xmlsigner
- */
- function ExclusiveCanonicalization() {}
- /**
- * Sorts the attributes
- *
- * @function
- * @param xmlNode
- * xml node, as a DOM.
- */
- ExclusiveCanonicalization.prototype.sortAttributes = function(xmlNode) {
- // gather all attributes and remove them
- var list = [];
- var attr;
- if (xmlNode.attributes) {
- for (var i = 0; i < xmlNode.attributes.length; i++) {
- attr = xmlNode.attributes[i];
- list.push({id: attr.name, val: xmlNode.getAttribute(attr.name)});
- xmlNode.removeAttribute(attr.name);
- i--;
- }
- }
- // sort the attributes
- list.sort(function(a, b) {
- if (a.id < b.id) {
- return -1;
- }
- if (a.id > b.id) {
- return 1;
- }
- return 0;
- });
- // reinsert the attributes
- for (var j = 0; j < list.length; j++) {
- attr = list[j];
- xmlNode.setAttribute(attr.id, attr.val);
- }
- };
- /**
- * Inits the process of canonicalization.
- *
- * @function
- * @param xmlNode
- * xml node, as a DOM.
- *
- * @return xml node processed, as DOM.
- */
- ExclusiveCanonicalization.prototype.process = function(xml) {
- // traverse the tree through all the children
- for (var i = 0; i < xml.childNodes.length; i++) {
- var child = xml.childNodes[i];
- if (child.nodeType === Node.ELEMENT_NODE) {
- this.process(child);
- }
- // if are comments or other stuff, remove them
- else if (child.nodeType !== Node.TEXT_NODE) {
- child.parentNode.removeChild(child);
- --i;
- }
- }
- // sort the attributes
- this.sortAttributes(xml);
- // return the final object
- return xml;
- };
- /**
- * An xml signer.
- *
- * @class
- * @memberof asymmetric/xmlsigner
- */
- function CryptoForgeXmlSigner() {}
- CryptoForgeXmlSigner.prototype = {
- /**
- * Verifies the digital signature of a selfsigned xml.
- *
- * @function
- * @param publicKey
- * Public key, as an object.
- * @param signedXml
- * XML data, as a string
- * @param signatureParentNode
- * The node where the signature is, as a string.
- *
- * @returns Boolean indicating whether signature verification was
- * successful.
- */
- verify: function(publicKey, signedXml, signatureParentNode) {
- // clean the comments in the xml
- signedXml = this._removeXmlStringComments(signedXml);
- // loads the text to an xml
- var xml = parsers.xmlFromString(signedXml);
- // loads the xml signature structure to json
- var signature = this._loadSignature(xml, signatureParentNode);
- // check all the algorithms are the expected ones
- this._verifyAlgorithmsInSignature(signature);
- // check the public key is the expected one
- this._verifyPublicKeyInSignature(signature, publicKey);
- // check the references are well encoded
- this._validateReferences(signature, signedXml);
- // validates the signatures are right
- this._validateSignature(signature, publicKey);
- // if not exception raised, all went good
- return true;
- },
- /**
- * Gets the XML signature node from the main XML node
- *
- * @function
- * @private
- * @param xml
- * XML where the signature is, as a Document Object
- * @param signatureParentNode
- * The node where the signature is, as a string.
- *
- * @returns Object with the DOM node of the signature and and the
- * signature in json.
- */
- _loadSignature: function(xml, signatureParentNode) {
- // access to the node where the signature is, and take the methods
- try {
- // get the signature node
- var xmlNode = new utils.XPath(xml, signatureParentNode);
- // create signature object to load the data from the signature
- var data = new XmlSignature(xmlNode);
- // return the main object
- return {xmlNode: xmlNode, data: data};
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not load the signature from the XML', error);
- }
- },
- /**
- * Verifies that the method algorithms in the EML and the properties
- * match.
- *
- * @function
- * @private
- * @param signature
- * Signature, as a Javascript Object
- */
- _verifyAlgorithmsInSignature: function(signature) {
- try {
- if (signature.data.canonicalization.method !==
- 'http://www.w3.org/2001/10/xml-exc-c14n#') {
- throw new exceptions.CryptoLibException(
- 'Invalid canonicalization algorithm');
- }
- if (!stringUtils.containsSubString(
- signature.data.info.method, policies.algorithm) &&
- !stringUtils.containsSubString(
- signature.data.info.method, policies.hash)) {
- throw new exceptions.CryptoLibException(
- 'Invalid signature algorithm');
- }
- if (!stringUtils.containsSubString(
- signature.data.reference.digest.method, policies.hash)) {
- throw new exceptions.CryptoLibException('Invalid digest algorithm');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not verify the data in the XML.', error);
- }
- },
- /**
- * Verifies the public key is the same than the one in the EML.
- *
- * @function
- * @private
- * @param signature
- * Signature, as a Javascript Object
- * @param publicKey
- * Public key, as an object.
- */
- _verifyPublicKeyInSignature: function(signature, publicKey) {
- // it has no key
- if (!signature.data.rsakey.exponent || !signature.data.rsakey.modulus) {
- return;
- }
- // if it has key, we validate it
- try {
- var signatureExponent =
- converters.base64ToBigInteger(signature.data.rsakey.exponent);
- var signatureModulus =
- converters.base64ToBigInteger(signature.data.rsakey.modulus);
- if (publicKey.e.compareTo(signatureExponent) !== 0 ||
- publicKey.n.compareTo(signatureModulus) !== 0) {
- throw new exceptions.CryptoLibException('Invalid public key');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not verify the data in the XML.', error);
- }
- },
- /**
- * Verifies the references of a selfsigned xml.
- *
- * @function
- * @private
- * @param signature
- * Signature, as a Javascript Object
- */
- _validateReferences: function(signature, xmlString) {
- try {
- var xmlCanonString;
- // The canonicalization transformations are performed here.
- // Due to differences in the behaviour of Internet Explorer,
- // these transformations must be applied manually in the case
- // of that browser. For all other browsers, the transformations
- // are performed by applying a canonicalization algorithm.
- if (parsers.isIE()) {
- xmlCanonString = this._removeXmlStringHeader(xmlString);
- xmlCanonString = this._removeXmlStringSelfClosingTags(xmlCanonString);
- xmlCanonString = this._removeXmlStringSignature(xmlCanonString);
- xmlCanonString = this._removeXmlStringFirstCharacter(xmlCanonString);
- } else {
- var xmlCanon = null;
- // apply all transforms to the xml
- for (var i = 0; i < signature.data.reference.transforms.length; i++) {
- // get the algorithm name
- var algorithm = signature.data.reference.transforms[i];
- // consume it if it exists
- if (algorithm in this._transformAlgorithmMap) {
- xmlCanon = this._transformAlgorithmMap[algorithm](
- signature.xmlNode.getXml());
- }
- }
- xmlCanon = this._removeXmlHeader(xmlCanon);
- xmlCanonString = parsers.xmlToString(xmlCanon, true);
- }
- var digester =
- this._getHashMethod(signature.data.reference.digest.method);
- digester.start();
- digester.update(
- parsers.removeCarriageReturnChars(xmlCanonString), 'utf8');
- var messageDigest = digester.digest();
- // check if the result is valid
- var encodedMessage = forge.util.encode64(messageDigest.getBytes());
- if (encodedMessage !== signature.data.reference.digest.value) {
- throw new exceptions.CryptoLibException(
- 'Invalid reference: \'' + encodedMessage +
- '\' when was expected \'' +
- signature.data.reference.digest.value + '\'');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not validate references.', error);
- }
- },
- /**
- * Verifies the digital signature of a selfsigned xml.
- *
- * @function
- * @private
- * @param signature
- * Signature, as a Javascript Object
- * @param publicKey
- * Public key, as an object.
- */
- _validateSignature: function(signature, publicKey) {
- try {
- var signedInfoNode =
- new utils.XPath(signature.xmlNode.getXml(), '/SignedInfo');
- var algorithm = signature.data.canonicalization.method;
- var xmlCanon = null;
- if (algorithm in this._transformAlgorithmMap) {
- xmlCanon =
- this._transformAlgorithmMap[algorithm](signedInfoNode.getXml());
- }
- var digester = this._getHashMethod(signature.data.info.method);
- digester.start();
- digester.update(parsers.xmlToString(xmlCanon, true), 'utf8');
- var signatureValue = forge.util.decode64(signature.data.info.value);
- var result =
- publicKey.verify(digester.digest().getBytes(), signatureValue);
- if (!result) {
- throw new exceptions.CryptoLibException(
- 'Could not validate the signature.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not validate signatures.', error);
- }
- },
- /**
- * Creates the hash method
- *
- * @function
- * @private
- * @param method
- * method type, as string.
- *
- * @return Object, the disgester of that method.
- */
- _getHashMethod: function(method) {
- if (stringUtils.containsSubString(method, 'sha256')) {
- return forge.md.sha256.create();
- }
- },
- /**
- * Map with all tarnsform algorithms
- *
- * @function
- * @private
- */
- _transformAlgorithmMap: {
- /**
- * Removes the signature from a signed XML
- *
- * @param xmlSignature
- * the xml signature, as DOM.
- *
- * @return the XML top document, as DOM
- */
- 'http://www.w3.org/2000/09/xmldsig#enveloped-signature': function(
- xmlSignature) {
- var topElement = xmlSignature;
- // get the top document
- while (topElement.parentNode) {
- topElement = topElement.parentNode;
- }
- // remove the signature from the node
- xmlSignature.parentNode.removeChild(xmlSignature);
- return topElement;
- },
- /**
- * c14n the XML
- *
- * @param xmlNode
- * the xml node, as DOM.
- *
- * @return the XML top document, as DOM
- */
- 'http://www.w3.org/2001/10/xml-exc-c14n#': function(xmlNode) {
- var transform = new ExclusiveCanonicalization();
- return transform.process(xmlNode);
- }
- },
- /**
- * Removes the comments in the xml
- *
- * @function
- * @private
- * @param xml
- * the xml, as string.
- *
- * @return {string} the xml without comments
- */
- _removeXmlStringComments: function(xml) {
- return xml.replace(/<!--[\s\S]*?-->/g, '');
- },
- /**
- * Removes the header in the xml structure. <?xml version="1.0"
- * encoding="UTF-8"?>
- *
- * @function
- * @private
- * @param {object}
- * xmlDocument the xml, as DOM.
- *
- * @returns {object} the xml, as DOM without the header
- */
- _removeXmlHeader: function(xmlDocument) {
- return xmlDocument.documentElement ? xmlDocument.documentElement :
- xmlDocument;
- },
- /**
- * Removes the header in the XML string.
- *
- * @param xmlString
- * the xml, as a string.
- *
- * @return the xml string without the header
- */
- _removeXmlStringHeader: function(xmlString) {
- return parsers.removeXmlHeaderFromString(xmlString);
- },
- /**
- * Removes the signature node in the XML string.
- *
- * @param xmlString
- * the xml, as a string.
- *
- * @return the xml string without the signature tag
- */
- _removeXmlStringSignature: function(xmlString) {
- return parsers.removeXmlSignature(xmlString);
- },
- /**
- * Converts any self-closing tags to opening and closing tags, within an
- * XML string.
- *
- * @param xmlString
- * the xml, as a string.
- *
- * @return the xml string with self-closing tags converted to opening
- * and closing tags
- */
- _removeXmlStringSelfClosingTags: function(xmlString) {
- return parsers.xmlRemoveSelfClosingTags(xmlString);
- },
- /**
- * Removes the first character from an XML string if that character is
- * not the expected initial character.
- *
- * @param xmlString
- * the xml, as a string.
- *
- * @return the xml string with the initial character removed if it is
- * not wanted
- */
- _removeXmlStringFirstCharacter: function(xmlString) {
- if (xmlString[0] !== '<') {
- return xmlString.slice(1, xmlString.length);
- } else {
- return xmlString;
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- /** @namespace certificates */
- cryptolib.modules.certificates = function(box) {
- 'use strict';
- if (box.certificates) {
- return;
- }
- box.certificates = {};
- /**
- * Provides an API that can be used to perform operations with certificates.
- *
- * @exports certificates/service
- */
- box.certificates.service = {};
- var converters;
- var exceptions;
- cryptolib('commons', function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- });
- /**
- * Loads a certificate in pem format.
- *
- * @function
- * @param {string}
- * certificatePem certificate as string in PEM format.
- * @returns {certificates.box.certificates.CryptoX509Certificate} the
- * certificate.
- */
- box.certificates.service.load = function(certificatePem) {
- return new box.certificates.CryptoX509Certificate(certificatePem);
- };
- /**
- * Provides methods to access X509 certificate data.
- *
- * @class
- * @param certificatePem
- * certificate as string in PEM format.
- * @memberof certificates
- */
- box.certificates.CryptoX509Certificate = function(certificatePem) {
- /** @property {object} certificate the certificate. * */
- this.certificate = forge.pki.certificateFromPem(certificatePem, true);
- };
- box.certificates.CryptoX509Certificate.prototype = {
- /**
- * Retrieves the public key of the certificate.
- *
- * @function
- * @returns public key, as string in PEM format.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getPublicKey: function() {
- var publicKey = this.certificate.publicKey;
- if (publicKey !== null) {
- return forge.pki.publicKeyToPem(publicKey);
- } else {
- throw new exceptions.CryptoLibException(
- 'Could not find public key in certificate.');
- }
- },
- /**
- * Retrieves the start time of the certificate's validity.
- *
- * @function
- * @returns start time of certificate validity, as Date object.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getNotBefore: function() {
- var notBeforeField = this.certificate.validity.notBefore;
- if (notBeforeField !== null) {
- return notBeforeField;
- } else {
- throw new exceptions.CryptoLibException(
- 'Could not find validity start time in certificate.');
- }
- },
- /**
- * Retrieves the end time of the certificate's validity.
- *
- * @function
- * @returns end time of certificate validity, as Date object.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getNotAfter: function() {
- var notAfterField = this.certificate.validity.notAfter;
- if (notAfterField !== null) {
- return notAfterField;
- } else {
- throw new exceptions.CryptoLibException(
- 'Could not find validity end time in certificate.');
- }
- },
- /**
- * Retrieves the serial number of the certificate.
- *
- * @function
- * @returns serial number of certificate, as hexadecimal string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSerialNumber: function() {
- var serialNumber = this.certificate.serialNumber;
- if (serialNumber !== null) {
- return serialNumber;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the issuer common name of the certificate.
- *
- * @function
- * @returns issuer common name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getIssuerCN: function() {
- var issuerCNField =
- this.certificate.issuer.getField({name: 'commonName'});
- if (issuerCNField !== null) {
- return issuerCNField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the issuer organizational unit of the certificate.
- *
- * @function
- * @returns issuer organizational unit of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getIssuerOrgUnit: function() {
- var orgUnitField = this.certificate.issuer.getField({shortName: 'OU'});
- if (orgUnitField !== null) {
- return orgUnitField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the issuer organization name of the certificate.
- *
- * @function
- * @returns Issuer organization name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getIssuerOrg: function() {
- var orgNameField =
- this.certificate.issuer.getField({name: 'organizationName'});
- if (orgNameField !== null) {
- return orgNameField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the issuer locality name of the certificate.
- *
- * @function
- * @returns Locality name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getIssuerLocality: function() {
- var localityField =
- this.certificate.issuer.getField({name: 'localityName'});
- if (localityField !== null) {
- return localityField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the issuer country name of the certificate.
- *
- * @function
- * @returns Issuer country name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getIssuerCountry: function() {
- var countryField =
- this.certificate.issuer.getField({name: 'countryName'});
- if (countryField !== null) {
- return countryField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the subject common name of the certificate.
- *
- * @function
- * @returns Subject common name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSubjectCN: function() {
- var subjectCNField =
- this.certificate.subject.getField({name: 'commonName'});
- if (subjectCNField !== null) {
- return subjectCNField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the subject organizational unit of the certificate.
- *
- * @function
- * @returns Subject organizational unit of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSubjectOrgUnit: function() {
- var orgUnitField = this.certificate.subject.getField({shortName: 'OU'});
- if (orgUnitField !== null) {
- return orgUnitField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the subject organization name of the certificate.
- *
- * @function
- * @return Subject organization name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSubjectOrg: function() {
- var organizationNameField =
- this.certificate.subject.getField({name: 'organizationName'});
- if (organizationNameField !== null) {
- return organizationNameField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the subject locality name of the certificate.
- *
- * @function
- * @returns Subject locality name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSubjectLocality: function() {
- var localityField =
- this.certificate.subject.getField({name: 'localityName'});
- if (localityField !== null) {
- return localityField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the subject country name of the certificate.
- *
- * @function
- * @returns Subject country name of certificate, as string.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSubjectCountry: function() {
- var countryField =
- this.certificate.subject.getField({name: 'countryName'});
- if (countryField !== null) {
- return countryField.value;
- } else {
- return '';
- }
- },
- /**
- * Retrieves the key usage extension of the certificate.
- *
- * @function
- * @return KeyUsageExtension key usage extension, as KeyUsageExtension
- * object.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getKeyUsageExtension: function() {
- var keyUsageExt = this.certificate.getExtension({name: 'keyUsage'});
- if (keyUsageExt !== null) {
- var keyUsageMap = {};
- keyUsageMap.digitalSignature = keyUsageExt.digitalSignature;
- keyUsageMap.nonRepudiation = keyUsageExt.nonRepudiation;
- keyUsageMap.keyEncipherment = keyUsageExt.keyEncipherment;
- keyUsageMap.dataEncipherment = keyUsageExt.dataEncipherment;
- keyUsageMap.keyAgreement = keyUsageExt.keyAgreement;
- keyUsageMap.keyCertSign = keyUsageExt.keyCertSign;
- keyUsageMap.crlSign = keyUsageExt.cRLSign;
- keyUsageMap.encipherOnly = keyUsageExt.encipherOnly;
- keyUsageMap.decipherOnly = keyUsageExt.decipherOnly;
- return new box.certificates.KeyUsageExtension(keyUsageMap);
- } else {
- return null;
- }
- },
- /**
- * Retrieves the basic constraints of the certificate.
- *
- * @function
- * @returns map containing the basic constraints.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getBasicConstraints: function() {
- var basicConstraints =
- this.certificate.getExtension({name: 'basicConstraints'});
- if (basicConstraints !== null) {
- var basicConstraintsMap = {};
- basicConstraintsMap.ca = basicConstraints.cA;
- return basicConstraintsMap;
- } else {
- return null;
- }
- },
- /**
- * Retrieves the digital signature of the certificate.
- *
- * @function
- * @returns digital signature of certificate, as string in Base64
- * encoded format.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- getSignature: function() {
- var signature = this.certificate.signature;
- if (signature !== null) {
- var signatureB64 =
- converters.base64Encode(signature, box.RSA_LINE_LENGTH);
- if (signatureB64 !== null) {
- return signatureB64;
- } else {
- throw new exceptions.CryptoLibException(
- 'Base64 encoding of signature is null.');
- }
- } else {
- throw new exceptions.CryptoLibException('Signature is null.');
- }
- },
- /**
- * Verifies the digital signature of the certificate provided as input,
- * using this certificate's public key.
- *
- * @function
- * @param certificatePem
- * certificate whose signature is to be verified, as string
- * in PEM format.
- * @returns boolean indicating whether signature was verified.
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- verify: function(certificatePem) {
- var certificate = forge.pki.certificateFromPem(certificatePem);
- if (certificate !== null) {
- return this.certificate.verify(certificate);
- } else {
- throw new exceptions.CryptoLibException('Certificate is null.');
- }
- },
- /**
- * Retrieves the certificate, in PEM format.
- *
- * @function
- * @returns certificate, as string in PEM format
- * @memberof certificates.box.certificates.CryptoX509Certificate
- */
- toPem: function() {
- if (this.certificate !== null) {
- return forge.pki.certificateToPem(
- this.certificate, box.RSA_LINE_LENGTH);
- } else {
- throw new exceptions.CryptoLibException('Certificate is null.');
- }
- }
- };
- /**
- * Container class for the key usage extension flags of a digital
- * certificate.
- *
- * @class
- * @param keyUsageMap
- * map containing name-value pairs of key usage extension flags.
- * @memberof certificates
- */
- box.certificates.KeyUsageExtension = function(keyUsageMap) {
- this.keyUsageMap = keyUsageMap;
- };
- box.certificates.KeyUsageExtension.prototype = {
- /**
- * Retrieves the digital signature flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether digital signature flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- digitalSignature: function() {
- return this.keyUsageMap.digitalSignature;
- },
- /**
- * Retrieves the non-repudiation flag of the key usage extension.
- *
- * @function
- * @return boolean indicating whether non-repudiation flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- nonRepudiation: function() {
- return this.keyUsageMap.nonRepudiation;
- },
- /**
- * Retrieves the key encipherment flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether key encipherment flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- keyEncipherment: function() {
- return this.keyUsageMap.keyEncipherment;
- },
- /**
- * Retrieves the data encipherment flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether data encipherment flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- dataEncipherment: function() {
- return this.keyUsageMap.dataEncipherment;
- },
- /**
- * Retrieves the key agreement flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether key agreement flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- keyAgreement: function() {
- return this.keyUsageMap.keyAgreement;
- },
- /**
- * Retrieves the key certificate sign flag of the key usage extension.
- *
- * @function
- * @returns Boolean indicating whether key certificate sign flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- keyCertSign: function() {
- return this.keyUsageMap.keyCertSign;
- },
- /**
- * Retrieves the CRL sign flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether CRL sign flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- crlSign: function() {
- return this.keyUsageMap.crlSign;
- },
- /**
- * Retrieves the encipher only flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether encipher only flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- encipherOnly: function() {
- return this.keyUsageMap.encipherOnly;
- },
- /**
- * Retrieves the decipher only flag of the key usage extension.
- *
- * @function
- * @returns boolean indicating whether decipher only flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- decipherOnly: function() {
- return this.keyUsageMap.decipherOnly;
- },
- /**
- * Retrieves the CA flag of the key usage extension.
- *
- * @function
- * @return boolean indicating whether CA flag is set.
- * @memberof certificates.box.certificates.KeyUsageExtension
- */
- ca: function() {
- return this.keyUsageMap.ca;
- }
- };
- /**
- * Class that validates the content of a CryptoX509Certificate.
- *
- * @class
- * @param validationData
- * @param {string}
- * validationData.subject
- * @param {string}
- * validationData.subject.commonName
- * @param {string}
- * validationData.subject.organization
- * @param {string}
- * validationData.subject.organizationUnit
- * @param {string}
- * validationData.subject.country
- * @param {string}
- * validationData.issuer
- * @param {string}
- * validationData.issuer.commonName
- * @param {string}
- * validationData.issuer.organization
- * @param {string}
- * validationData.issuer.organizationUnit
- * @param {string}
- * validationData.issuer.country
- * @param {string}
- * validationData.time
- * @param {string}
- * validationData.keytype CA, Sign or Encryption
- * @param {string}
- * validationData.caCertificatePem
- * @memberof certificates
- */
- box.certificates.CryptoX509CertificateValidator = function(validationData) {
- var parseIsoDate = function(isoDate) {
- var dateChunks = isoDate.split(/\D/);
- return new Date(Date.UTC(
- +dateChunks[0], --dateChunks[1], +dateChunks[2], +dateChunks[5],
- +dateChunks[6], +dateChunks[7], 0));
- };
- /**
- * Validates the content of the X.509 certificate.
- *
- * @function
- * @param certificatePem
- * certificate as string in PEM format.
- * @return an array containing the errors type, if any.
- */
- this.validate = function(x509CertificatePem) {
- var cryptoX509Certificate =
- new box.certificates.CryptoX509Certificate(x509CertificatePem);
- var failedValidations = [];
- var validateSubject = function(subject) {
- if (subject.commonName !== cryptoX509Certificate.getSubjectCN() ||
- subject.organization !== cryptoX509Certificate.getSubjectOrg() ||
- subject.organizationUnit !==
- cryptoX509Certificate.getSubjectOrgUnit() ||
- subject.country !== cryptoX509Certificate.getSubjectCountry()) {
- failedValidations.push('SUBJECT');
- }
- };
- var validateIssuer = function(issuer) {
- if (issuer.commonName !== cryptoX509Certificate.getIssuerCN() ||
- issuer.organization !== cryptoX509Certificate.getIssuerOrg() ||
- issuer.organizationUnit !==
- cryptoX509Certificate.getIssuerOrgUnit() ||
- issuer.country !== cryptoX509Certificate.getIssuerCountry()) {
- failedValidations.push('ISSUER');
- }
- };
- var validateTime = function(isoDate) {
- var time = parseIsoDate(isoDate);
- if (time.toString() === 'Invalid Date' ||
- time - cryptoX509Certificate.getNotBefore() < 0 ||
- time - cryptoX509Certificate.getNotAfter() > 0) {
- failedValidations.push('TIME');
- }
- };
- var areBasicConstraintsValid = function(keyType) {
- var returnValue = true;
- var basicConstraints = cryptoX509Certificate.getBasicConstraints();
- if (keyType === 'CA' &&
- (!basicConstraints || basicConstraints.ca !== true)) {
- returnValue = false;
- }
- return returnValue;
- };
- var isKeyUsageValid = function(keyType) {
- var returnValue = true;
- var keyUsageExtension = cryptoX509Certificate.getKeyUsageExtension();
- if (!keyUsageExtension) {
- return false;
- }
- switch (keyType) {
- case 'CA':
- if (keyUsageExtension.keyCertSign() !== true ||
- keyUsageExtension.crlSign() !== true) {
- returnValue = false;
- }
- break;
- case 'Sign':
- if (keyUsageExtension.digitalSignature() !== true ||
- keyUsageExtension.nonRepudiation() !== true) {
- returnValue = false;
- }
- break;
- case 'Encryption':
- if (keyUsageExtension.keyEncipherment() !== true ||
- keyUsageExtension.dataEncipherment() !== true) {
- returnValue = false;
- }
- break;
- default:
- returnValue = false;
- }
- return returnValue;
- };
- var validateKeyType = function(keyType) {
- if (!areBasicConstraintsValid(keyType) || !isKeyUsageValid(keyType)) {
- failedValidations.push('KEY_TYPE');
- }
- };
- var validateSignature = function(caCertificatePem) {
- var caCryptoX509Certificate =
- new box.certificates.CryptoX509Certificate(caCertificatePem);
- if (caCryptoX509Certificate === null) {
- failedValidations.push('SIGNATURE');
- throw new exceptions.CryptoLibException('CA certificate is null.');
- }
- try {
- if (!caCryptoX509Certificate.verify(x509CertificatePem)) {
- failedValidations.push('SIGNATURE');
- }
- } catch (error) {
- failedValidations.push('SIGNATURE');
- throw new exceptions.CryptoLibException(
- 'Signature verification process failed.');
- }
- };
- if (validationData.subject) {
- validateSubject(validationData.subject);
- }
- if (validationData.issuer) {
- validateIssuer(validationData.issuer);
- }
- if (validationData.time) {
- validateTime(validationData.time);
- }
- if (validationData.keyType) {
- validateKeyType(validationData.keyType);
- }
- if (validationData.caCertificatePem) {
- validateSignature(validationData.caCertificatePem);
- }
- return failedValidations;
- };
- };
- /**
- * Class that validates the content of a CryptoX509Certificate.
- *
- * @function
- * @param validationData
- * {json}
- * @param {string}
- * validationData.subject the subject data.
- * @param {string}
- * validationData.subject.commonName
- * @param {string}
- * validationData.subject.organization
- * @param {string}
- * validationData.subject.organizationUnit
- * @param {string}
- * validationData.subject.country
- * @param {string}
- * validationData.issuer the issuer data.
- * @param {string}
- * validationData.issuer.commonName
- * @param {string}
- * validationData.issuer.organization
- * @param {string}
- * validationData.issuer.organizationUnit
- * @param {string}
- * validationData.issuer.country
- * @param {string}
- * validationData.time time to be checked.
- * @param {string}
- * validationData.keyType CA, Sign or Encryption.
- * @param {string}
- * validationData.caCertificatePem
- * @param certificate
- * certificate as string in PEM format.
- * @returns {Array} an array that contains the error types occurred, if any.
- */
- box.certificates.service.validateCertificate = function(
- validationData, certificate) {
- if (validationData === null) {
- throw new exceptions.CryptoLibException('Validation data is null.');
- }
- if (Object.getOwnPropertyNames(validationData).length) {
- throw new exceptions.CryptoLibException('Validation data is empty.');
- }
- if (certificate === null) {
- throw new exceptions.CryptoLibException('Certificate is null.');
- }
- return (new box.certificates.CryptoX509CertificateValidator(validationData))
- .validate(certificate);
- };
- /**
- * Validates the certificate information provided to the constructor. The
- * validation process loops through all certificates, starting with the leaf
- * certificate, until it reaches the trusted certificate. For each
- * certificate, except the trusted certificate, it checks that the following
- * conditions hold:
- * <ul>
- * <li>Subject DN is that expected for given certificate.</li>
- * <li>Issuer DN is same as subject DN of next certificate in chain.</li>
- * <li>Key type is that expected: "signing" or "encryption" for leaf
- * certificate and "CA" for rest of certificates in chain.</li>
- * <li>Signature can be verified with public key of next certificate in
- * chain.</li>
- * <li>Starting time is earlier than ending time.</li>
- * <li>Starting time is equal to or later than starting time of next
- * certificate in chain.</li>
- * <li>Ending time is equal to or earlier than ending time of next
- * certificate in chain.</li>
- * </ul>
- * In addition, if a non-null value is provided to the constructor for the
- * time reference, it will be checked whether this time reference is within
- * the dates of validity of the leaf certificate. After the validation
- * process has completed, a list of strings will be returned. If this list
- * is empty, then the validation was successful. Otherwise, the list will
- * contain string identifiers for each type of validation that failed.
- *
- * @function
- * @param {json}
- * chain certificate chain.
- * @param {json}
- * chain.leaf leaf certificate.
- * @param {string}
- * chain.leaf.pem X.509 certificate.
- * @param {string}
- * chain.leaf.keyType keyType.
- * @param {string}
- * chain.leaf.subject subject.
- * @param {string}
- * chain.leaf.time time reference (Optional). Only mandatory if
- * the 'Time' validation is going to be performed.
- * @param {json}
- * chain.certificates chain of certificates.
- * @param {Array}
- * chain.certificates.pems list of X.509 Certificates as string
- * in pem format. The list starts by the one closer to the root.
- * @param {Array}
- * chain.certificates.subjects list of subjects
- * @param {Array}
- * chain.root X.509 trusted Certificate.
- * @returns {Array} a two dimension array where the first dimension is the
- * index of the element starting by 1 -leaf certificate - and the
- * second dimension holds the error types.
- */
- box.certificates.service.validateX509CertificateChain = function(chain) {
- var validateDateRange = function(certificate, failedValidation) {
- if (certificate.getNotBefore() > certificate.getNotAfter()) {
- failedValidation.push('VALIDITY_PERIOD');
- }
- };
- var validateNotBefore = function(
- notBefore, previousNotBefore, failedValidation) {
- if (notBefore < previousNotBefore) {
- failedValidation.push('NOT_BEFORE');
- }
- };
- var validateNotAfter = function(
- notAfter, previousNotAfter, failedValidation) {
- if (notAfter > previousNotAfter) {
- failedValidation.push('NOT_AFTER');
- }
- };
- var validateLeafCertificate = function(
- issuer, signature, previousNotBefore, previousNotAfter) {
- var validationData = {
- subject: chain.leaf.subject,
- issuer: issuer,
- keyType: chain.leaf.keyType,
- caCertificatePem: signature
- };
- if (chain.leaf.time) {
- validationData.time = chain.leaf.time;
- }
- var certificateValidator =
- new box.certificates.CryptoX509CertificateValidator(validationData);
- var failedValidations = certificateValidator.validate(chain.leaf.pem);
- var certificate =
- new box.certificates.CryptoX509Certificate(chain.leaf.pem);
- validateDateRange(certificate, failedValidations);
- validateNotBefore(
- certificate.getNotBefore(), previousNotBefore, failedValidations);
- validateNotAfter(
- certificate.getNotAfter(), previousNotAfter, failedValidations);
- return failedValidations;
- };
- var rootCertificate =
- new box.certificates.CryptoX509Certificate(chain.root);
- var issuer = {
- commonName: rootCertificate.getSubjectCN(),
- organization: rootCertificate.getSubjectOrg(),
- organizationUnit: rootCertificate.getSubjectOrgUnit(),
- country: rootCertificate.getSubjectCountry()
- };
- var signature = chain.root;
- var failedValidation = [];
- var previousNotBefore = rootCertificate.getNotBefore();
- var previousNotAfter = rootCertificate.getNotAfter();
- var certificateValidator;
- chain.certificates.pems.reverse();
- chain.certificates.subjects.reverse();
- for (var i = 0; i < chain.certificates.pems.length; i++) {
- var certificate = new box.certificates.CryptoX509Certificate(
- chain.certificates.pems[i]);
- var validationData = {
- subject: chain.certificates.subjects[i],
- issuer: issuer,
- keyType: 'CA',
- signature: signature
- };
- certificateValidator =
- new box.certificates.CryptoX509CertificateValidator(validationData);
- failedValidation[i] =
- certificateValidator.validate(chain.certificates.pems[i]);
- validateDateRange(certificate, failedValidation[i]);
- validateNotBefore(
- certificate.getNotBefore(), previousNotBefore, failedValidation[i]);
- validateNotAfter(
- certificate.getNotAfter(), previousNotAfter, failedValidation[i]);
- issuer = {
- commonName: certificate.getSubjectCN(),
- organization: certificate.getSubjectOrg(),
- organizationUnit: certificate.getSubjectOrgUnit(),
- country: certificate.getSubjectCountry()
- };
- signature = chain.certificates.pems[i];
- previousNotBefore = certificate.getNotBefore();
- previousNotAfter = certificate.getNotAfter();
- }
- failedValidation.push(validateLeafCertificate(
- issuer, signature, previousNotBefore, previousNotAfter));
- failedValidation.reverse();
- return failedValidation;
- };
- /**
- * Flattens failed validations to a one dimensional array to a one
- * dimensional array.
- *
- * @function
- * @param {array}
- * failedValidations a two-dimensional failed validations array.
- * @returns {array} a flat array in which each element contains the error
- * type message piped with the index of the element, i.e.
- * ERROR_<element index>.
- */
- box.certificates.service.flattenFailedValidations = function(
- failedValidations) {
- var flattenFailedValidations = Array();
- for (var i = 0; i < failedValidations.length; i++) {
- if (failedValidations[i] !== undefined) {
- for (var j = 0; j < failedValidations[i].length; j++) {
- flattenFailedValidations.push(
- failedValidations[i][j].toLowerCase() + '_' + (i));
- }
- }
- }
- return flattenFailedValidations;
- };
- };
- cryptolib.modules.certificates.service = cryptolib.modules.certificates;
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.commons = cryptolib.modules.commons || {};
- /**
- * Defines our exception wrapper.
- *
- * @param message.
- * The string to use in the error description.
- */
- cryptolib.modules.commons.exceptions = function(box) {
- 'use strict';
- box.commons = box.commons || {};
- box.commons.exceptions = {};
- box.commons.exceptions.CryptoLibException = function(
- customMessage, originalMessage) {
- this.customMessage = customMessage;
- this.originalMessage = originalMessage;
- };
- box.commons.exceptions.CryptoLibException.prototype = {
- /**
- * Returns the exception message.
- *
- * @return {string} The message.
- */
- toString: function() {
- var errorMessage = 'ERROR: ';
- if (typeof this.originalMessage !== 'undefined') {
- errorMessage += this.customMessage +
- '. Original Error Message: ' + this.originalMessage;
- } else {
- errorMessage += this.customMessage;
- }
- return errorMessage;
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.commons = cryptolib.modules.commons || {};
- /**
- * @namespace commons/mathematical
- */
- cryptolib.modules.commons.mathematical = function(box) {
- 'use strict';
- box.commons = box.commons || {};
- /**
- * A module the defines mathematical groups, elements, and operations that
- * can be performed
- *
- * @exports commons/mathematical
- */
- box.commons.mathematical = {};
- var BigInteger = box.forge.jsbn.BigInteger;
- var exceptions;
- var converters;
- cryptolib('commons.exceptions', 'commons.utils', function(box) {
- exceptions = box.commons.exceptions;
- converters = new box.commons.utils.Converters();
- });
- /**
- * Given p and Zp representing 'Integers (mod p)' group, a Zp subgroup is a
- * group where the elements are a subset of elements from Zp.
- *
- * The order of the subgroup is q, that is the number of elements. Both Zp
- * and the ZpSubgroup are finite cyclic groups, it means that all elements
- * can be generated exponentiating a special group element called generator.
- *
- * When the p and q are related with the restriction p = 2q + 1 the subgroup
- * is also defined as 'Quadratic Residue'.
- *
- * @class
- * @param valueG
- * {forge.jsbn.BigInteger} The generator of the subgroup, as a
- * BigInteger. This value must be a group element different from
- * one.
- * @param valueP
- * {forge.jsbn.BigInteger} The modulus, as a BigInteger.
- * @param valueQ
- * {forge.jsbn.BigInteger} The order of the subgroup, as a
- * BigInteger.
- *
- * @throws CryptoLibException
- * if 0 < q < p restriction is not accomplished
- * @throws CryptoLibException
- * if subgroup generator is nor between 2 and p-1
- *
- */
- box.commons.mathematical.ZpSubgroup = function(valueG, valueP, valueQ) {
- if ((typeof valueG === 'undefined') || (typeof valueP === 'undefined') ||
- (typeof valueQ === 'undefined')) {
- throw new exceptions.CryptoLibException(
- 'The given parameters should be initialized');
- }
- if ((BigInteger.ONE.compareTo(valueG) >= 0) ||
- (valueP.compareTo(valueG) <= 0)) {
- throw new exceptions.CryptoLibException(
- 'The generator should be between 2 and p-1');
- }
- if ((BigInteger.ZERO.compareTo(valueQ) >= 0) ||
- (valueP.compareTo(valueQ) <= 0)) {
- throw new exceptions.CryptoLibException(
- 'The relationship between the values of the p and q parameters should be such that 0 < q < p');
- }
- var _p = valueP;
- var _q = valueQ;
- var generator = new box.commons.mathematical.ZpGroupElement(valueG, _p, _q);
- var identity =
- new box.commons.mathematical.ZpGroupElement(BigInteger.ONE, _p, _q);
- /**
- * @function
- * @returns the identity element of the group.
- */
- this.getIdentity = function() {
- return identity;
- };
- /**
- * @function
- * @returns the q parameter (the order of the group).
- */
- this.getQ = function() {
- return _q;
- };
- /**
- * @function
- * @returns the p parameter (the modulus of the group).
- */
- this.getP = function() {
- return _p;
- };
- /**
- * @function
- * @returns {box.commons.mathematical.ZpGroupElement} the generator
- * element of the group.
- */
- this.getGenerator = function() {
- return generator;
- };
- };
- box.commons.mathematical.ZpSubgroup.prototype = {
- /**
- * Checks whether a given element is a member of this MathematicalGroup.
- *
- * An element is a member of the group if:
- * <ul>
- * <li><code>element</code> has an integer value between
- * <code>1</code> and <code>p-1</code>:
- * <code>(0 < element < p)</code></li>
- * <li><code>element<sup>q</sup> mod p = 1</code></li>
- * </ul>
- *
- * @function
- * @param element
- * {ZpGroupElement} the element whose group membership should
- * be checked.
- * @returns true if the given element is member of the group, otherwise
- * false.
- */
- isGroupMember: function(element) {
- if (typeof element !== 'undefined' &&
- element.getP().equals(this.getP())) {
- var modPow = element.getElementValue().modPow(this.getQ(), this.getP());
- return BigInteger.ONE.equals(modPow);
- } else {
- return false;
- }
- },
- /**
- * Check if this group is equal to the received group.
- *
- * @function
- * @param group
- * {ZpSubgroup} the group which should be checked against
- * this group for equality.
- * @returns true if the given group has the same <code>q</code>, the
- * same <code>p</code>, and the same <code>generator</code>.
- */
- equals: function(group) {
- if (typeof group !== 'undefined' &&
- group.getGenerator().equals(this.getGenerator()) &&
- group.getQ().equals(this.getQ()) &&
- group.getP().equals(this.getP())) {
- return true;
- } else {
- return false;
- }
- },
- /**
- * Check if this group is a quadratic residue group, which is defined
- * such that p = 2q + 1.
- *
- * @function
- * @returns true if the given group is a quadratic residue group.
- */
- isQuadraticResidueGroup: function() {
- return this.getP().equals(
- new BigInteger('2').multiply(this.getQ()).add(BigInteger.ONE));
- },
- /**
- * Displays a string representation of this mathematical group JSON.
- * <p>
- * Note: in order to permit interoperability between libraries, this
- * representation should match the equivalent representation in Java.
- *
- * @function
- * @returns a string representation of this mathematical group JSON.
- */
- stringify: function() {
- return JSON.stringify({
- zpSubgroup: {
- p: converters.base64FromBigInteger(this.getP()),
- q: converters.base64FromBigInteger(this.getQ()),
- g: converters.base64FromBigInteger(
- this.getGenerator().getElementValue())
- }
- });
- }
- };
- /**
- * Class representing elements of a Zp group.
- *
- * <p>
- * Note: This constructor does not check whether the given value is a valid
- * member of the subgroup. To check subgroup membership the function
- * <code>zpSubgroup.isGroupMember(groupElement)</code> can be called,
- * however this is a computationally expensive operation.
- *
- * @class
- * @param value
- * {forge.jsbn.BigInteger} Value of the element (not null). The
- * value must be between <code>[1..p-1]</code>
- * @param groupP
- * {forge.jsbn.BigInteger} The p parameter, as a BigInteger.
- * @param groupQ
- * {forge.jsbn.BigInteger} The q parameter, as a BigInteger.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- box.commons.mathematical.ZpGroupElement = function(value, groupP, groupQ) {
- if ((typeof value === 'undefined')) {
- throw new exceptions.CryptoLibException(
- 'The received value is not the expected object');
- }
- if ((BigInteger.ZERO.compareTo(value) >= 0) ||
- (groupP.compareTo(value) <= 0)) {
- throw new exceptions.CryptoLibException(
- 'The value of the element should be between 1 and p-1. P: ' + groupP +
- ', value: ' + value);
- }
- if ((BigInteger.ZERO.compareTo(groupQ) >= 0) ||
- (groupP.compareTo(groupQ) <= 0)) {
- throw new exceptions.CryptoLibException(
- 'The relationship between the values of the p and q parameters should hold that 0 < q < p');
- }
- var v = value;
- var p = groupP;
- var q = groupQ;
- /**
- * Performs a basic check to verify if this element belongs to the same
- * group as <code>element</code> by checking if the p and q parameters
- * of both are equal.
- * <p>
- * Note: this function does NOT perform the mathematical operation
- * needed to actually confirm that a value is an element of a group,
- * which involves modular exponentiation and is very computationally
- * costly. Instead, this function simply examines the p and q parameters
- * that are stored within both elements.
- *
- * @function
- * @param element
- * {ZpGroupElement} element to by multiplied with this
- * element.
- * @throws CryptoLibException
- * if the p and q parameters of the group that the received
- * element belongs to are not equal to the p and q
- * parameters of this element.
- */
- this._validateReceivedElementIsFromSameGroup = function(element) {
- if (typeof element === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The received value is not the expected object');
- }
- if ((!this.getP().equals(element.getP())) ||
- (!this.getQ().equals(element.getQ()))) {
- throw new exceptions.CryptoLibException(
- 'Operations can only be performed on group elements which are members of the same Zp subgroup');
- }
- };
- /**
- * Performs a basic check to verify if this element belongs to the same
- * group as <code>exponent</code> by checking if the p and q
- * parameters of both are equal.
- * <p>
- * Note: this function does NOT perform the mathematical operation
- * needed to actually confirm that an exponent belongs to a particular
- * group, which would involve confirming the following:
- * <p>
- * <code>0 >= exponent value <= p-1</code>
- *
- * @function
- * @param exponent
- * {Exponent} element to by multiplied with this element.
- * @throws CryptoLibException
- * if p and q parameters of the group that the received
- * element belongs to are not equal to the p and q
- * parameters of this element.
- */
- this._validateReceivedExponent = function(exponent) {
- if (typeof exponent === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The received value is not the expected object');
- }
- if (!this.getQ().equals(exponent.getQ())) {
- throw new exceptions.CryptoLibException(
- 'The exponent should have the same q as this Zp group element');
- }
- };
- /**
- * @function
- * @returns The value of this element.
- */
- this.getElementValue = function() {
- return v;
- };
- /**
- * @function
- * @returns The p parameter of the mathematical group to which this
- * element belongs.
- */
- this.getP = function() {
- return p;
- };
- /**
- * @function
- * @returns The q parameter of the mathematical group to which this
- * element belongs.
- */
- this.getQ = function() {
- return q;
- };
- };
- box.commons.mathematical.ZpGroupElement.prototype = {
- /**
- * Multiple this element by the received element. The operation is
- * performed mod p. Performs a basic check to confirm that this element
- * and the received element belong to the same group.
- *
- * @function
- * @param element
- * {ZpGroupElement} element to by multiplied with this
- * element.
- * @returns <code>(this * element) mod p</code>, as a ZpGroupElement.
- * @throws CryptoLibException
- * if the p and q parameters of the group that the received
- * element belongs to are not equal to the p and q
- * parameters of this element.
- */
- multiply: function(element) {
- this._validateReceivedElementIsFromSameGroup(element);
- var result = this.getElementValue()
- .multiply(element.getElementValue())
- .mod(this.getP());
- return new box.commons.mathematical.ZpGroupElement(
- result, this.getP(), this.getQ());
- },
- /**
- * Exponentiate this element to the received exponent.
- *
- * @function
- * @param exponent
- * {Exponent} the exponent used to raise the value of the
- * group element.
- * @returns <code>(this<sup>exponent</sup>) mod p</code>, as a
- * ZpGroupElement.
- * @throws CryptoLibException
- * if the p and q parameters of the group that the received
- * exponent belongs to are not equal to the p and q
- * parameters of this element.
- */
- exponentiate: function(exponent) {
- this._validateReceivedExponent(exponent);
- var result =
- this.getElementValue().modPow(exponent.getValue(), this.getP());
- return new box.commons.mathematical.ZpGroupElement(
- result, this.getP(), this.getQ());
- },
- /**
- * Get the inverse of this element, mod p.
- *
- * @function
- * @returns the inverse of this element mod p, as a ZpGroupElement.
- */
- invert: function() {
- var result = this.getElementValue().modInverse(this.getP());
- return new box.commons.mathematical.ZpGroupElement(
- result, this.getP(), this.getQ());
- },
- /**
- * Check if this element is equal to the received element.
- * <p>
- * Elements are considered equal if:
- * <ul>
- * <li>They have the same value.</li>
- * <li>They belong to the same group (which is confirmed here by
- * checking if their p and q parameters are equal).</li>
- * </ul>
- *
- * @function
- * @param element
- * {ZpGroupElement} the element which should be checked
- * against this element for equality.
- * @returns true if the given group element has the same <code>v</code>,
- * the same <code>p</code> and the same <code>q</code>.
- */
- equals: function(element) {
- if (typeof element !== 'undefined' &&
- element.getElementValue().equals(this.getElementValue()) &&
- element.getP().equals(this.getP()) &&
- element.getQ().equals(this.getQ())) {
- return true;
- } else {
- return false;
- }
- },
- /**
- * Displays a string representation of this Zp group element JSON.
- * <p>
- * Note: in order to permit interoperability between libraries, this
- * representation should match the equivalent representation in Java.
- *
- * @function
- * @returns a string representation of Zp group element JSON.
- */
- stringify: function() {
- return JSON.stringify({
- zpGroupElement: {
- p: converters.base64FromBigInteger(this.getP()),
- q: converters.base64FromBigInteger(this.getQ()),
- value: converters.base64FromBigInteger(this.getElementValue())
- }
- });
- }
- };
- /**
- * Represents an exponent for a particular mathematical group.
- * <p>
- * The value of an exponent must be within the range [0..q-1]. If the
- * received value is not within this range, then the value that will be
- * assigned to the created Exponent will be calculated as follows:
- * <p>
- * <code>value = value mod q</code>
- *
- * @class
- *
- * @param q
- * {forge.jsbn.BigInteger} the order of the mathematical group
- * for which this is an exponent.
- * @param exponentValue
- * {forge.jsbn.BigInteger} the value of the exponent.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- box.commons.mathematical.Exponent = function(valueQ, exponentValue) {
- if (valueQ === 'undefined' || valueQ.compareTo(BigInteger.ZERO) === 0) {
- throw new exceptions.CryptoLibException(
- 'Q (the order of the group) cannot be null or zero');
- }
- var _q = valueQ;
- /**
- * Gets the value to set for this Exponent. This value has to be a
- * number between <code>0</code> and <code>q-1</code> (inclusive),
- * so if it is less than <code>0</code> or greater than
- * <code>q-1</code>, then <code>mod q</code> has to be applied.
- *
- * @function
- * @param {forge.jsbn.BigInteger}
- * exponentValue the value of the exponent.
- * @returns the value to set to this exponent.
- */
- function getExponent(exponentValue) {
- if ((_q.compareTo(exponentValue) > 0) &&
- (BigInteger.ZERO.compareTo(exponentValue) <= 0)) {
- return exponentValue;
- } else {
- return exponentValue.mod(_q);
- }
- }
- var _value = getExponent(exponentValue);
- /**
- * Checks if this exponent and the received exponent belong to the same
- * group.
- *
- * @function
- * @param exponent
- * {Exponent} the exponent which should be checked to see if
- * it belongs to the same group as this exponent.
- * @throws CryptoLibException
- * if the received exponent is undefined or does not belong
- * to the same group as this exponent.
- */
- this._confirmSameGroup = function(exponent) {
- if (typeof exponent === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The received exponent is not the expected object');
- }
- if (!_q.equals(exponent.getQ())) {
- throw new exceptions.CryptoLibException(
- 'Operations may only be performed with exponents of the same mathematical group order');
- }
- };
- /**
- * @function
- * @returns The numeric value of the exponent.
- */
- this.getValue = function() {
- return _value;
- };
- /**
- * @function
- * @returns The numeric value of the exponent.
- */
- this.getQ = function() {
- return _q;
- };
- };
- box.commons.mathematical.Exponent.prototype = {
- /**
- * Returns an Exponent whose value is:
- * <p>
- * <code>(this + exponent) mod q</code>
- *
- * @param exponent
- * {Exponent} the exponent to be added to this exponent.
- * @returns <code>(this + exponent) mod q</code>
- */
- add: function(exponent) {
- this._confirmSameGroup(exponent);
- var result = this.getValue().add(exponent.getValue()).mod(this.getQ());
- return new box.commons.mathematical.Exponent(this.getQ(), result);
- },
- /**
- * Returns an Exponent whose value is:
- * <p>
- * <code>(this - exponent) mod q</code>
- *
- * @param exponent
- * {Exponent} the exponent to be subtracted from this
- * exponent.
- * @returns <code>(this - exponent) mod q</code>
- */
- subtract: function(exponent) {
- this._confirmSameGroup(exponent);
- var result =
- this.getValue().subtract(exponent.getValue()).mod(this.getQ());
- return new box.commons.mathematical.Exponent(this.getQ(), result);
- },
- /**
- * Returns an Exponent whose value is:
- * <p>
- * <code>(this * exponent) mod q</code>
- *
- * @param exponent
- * {Exponent} the exponent to be multiplied with this
- * exponent.
- * @returns <code>(this * exponent) mod q</code>
- */
- multiply: function(exponent) {
- this._confirmSameGroup(exponent);
- var result =
- this.getValue().multiply(exponent.getValue()).mod(this.getQ());
- return new box.commons.mathematical.Exponent(this.getQ(), result);
- },
- /**
- * Returns an Exponent whose value is <code>(-this) mod q</code>
- *
- * @returns <code>(-this mod q)</code>
- */
- negate: function() {
- return new box.commons.mathematical.Exponent(
- this.getQ(), this.getValue().negate().mod(this.getQ()));
- },
- /**
- * Check if this exponent is equal to the received exponent.
- * <p>
- * Elements are considered equal if:
- * <ul>
- * <li>They have the same value.</li>
- * <li>They belong to the groups with the same order.</li>
- * </ul>
- *
- * @param {Exponent}
- * exponent the exponent to be checked against this exponent
- * for equality.
- * @returns true if the given exponent has the same <code>value</code>
- * and belongs to the same <code>group</code> as this
- * exponent.
- */
- equals: function(exponent) {
- if (exponent.getValue().equals(this.getValue()) &&
- exponent.getQ().equals(this.getQ())) {
- return true;
- } else {
- return false;
- }
- },
- /**
- * Displays a string representation of the exponent JSON.
- * <p>
- * Note: in order to permit interoperability between libraries, this
- * representation should match the equivalent representation in Java.
- *
- * @function
- * @returns a string representation of the exponent JSON.
- */
- stringify: function() {
- return JSON.stringify({
- exponent: {
- q: converters.base64FromBigInteger(this.getQ()),
- value: converters.base64FromBigInteger(this.getValue())
- }
- });
- }
- };
- /**
- * Provides utility functionality for working with mathematical groups.
- *
- * @class groupUtils
- * @memberof commons/mathematical
- */
- box.commons.mathematical.groupUtils = (function() {
- /**
- * Deserializes a Zp Subgroup string representation to a ZpSubgroup
- * object.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param groupJson
- * {JSON} a JSON representation of a Zp subgroup.
- * @returns a new ZpSubgroup, created from the received string.
- */
- function deserializeGroup(groupJson) {
- var parsed = JSON.parse(groupJson);
- var p = converters.base64ToBigInteger(parsed.zpSubgroup.p);
- var q = converters.base64ToBigInteger(parsed.zpSubgroup.q);
- var g = converters.base64ToBigInteger(parsed.zpSubgroup.g);
- return new box.commons.mathematical.ZpSubgroup(g, p, q);
- }
- /**
- * Deserializes a Zp Subgroup element string to a ZpGroupElement object.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param groupElementJson
- * {JSON} a JSON representation of a Zp Subgroup element
- * element.
- * @returns a new ZpGroupElement, created from the received string.
- */
- function deserializeGroupElement(groupElementJson) {
- var parsed = JSON.parse(groupElementJson);
- var value = converters.base64ToBigInteger(parsed.zpGroupElement.value);
- var p = converters.base64ToBigInteger(parsed.zpGroupElement.p);
- var q = converters.base64ToBigInteger(parsed.zpGroupElement.q);
- return new box.commons.mathematical.ZpGroupElement(value, p, q);
- }
- /**
- * Deserializes an exponent string to an Exponent object.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param exponentJson
- * {JSON} a JSON representation of an exponent.
- * @returns a new Exponent, created from the received string.
- */
- function deserializeExponent(exponentJson) {
- var parsed = JSON.parse(exponentJson);
- var q = converters.base64ToBigInteger(parsed.exponent.q);
- var value = converters.base64ToBigInteger(parsed.exponent.value);
- return new box.commons.mathematical.Exponent(q, value);
- }
- /**
- * Compress a list of group elements.
- * <P>
- * Note: an exception will be thrown if an array is received which
- * contains any elements that are not elements of the mathematical
- * group.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group.
- * @param elementsToBeCompressedArray
- * {object} the array of group elements to be compressed.
- * @returns the result of the compression process, as a group element.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function compressGroupElements(group, elementsToBeCompressedArray) {
- validateArray(elementsToBeCompressedArray);
- validateGroup(group);
- var elem = elementsToBeCompressedArray[0];
- for (var i = 1; i < elementsToBeCompressedArray.length; i++) {
- elem = elem.multiply(elementsToBeCompressedArray[i]);
- }
- return elem;
- }
- /**
- * Compress a list of exponents.
- * <P>
- * Note: an exception will be thrown if an array is received which
- * contains any exponents that are not exponents of the mathematical
- * group.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group
- * @param exponentsToBeCompressedArray
- * {object} the array of exponents to be compressed
- * @returns the result of the compression process, as an exponent.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function compressExponents(group, exponentsToBeCompressedArray) {
- validateArray(exponentsToBeCompressedArray);
- validateGroup(group);
- validateExponents(group.getQ(), exponentsToBeCompressedArray);
- var elem = exponentsToBeCompressedArray[0];
- for (var i = 1; i < exponentsToBeCompressedArray.length; i++) {
- elem = elem.add(exponentsToBeCompressedArray[i]);
- }
- return elem;
- }
- /**
- * Builds a new array of elements from the input array, where the final
- * elements from the input array are compressed into a simple element.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group that this compressor
- * operates on.
- * @param inputArray
- * {object} the input array of group elements.
- * @param numElementsRequiredInNewList
- * {number} the number of elements that should be in the
- * output array.
- * @returns a new array of group elements.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function buildListWithCompressedFinalElement(
- group, inputArray, numElementsRequiredInNewList) {
- validateArray(inputArray);
- validateGroup(group);
- if (numElementsRequiredInNewList < 1) {
- throw new exceptions.CryptoLibException(
- 'The number of elements in the output list must be at least 1');
- }
- var offset = numElementsRequiredInNewList - 1;
- var outputArray = inputArray.slice(0, offset);
- var lastElement = compressGroupElements(
- group, inputArray.slice(offset, inputArray.length));
- outputArray.push(lastElement);
- return outputArray;
- }
- /**
- * Builds a new array of exponents from the input array, where the final
- * exponents from the input array are compressed into a simple
- * exponents.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group that this compressor
- * operates on.
- * @param inputArray
- * {object} the input array of exponents.
- * @param numExponentsRequiredInNewList
- * {number} the number of exponents that should be in the
- * output array.
- * @returns a new array of group elements.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function buildListWithCompressedFinalExponent(
- group, inputArray, numExponentsRequiredInNewList) {
- validateArray(inputArray);
- validateGroup(group);
- if (numExponentsRequiredInNewList < 1) {
- throw new exceptions.CryptoLibException(
- 'The number of exponents in the output list must be at least 1');
- }
- var offset = numExponentsRequiredInNewList - 1;
- var outputArray = inputArray.slice(0, offset);
- var lastExponent =
- compressExponents(group, inputArray.slice(offset, inputArray.length));
- outputArray.push(lastExponent);
- return outputArray;
- }
- /**
- * Given two arrays of group elements, this method produces a new list
- * of group elements that represents the two input lists combined.
- * <P>
- * The two arrays must only contain values that are elements of the
- * mathematical group that this divider operates on. If either array
- * contains any element that is not a group element then an exception
- * will be thrown.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param arrayElements1
- * {object} an input array of Zp group elements.
- * @param arrayElements2
- * {object} an input array of Zp group elements.
- * @returns a new list of group elements.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function divide(arrayElements1, arrayElements2) {
- validateArray(arrayElements1);
- validateArray(arrayElements2);
- if (arrayElements1.length !== arrayElements2.length) {
- throw new exceptions.CryptoLibException(
- 'Both arrays should have the same length');
- }
- var newList = [];
- var newElement;
- for (var i = 0; i < arrayElements1.length; i++) {
- newElement = arrayElements1[i].multiply(arrayElements2[i].invert());
- newList.push(newElement);
- }
- return newList;
- }
- /**
- * Given an array of group elements and one exponent, this method
- * produces a new list of group elements that represents the
- * exponentiation of the group elements to the exponent.
- * <P>
- * The array must contain values that are elements of the mathematical
- * group that this exponentiation activity operates on. If the array
- * contains any element that is not a group element then an exception
- * will be thrown.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param {array} arrayElements
- * an input array of Zp group elements.
- * @param {object} exponent
- * An Exponent.
- * @param {object} group
- * The mathematical group that all of the elements in
- * arrayElements belong to.
- * @param {boolean} validateElements An Exponent.
- * @return A new list of group elements.
- *
- */
- function exponentiateArrays(
- arrayElements, exponent, group, validateElements) {
- validateArray(arrayElements);
- validateExponent(exponent);
- validateGroup(group);
- // If requested, validate all elements prior to any operations.
- if (typeof validateElements !== 'undefined' && validateElements) {
- for (var j = 0; j < arrayElements.length; j++) {
- if (!group.isGroupMember(arrayElements[j])) {
- throw new exceptions.CryptoLibException(
- 'The element does not belong to the group');
- }
- }
- }
- var newList = [];
- var newElement;
- for (var i = 0; i < arrayElements.length; i++) {
- newElement = arrayElements[i].exponentiate(exponent);
- newList.push(newElement);
- }
- return newList;
- }
- /**
- * Returns a new random exponent for the received mathematical group.
- * <P>
- * The value of the created exponent will be between <code>0</code>
- * and q-1.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group.
- * @param cryptoRandomInteger
- * {CryptoScytlRandomInteger} the source of randomness.
- * @param {boolean}
- * useShortExponent true if a short exponent is to be
- * generated. Default value is false.
- * @returns a new random exponent.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function generateRandomExponent(
- group, cryptoRandomInteger, useShortExponent) {
- validateGroup(group);
- if (typeof cryptoRandomInteger === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The given parameters should be initialized');
- }
- var _useShortExponent = true;
- if (!useShortExponent) {
- _useShortExponent = false;
- }
- var q = group.getQ();
- var qBitLength = q.bitLength();
- var randomExponentLength;
- if (_useShortExponent) {
- if (qBitLength < box.SHORT_EXPONENT_BIT_LENGTH) {
- throw new exceptions.CryptoLibException(
- 'Zp subgroup order bit length must be greater than or equal to short exponent bit length : ' +
- box.SHORT_EXPONENT_BIT_LENGTH + '; Found ' + qBitLength);
- }
- randomExponentLength = box.SHORT_EXPONENT_BIT_LENGTH;
- } else {
- randomExponentLength = qBitLength;
- }
- var randomExponentValue;
- var randomExponentFound = false;
- while (!randomExponentFound) {
- randomExponentValue =
- cryptoRandomInteger.nextRandomByBits(randomExponentLength);
- if (randomExponentValue.compareTo(q) < 0) {
- randomExponentFound = true;
- }
- }
- return new box.commons.mathematical.Exponent(q, randomExponentValue);
- }
- /**
- * Returns a group element symmetric key which is obtained by
- * exponentiating the generator of a given mathematical group to a
- * random exponent <code>k</code>.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param group
- * {ZpSubgroup} the mathematical group.
- * @param cryptoRandomInteger
- * {CryptoScytlRandomInteger} the source of randomness.
- * @returns the secret key, as a group element.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function generateGroupElementSecretKey(group, cryptoRandomInteger) {
- var exponent = generateRandomExponent(group, cryptoRandomInteger);
- var groupElementSecretKey = group.getGenerator().exponentiate(exponent);
- return groupElementSecretKey;
- }
- /**
- * Build a ZpSubgroup from the p and g parameters.
- * <P>
- * NOTE: This method builds a particular type of mathematical group with
- * property that:
- * <P>
- * P = (Q * 2) + 1
- * <P>
- * This property holds for all groups generated using this method, but
- * this property does not hold for all mathematical groups.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param p
- * {forge.jsbn.BigInteger} the p parameter of the group.
- * @param g
- * {forge.jsbn.BigInteger} the generator of the group.
- * @returns the generated ZpSubgroup.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function buildZpSubgroupFromPAndG(p, g) {
- validateBuildFromPAndGInputs(p, g);
- var q = p.subtract(BigInteger.ONE).divide(new BigInteger('2'));
- return new box.commons.mathematical.ZpSubgroup(g, p, q);
- }
- /**
- * Build a random ZpSubgroup whose p parameter will have the specified
- * bit length. The certainty that both p and q are both prime is
- * specified by certainty.
- * <P>
- * NOTE: This method builds a particular type of Zp subgroup with
- * property that:
- * <P>
- * p = (q * 2) + 1
- * <P>
- * This property holds for all mathematical groups generated using this
- * method, but this property does not hold for all mathematical groups.
- * <P>
- * Note: the minimum bit length of the p parameter that is permitted by
- * this method is 2. If a bit length less than 2 is requested then a
- * CryptoLibException will be thrown.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param bitLengthOfP
- * {number} the bit length that the p parameter of the
- * generated group should be.
- * @param cryptoRandomInteger
- * {CryptoScytlRandomInteger} an instance of
- * CryptoRandomInteger that can be used as a source of random
- * integers.
- * @param certainty
- * {number} the required level of certainty that the q
- * parameter of the generated group is prime.
- * @returns the generated ZpSubgroup.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function buildRandomZpSubgroupFromLengthOfP(
- bitLengthOfP, cryptoRandomBytes, certainty) {
- validateBuildFromLengthPInputs(
- bitLengthOfP, cryptoRandomBytes, certainty);
- var p, q;
- var twoBI = new BigInteger('2');
- var randomGroupFound = false;
- var options = {prng: cryptoRandomBytes};
- var callback = function(err, num) {
- if (err) {
- throw new exceptions.CryptoLibException(
- 'Error while generating prime ' + err);
- }
- p = num;
- q = num.subtract(BigInteger.ONE).divide(twoBI);
- };
- while (!randomGroupFound) {
- forge.prime.generateProbablePrime(bitLengthOfP, options, callback);
- if (q.isProbablePrime(certainty)) {
- randomGroupFound = true;
- }
- }
- var generator = findSmallestGenerator(p, q);
- return new box.commons.mathematical.ZpSubgroup(generator, p, q);
- }
- /**
- * Given an input array containing possible group members, this method
- * cycles through that array, checking if each element is a group
- * member. This method attempts to find the specified number of group
- * members. Once that number has been found, the method will return a
- * new array containing the specified number of group members.
- * <p>
- * If the required number of group members are not found in the input
- * array then a CryptoLibException will be thrown.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @param possibleGroupMembersArray
- * {object} an array containing possible group members.
- * @param group
- * {ZpSubgroup} the Zp subgroup for which the specified
- * number of group members are required.
- * @param numMembersRequired
- * {number} the number of group members of the specified
- * group that should be added to the output list.
- * @returns a new array containing the specified number of group
- * elements, which have been read from the input array.
- * @throws CryptoLibException
- * if there are any problems with the inputs.
- */
- function extractNumberOfGroupMembersFromListOfPossibleMembers(
- possibleGroupMembersArray, group, numMembersRequired) {
- validateExtractFromListInputs(
- possibleGroupMembersArray, group, numMembersRequired);
- var outputArray = [];
- var membersFound = 0;
- var candidate;
- for (var i = 0; i < possibleGroupMembersArray.length; i++) {
- candidate = new box.commons.mathematical.ZpGroupElement(
- possibleGroupMembersArray[i], group.getP(), group.getQ());
- if (group.isGroupMember(candidate)) {
- outputArray.push(candidate);
- membersFound++;
- }
- if (membersFound === numMembersRequired) {
- return outputArray;
- }
- }
- if (membersFound !== numMembersRequired) {
- throw new exceptions.CryptoLibException(
- 'Error - did not find the required number of group members in the given list. The required number of was ' +
- numMembersRequired + ', number of members found was ' +
- membersFound);
- }
- }
- /**
- * Find the smallest generator of a mathematical group.
- * <p>
- * Note: starts with a candidate generator value (two is the initial
- * candidate generator value), and checks if the candidate generator is
- * a group memeber. If that candidate is a group memeber then return
- * that value, else increment the candidate by one and again check if
- * the candidate is a group member. Continue this process until the
- * candidate value is less than the parameter p.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params p {number} the p parameter of the group.
- * @params q {number} the q parameter of the group.
- * @throws CryptoLibException
- */
- function findSmallestGenerator(p, q) {
- var g = new BigInteger('2');
- var generatorFound = false;
- while ((!generatorFound) && (g.compareTo(p) < 0)) {
- if (g.modPow(q, p).equals(BigInteger.ONE)) {
- generatorFound = true;
- } else {
- g = g.add(BigInteger.ONE);
- }
- }
- if (!generatorFound) {
- throw new exceptions.CryptoLibException(
- 'Failed to find a generator, p was: ' + p + ', q was: ' + q);
- }
- return g;
- }
- /**
- * Validates a group.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params group {ZpSubgroup} the group to be validated.
- * @throws CryptoLibException
- * if the received group is undefined.
- */
- function validateGroup(group) {
- if (typeof group === 'undefined' || null === group) {
- throw new exceptions.CryptoLibException(
- 'The given group should be initialized');
- }
- }
- function validateExponent(exponent) {
- if (typeof exponent === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The given exponent should be initialized');
- }
- }
- /**
- * Validates that an array is initialized and non-empty.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params inputArray {object} an array to be validated.
- * @throws CryptoLibException
- * if the received array is not initialized or is empty.
- */
- function validateArray(inputArray) {
- if (typeof inputArray === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The given array should be initialized');
- }
- if (!(inputArray instanceof Array)) {
- throw new exceptions.CryptoLibException(
- 'The given array are not from the expected type');
- }
- if (inputArray.length < 1) {
- throw new exceptions.CryptoLibException(
- 'The given array cannot be empty');
- }
- }
- /**
- * Performs a very basic validation on the received inputs.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params p {object} the first parameter.
- * @params g {object} the second parameter.
- * @throws CryptoLibException
- * if either (or both) inputs are undefined.
- */
- function validateBuildFromPAndGInputs(p, g) {
- if ((typeof p === 'undefined') || (typeof g === 'undefined')) {
- throw new exceptions.CryptoLibException('p or g are incorrect');
- }
- }
- /**
- * Performs a some basic validations on the received inputs.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params bitLengthOfP {number} bit length of p parameter.
- * @params cryptoRandomBytes {CryptoScytlRandomBytes} a secure source of
- * random bytes.
- * @params certainty {number} a certainty level.
- * @throws CryptoLibException
- * if any of the inputs fail any of the validations.
- */
- function validateBuildFromLengthPInputs(
- bitLengthOfP, cryptoRandomBytes, certainty) {
- if (bitLengthOfP < 2) {
- throw new exceptions.CryptoLibException(
- 'The bit length should be higher');
- }
- if (typeof cryptoRandomBytes === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The random generator should be initialized');
- }
- if (certainty < box.MINIMUM_PRIME_CERTAINTY_LEVEL) {
- throw new exceptions.CryptoLibException('Certainty should be higher');
- }
- }
- /**
- * Performs some basic validations on the received inputs.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params inputArray {object} an array.
- * @params group {ZpSubgroup} a Zp subgroup.
- * @params numMembersRequired {number} an integer value.
- * @throws CryptoLibException
- * if any of the inputs fail any of the validations.
- */
- function validateExtractFromListInputs(
- inputArray, group, numMembersRequired) {
- validateArray(inputArray);
- validateGroup(group);
- if (typeof numMembersRequired === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The given objects should be initialized');
- }
- if (typeof numMembersRequired !== 'number') {
- throw new exceptions.CryptoLibException(
- 'The given objects are not from the expected type');
- }
- if (numMembersRequired < 1 || numMembersRequired > inputArray.length) {
- throw new exceptions.CryptoLibException(
- 'The given number of required elements cannot be higher than the number of elements of the array');
- }
- }
- /**
- * Validates that all of the exponents in the received list are
- * exponents are members of the received group, by checking if the
- * groups that they contain are equal.
- *
- * @function
- * @memberof commons/mathematical.groupUtils
- * @params group {ZpSubgroup} a Zp subgroup.
- * @params exponents {object} a list of exponents.
- */
- function validateExponents(q, exponents) {
- for (var i = 0; i < exponents.length; i++) {
- if (!exponents[i].getQ().equals(q)) {
- throw new exceptions.CryptoLibException(
- 'The list of exponents contained an exponent which does not belong to the group with the same order.');
- }
- }
- }
- return {
- buildZpSubgroupFromPAndG: buildZpSubgroupFromPAndG,
- buildRandomZpSubgroupFromLengthOfP: buildRandomZpSubgroupFromLengthOfP,
- extractNumberOfGroupMembersFromListOfPossibleMembers:
- extractNumberOfGroupMembersFromListOfPossibleMembers,
- generateRandomExponent: generateRandomExponent,
- generateGroupElementSecretKey: generateGroupElementSecretKey,
- compressGroupElements: compressGroupElements,
- buildListWithCompressedFinalElement: buildListWithCompressedFinalElement,
- deserializeGroup: deserializeGroup,
- deserializeGroupElement: deserializeGroupElement,
- deserializeExponent: deserializeExponent,
- compressExponents: compressExponents,
- buildListWithCompressedFinalExponent:
- buildListWithCompressedFinalExponent,
- divide: divide,
- exponentiateArrays: exponentiateArrays
- };
- })();
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.commons = cryptolib.modules.commons || {};
- /** namespace commons/utils */
- cryptolib.modules.commons.utils = function(box) {
- 'use strict';
- box.commons = box.commons || {};
- /**
- * A module that holds utility functionalities.
- *
- * @exports commons/utils
- */
- box.commons.utils = {};
- var exceptions;
- cryptolib('commons.exceptions', function(box) {
- exceptions = box.commons.exceptions;
- });
- /**
- * Defines some useful functions for data manipulation and type conversion.
- *
- * @class
- */
- box.commons.utils.Converters = function() {};
- box.commons.utils.Converters.prototype = {
- /**
- * Base64 encodes some data.
- *
- * @function
- * @param {string}
- * data data to Base64 encode.
- * @param {number}
- * lineLength line length of encoding (No line breaks if not
- * specified).
- * @returns {string} base64 encoded data.
- */
- base64Encode: function(data, lineLength) {
- if (lineLength === undefined || lineLength === null) {
- return forge.util.encode64(data);
- } else {
- return forge.util.encode64(data, lineLength);
- }
- },
- /**
- * Base64 decodes some data.
- *
- * @function
- * @param {string}
- * dataB64 data to Base64 decode.
- * @returns {string} base64 decoded data.
- */
- base64Decode: function(dataB64) {
- return forge.util.decode64(dataB64);
- },
- /**
- * Converts a string to a collection of bytes.
- *
- * @function
- * @param {string}
- * str string to convert to collection of bytes.
- * @returns collection of bytes from string.
- */
- bytesFromString: function(str) {
- var bytes = [];
- for (var i = 0; i < str.length; i++) {
- bytes.push(str.charCodeAt(i));
- }
- return bytes;
- },
- /**
- * Converts a collection of bytes to a string.
- *
- * @function
- * @param {string}
- * bytes collection of bytes to convert to string.
- * @return {string} string from collection of bytes.
- */
- bytesToString: function(bytes) {
- var string = '';
- for (var i = 0; i < bytes.length; i++) {
- string += String.fromCharCode(bytes[i]);
- }
- return string;
- },
- /**
- * Converts a string to a hexadecimal string.
- *
- * @function
- * @param {string}
- * str String to convert.
- * @returns string string in hexadecimal format.
- */
- hexFromString: function(str) {
- return forge.util.bytesToHex(str);
- },
- /**
- * Converts a hexadecimal string to a string.
- *
- * @function
- * @param {string}
- * hexStr hexadecimal string to convert.
- * @returns {string} String from conversion.
- */
- hexToString: function(hexStr) {
- return forge.util.hexToBytes(hexStr);
- },
- /**
- * Converts a BigInteger object to a base64 string.
- *
- * @function
- * @param {object}
- * bigInteger forge.jsbn.BigInteger to convert.
- * @returns {string} base64 string from conversion.
- */
- base64FromBigInteger: function(bigInteger) {
- var array = new Uint8Array(bigInteger.toByteArray());
- return box.forge.util.binary.base64.encode(array);
- },
- /**
- * Converts a base64 string to a BigInteger object.
- *
- * @function
- * @param {string}
- * base64Str base64 string to convert.
- * @returns {object} forge.jsbn.BigInteger from conversion.
- */
- base64ToBigInteger: function(base64Str) {
- var buffer = this.base64Decode(base64Str);
- var hex = this.hexFromString(buffer);
- return new forge.jsbn.BigInteger(hex, 16);
- }
- };
- /**
- * Defines a set of bit operator utilities.
- *
- * @class
- */
- box.commons.utils.BitOperators = function() {};
- box.commons.utils.BitOperators.prototype = {
- /**
- * Bit-wise concatenates some data to some existing data.
- *
- * @function
- * @param {string}
- * data1 existing data, as string.
- * @param {string}
- * data2 data to concatenate, as string.
- * @returns {string} bit-wise concatenation of data, as string.
- */
- concatenate: function(data1, data2) {
- try {
- var converters = new box.commons.utils.Converters();
- var data1Bytes = converters.bytesFromString(data1);
- var data2Bytes = converters.bytesFromString(data2);
- var concatDataBytes = data1Bytes.concat(data2Bytes);
- return converters.bytesToString(concatDataBytes);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Data could not be bit-wise concatenated.', error);
- }
- },
- /**
- * Unpacks a data subset from a bitwise concatenation of data.
- *
- * @function
- * @param {string}
- * concatData bit-wise concatenation of data, as string.
- * @param {number}
- * offset offset of data subset in concatenation.
- * @param {number}
- * size size of data subset.
- * @returns {string} data subset, as string.
- */
- extract: function(concatData, offset, size) {
- try {
- var converters = new box.commons.utils.Converters();
- var concatDataBytes = converters.bytesFromString(concatData);
- var dataSubsetBytes = concatDataBytes.slice(offset, size);
- return converters.bytesToString(dataSubsetBytes);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Data could not be bit-wise extracted.', error);
- }
- }
- };
- /**
- * Defines a set of time utilities.
- *
- * @class
- */
- box.commons.utils.TimeUtils = function() {};
- box.commons.utils.TimeUtils.prototype = {
- /**
- * Generates a time stamp in Unix time, i.e. the number of seconds that
- * have elapsed since 00:00:00 Coordinated Universal Time (UTC), 1
- * January 1970.
- *
- * @function
- * @returns {number} time stamp in seconds, as integer.
- */
- unixTimeStamp: function() {
- try {
- return Math.round(new Date().getTime() / 1000);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not generate Unix timestamp.', error);
- }
- },
- /**
- * Generates a time stamp in Unix time, i.e. the number of seconds that
- * have elapsed since 00:00:00 Coordinated Universal Time (UTC), 1
- * January 1970. The value is returned as a floating point number.
- *
- * @function
- * @returns {number} time stamp in seconds, as floating point number.
- */
- unixTimeStampFloat: function() {
- try {
- return new Date().getTime() / 1000;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not generate Unix timestamp.', error);
- }
- }
- };
- /**
- * Defines a set of xpath utilities.
- *
- * @class
- * @param {string}
- * path path in XPathForm notation Eg.
- * <form><name>test</name></form> to '/form/name'
- */
- box.commons.utils.XPath = function(xml, path) {
- this.path = path;
- this.node = xml;
- var pathTree = path ? path.split('/') : [];
- for (var i = 0; i < pathTree.length; i++) {
- if (pathTree[i] && this.node) {
- var found = false;
- for (var j = 0; j < this.node.childNodes.length; j++) {
- var child = this.node.childNodes[j];
- // we found the node
- if (child.nodeType === Node.ELEMENT_NODE &&
- child.tagName.toLowerCase() === pathTree[i].toLowerCase()) {
- this.node = child;
- found = true;
- break;
- }
- }
- // invalid xpath
- if (!found) {
- this.node = null;
- throw new exceptions.CryptoLibException('Invalid xpath for: ' + path);
- }
- }
- }
- };
- box.commons.utils.XPath.prototype = {
- /**
- * Gets the value of a node. For example <node>value</node> returns
- * value.
- *
- * @function
- * @returns {string} the value, as string.
- */
- getValue: function() {
- return this.node ? this.node.childNodes[0].nodeValue : '';
- },
- /**
- * Returns the value of an attribute of a node. For example <node
- * attr="attr value">node value</node> returns "attr value".
- *
- * @function
- * @param {object}
- * attribute attribute to get the value.
- * @returns attribute value, as string.
- */
- getAttribute: function(attribute) {
- return this.node ? this.node.getAttribute(attribute) : '';
- },
- /**
- * Gets the node itself-
- *
- * @function
- * @returns {object} xml document, as a DOM object.
- */
- getXml: function() {
- return this.node;
- },
- /**
- * Gets an array of child nodes
- *
- * @function
- * @returns {object} xml document array with all children as DOM
- * objects.
- */
- getChildren: function() {
- return this.node ? this.node.childNodes : '';
- }
- };
- /**
- * Defines a set of string utilities.
- *
- * @class
- */
- box.commons.utils.StringUtils = function() {
- };
- box.commons.utils.StringUtils.prototype = {
- /**
- * Check if a string is within another string
- *
- * @function
- * @param {string}
- * main text
- * @param {string}
- * substring substring to search in the main text
- * @param caseSensitive
- * boolean, case sensitive the search
- *
- * @returns {boolean} boolean, true if found
- */
- containsSubString: function(string, substring, caseSensitive) {
- var main = string, sub = substring;
- if (!caseSensitive) {
- main = main.toLowerCase();
- sub = sub.toLowerCase();
- }
- return main.indexOf(sub) > -1;
- }
- };
- /**
- * Defines a set of parser utilities.
- *
- * @class
- */
- box.commons.utils.Parsers = function() {};
- box.commons.utils.Parsers.prototype = {
- /**
- * Converts a string to an XML document.
- *
- * @function
- * @param {string}
- * str String to convert.
- * @returns {string} XML document, as string.
- */
- xmlFromString: function(str) {
- if (this.isIE()) {
- // Remove null terminating character if exists
- var strNoNull = this.removeNullTerminatingChar(str);
- var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM');
- xmlDoc.async = false;
- xmlDoc.loadXML(strNoNull);
- return xmlDoc;
- } else if (typeof window.DOMParser !== 'undefined') {
- return (new window.DOMParser()).parseFromString(str, 'text/xml');
- } else {
- throw new exceptions.CryptoLibException(
- 'XML string could not be parsed.');
- }
- },
- /**
- * Converts an XML document to a string.
- *
- * @fuction
- * @param {string}
- * xmlDoc xml document to convert, as string.
- * @param {boolean}
- * removeSelfClosingTags removes self closing tags to
- * explicit tags. Example: <tag/> to <tag></tag>
- * @returns {string} string from conversion.
- */
- xmlToString: function(xmlDoc, removeSelfClosingTags) {
- var result = this.xmlToStringIeCompatible(xmlDoc);
- if (removeSelfClosingTags) {
- result = this.xmlRemoveSelfClosingTags(result);
- }
- return result;
- },
- xmlRemoveSelfClosingTags: function(data) {
- var split = data.split('/>');
- var newXml = '';
- for (var i = 0; i < split.length - 1; i++) {
- var edsplit = split[i].split('<');
- newXml +=
- split[i] + '></' + edsplit[edsplit.length - 1].split(' ')[0] + '>';
- }
- return newXml + split[split.length - 1];
- },
- xmlToStringIeCompatible: function(xmlNode) {
- if (this.isIE()) {
- return xmlNode.xml;
- } else if (typeof window.XMLSerializer !== 'undefined') {
- return (new window.XMLSerializer()).serializeToString(xmlNode);
- } else {
- throw new exceptions.CryptoLibException(
- 'Error while tring to construct XML from String.');
- }
- },
- /**
- * Removes all newline characters from some data.
- *
- * @function
- * @param {string}
- * data data from which to remove all newline characters, as
- * string.
- * @returns {string} data with all newline characters removed, as
- * string.
- */
- removeNewLineChars: function(data) {
- return data.replace(/(\r\n|\n|\r)/gm, '');
- },
- /**
- * Removes all carriage return characters from some data.
- *
- * @param data
- * Data from which to remove all carriage return characters,
- * as string.
- * @return Data with all carriage return characters removed, as string.
- */
- removeCarriageReturnChars: function(data) {
- return data.replace(/(\r)/gm, '');
- },
- /**
- * Removes the null terminating character from some data.
- *
- * @function
- * @param {string}
- * data Data from which to remove the null terminating
- * character, as string.
- * @returns {string} data with null terminating character removed, as
- * string.
- */
- removeNullTerminatingChar: function(data) {
- return data.replace(/\x00+$/, '');
- },
- /**
- * Removes the XML header from a string representing an XML.
- *
- * @param data
- * The XML string from which to remove the XML header.
- * @return XML string with the XML header removed.
- */
- removeXmlHeaderFromString: function(data) {
- return data.replace('<?xml version="1.0" encoding="UTF-8"?>', '');
- },
- /**
- * Removes the signature node from a string representing an XML.
- *
- * @param data
- * The XML string from which to remove the signature node.
- * @return XML string with the signature node removed.
- */
- removeXmlSignature: function(data) {
- return data.replace(/<Signature[\s\S]*?Signature>/g, '');
- },
- /**
- * Detects if the client agent is Microsoft Internet Explorer. This has
- * been tested to work with Internet Explorer 9, 10 and 11. If this
- * software is to be used on other versions, then it should be checked
- * if those versions are supported by this function and if they are not
- * then this function should be updated.
- */
- isIE: function() {
- var ua = window.navigator.userAgent;
- var msie = ua.indexOf('MSIE ');
- if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
- return true;
- } else {
- return false;
- }
- }
- };
- /**
- * Defines a set of connectors.
- *
- * @class
- */
- box.commons.utils.Connectors = function() {};
- box.commons.utils.Connectors.prototype = {
- /**
- * Posts a request message to a destination via HTTP.
- *
- * @function
- * @param {string}
- * request request message to post, as string.
- * @param {string}
- * url url of request destination, as string.
- * @param {boolean}
- * isAsynch boolean indicating whether the post is
- * asynchronous.
- * @return {string} response retrieved from request destination, as
- * string.
- */
- postHttpRequestMessage: function(request, url, isAsynch) {
- // Check if a post destination was provided.
- if (url === '') {
- throw new exceptions.CryptoLibException(
- 'No URL provided for posting HTTP request.');
- }
- // Create HTTP request object.
- var httpRequest;
- var done;
- if (window.XMLHttpRequest) {
- httpRequest = new XMLHttpRequest();
- done = XMLHttpRequest.DONE;
- } else {
- throw new exceptions.CryptoLibException(
- 'Could not create HTTP request object for this browser.');
- }
- // Define post response message handling.
- var response;
- httpRequest.onreadystatechange = function() {
- if (httpRequest.readyState === done) {
- if (httpRequest.status === 200) {
- response = httpRequest.responseText;
- } else {
- var errorMsg =
- 'HTTP request message POST was not successful.\n Status: ' +
- httpRequest.status + ', Message: ' + httpRequest.statusText;
- throw new exceptions.CryptoLibException(errorMsg);
- }
- }
- };
- // Open HTTP request object for synchronous post.
- httpRequest.open('POST', url, isAsynch);
- // Post HTTP request message.
- try {
- httpRequest.send(request);
- } catch (error) {
- var errorMsg =
- 'Could not post HTTP request message; IP of web application might be incorrect.';
- throw new exceptions.CryptoLibException(errorMsg, error);
- }
- return response;
- }
- };
- /**
- * Defines a progress meter.
- *
- * @param {integer}
- * progressMax Maximum amount of progress to be attained.
- * @param {integer}
- * progressCallback Progress callback function.
- * @param {integer}
- * progressPercentMinCheckInterval Progress percentage minimum
- * check interval (optional) (default: 10%).
- * @class
- */
- box.commons.utils.ProgressMeter = function(
- progressMax, progressCallback, progressPercentMinCheckInterval) {
- this.progressMax = progressMax;
- this.progressCallback = progressCallback;
- this.progressPercentMinCheckInterval =
- progressPercentMinCheckInterval || 10;
- this.lastProgressPercent = 0;
- };
- box.commons.utils.ProgressMeter.prototype = {
- /**
- * Calculates the progress as a percentage of the total and provides it
- * as input to the provided callback function.
- *
- * @function
- * @param {integer}
- * progress Present amount of progress.
- */
- update: function(progress) {
- if (typeof this.progressCallback === 'undefined') {
- return;
- }
- var progressPercent = Math.floor((progress / this.progressMax) * 100);
- progressPercent = Math.min(progressPercent, 100);
- var progressPercentChange = progressPercent - this.lastProgressPercent;
- if (progressPercentChange > 0) {
- var checkProgress =
- (progressPercentChange >= this.progressPercentMinCheckInterval) ||
- (progressPercent === 100);
- if (checkProgress) {
- this.lastProgressPercent = progressPercent;
- this.progressCallback(progressPercent);
- }
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- var cryptoPRNG = (function() {
- 'use strict';
- return {
- _collectorsStarted: false,
- _collectors: [],
- _events: [],
- _entropy: '',
- _entropyCounter: 0,
- _maxEntropyCounter: 0,
- _collectorHashUpdater: null,
- _hashUpdaterInterval: 0,
- _fullEntropyCallback: null,
- _tools: null,
- _seedLength: 0,
- _prng: null,
- _privateKeyPem: '',
- _pinEntropy: 0,
- _usePrivateKeyEntropy: false,
- /**
- * Initializes all the round object fields.
- *
- * @function
- * @param hashUpdaterInterval
- * the interval, in millis, that the function that replaces the
- * current entropy content by an hash is called. By default it is
- * initialized to 5000.
- * @param maxEntropyCounter
- * number of maximum bits used to determine when the collectors
- * should stop collecting entropy. By default it is initialized
- * to 256.
- */
- _initAndStart: function(hashUpdaterInterval, fullEntropyCallback) {
- this._collectorsStarted = false;
- this._collectors = [];
- this._events = [];
- this._entropy = '';
- this._entropyCounter = 0;
- this._maxEntropyCounter = 256;
- this._collectorHashUpdater = null;
- this._hashUpdaterInterval =
- (hashUpdaterInterval ? hashUpdaterInterval : 1000);
- this._fullEntropyCallback = fullEntropyCallback;
- this._tools = cryptoPRNG.Tools.init();
- this._initCollectors();
- this._startCollectors();
- },
- /**
- * adds a new collector to the list of available connectors
- *
- * @param collector
- * must return an object that implements the startCollector and
- * stopCollector methods
- */
- _addCollector: function(collector) {
- this._collectors.push(collector);
- },
- /**
- * adds a new event to the list of available events
- *
- * @param type
- * event type
- * @param listener
- * function that will be executed
- */
- _addEvent: function(type, listener) {
- this._events.push({'type': type, 'listener': listener});
- },
- /**
- * Initializes the random generator with the web kit random collector if
- * available.
- *
- * If it is not, it considers the rest of collectors: ajax calls collector,
- * JS calls execution collector, navigator information collector, math
- * random collector, web kit random collector, mouse events collectors, key
- * events collectors, load event collector, scroll collector)
- */
- _initCollectors: function() {
- if (this._noWindow()) {
- this._addNonWindowEntropyCollectors();
- return;
- }
- var _crypto = this._getCrypto();
- if ((_crypto) && (_crypto.getRandomValues)) {
- this._addCollector(cryptoPRNG.Collectors.getWebKitRandomCollector(
- _crypto, this._maxEntropyCounter));
- } else {
- this._addNonWindowEntropyCollectors();
- // The API detects and delivers accelerometer data 50 times per
- // second
- if (window.DeviceOrientationEvent) {
- // Listen for the device orientation event and handle
- // DeviceOrientationEvent object
- this._addEvent(
- 'deviceorientation',
- cryptoPRNG.Collectors.getDeviceOrientationCollector);
- } else if (window.OrientationEvent) {
- // Listen for the MozOrientation event and handle
- // OrientationData object
- this._addEvent(
- 'MozOrientation',
- cryptoPRNG.Collectors.getDeviceOrientationCollector);
- }
- if (window.DeviceMotionEvent) {
- this._addEvent(
- 'devicemotion', cryptoPRNG.Collectors.getDeviceMotionCollector);
- }
- }
- },
- _addNonWindowEntropyCollectors: function() {
- if (this._usePrivateKeyEntropy) {
- this._addCollector(cryptoPRNG.Collectors.getPrivateKeyCollector(
- this._privateKeyPem, this._pinEntropy));
- }
- this._addCollector(cryptoPRNG.Collectors.getAjaxCollector());
- this._addCollector(cryptoPRNG.Collectors.getJSExecutionCollector());
- this._addCollector(cryptoPRNG.Collectors.getNavigatorInfoCollector());
- this._addCollector(cryptoPRNG.Collectors.getMathRandomCollector());
- // mouse events collectors
- this._addEvent('mousemove', cryptoPRNG.Collectors.getMouseMoveCollector);
- this._addEvent(
- 'mousewheel', cryptoPRNG.Collectors.getMouseWheelCollector);
- this._addEvent('mouseup', cryptoPRNG.Collectors.getMouseUpCollector);
- this._addEvent('mousedown', cryptoPRNG.Collectors.getMouseDownCollector);
- this._addEvent(
- 'touchstart', cryptoPRNG.Collectors.getTouchStartCollector);
- this._addEvent('touchmove', cryptoPRNG.Collectors.getTouchMoveCollector);
- this._addEvent('touchend', cryptoPRNG.Collectors.getTouchEndCollector);
- this._addEvent(
- 'gesturestart', cryptoPRNG.Collectors.getGestureStartCollector);
- this._addEvent(
- 'gestureend', cryptoPRNG.Collectors.getGestureEndCollector);
- // keyboard events collectors
- this._addEvent('keyup', cryptoPRNG.Collectors.getKeyUpCollector);
- this._addEvent('keydown', cryptoPRNG.Collectors.getKeyDownCollector);
- // page events collectors
- this._addEvent('load', cryptoPRNG.Collectors.getLoadCollector);
- this._addEvent('scroll', cryptoPRNG.Collectors.getScrollCollector);
- // requests collector collectors
- this._addEvent('beforeload', cryptoPRNG.Collectors.getRequestsCollector);
- },
- _getCrypto: function() {
- return window.crypto || window.msCrypto;
- },
- _noWindow: function() {
- return (typeof window === 'undefined');
- },
- /**
- * Start the collectors
- */
- _startCollectors: function() {
- if (this._collectorsStarted) {
- return;
- }
- var i = 0;
- // start all the collectors
- while (i < this._collectors.length) {
- try {
- this._collectors[i].startCollector();
- } catch (e) {
- // do not do anything about any exception that is thrown
- // by the execution of the collectors
- }
- i++;
- }
- i = 0;
- // start all the events
- while (i < this._events.length) {
- try {
- if (window.addEventListener) {
- window.addEventListener(
- this._events[i].type, this._events[i].listener, false);
- } else if (document.attachEvent) {
- document.attachEvent(
- 'on' + this._events[i].type, this._events[i].listener);
- }
- } catch (e) {
- // do not do anything about any exception that is thrown
- // by the execution of the events
- }
- i++;
- }
- this._tools._mdUpdate.start();
- this._collectorHashUpdater = setInterval(function() {
- cryptoPRNG._hashUpdater();
- }, this._hashUpdaterInterval);
- this._collectorsStarted = true;
- },
- /**
- * Stop the collectors
- */
- _stopCollectors: function() {
- if (!this._collectorsStarted) {
- return;
- }
- var i = 0;
- while (i < this._collectors.length) {
- try {
- this._collectors[i].stopCollector();
- } catch (e) {
- // do not do anything about any exception that is thrown
- // by the execution of the collectors
- }
- i++;
- }
- i = 0;
- while (i < this._events.length) {
- try {
- if (window.removeEventListener) {
- window.removeEventListener(
- this._events[i].type, this._events[i].listener, false);
- } else if (document.detachEvent) {
- document.detachEvent(
- 'on' + this._events[i].type, this._events[i].listener);
- }
- } catch (e) {
- // do not do anything about any exception that is thrown
- // by the remove of the events
- }
- i++;
- }
- if (this._collectorHashUpdater) {
- clearInterval(this._collectorHashUpdater);
- }
- this._collectorsStarted = false;
- },
- /**
- * Usually this method is called from the collectors and events. It adds
- * entropy to the already collected entropy and increments the entropy
- * counter
- *
- * @param data
- * the entropy data to be added
- * @param entropyCounter
- * the entropy counter to be added
- */
- _collectEntropy: function(data, entropyCounter) {
- this._entropy += data;
- this._entropyCounter += (entropyCounter ? entropyCounter : 0);
- // if the entropy counter has reach the limit, update the hash and stop
- // the collectors
- if (this._entropyCounter >= this._maxEntropyCounter &&
- this._collectorsStarted) {
- this._hashUpdater();
- }
- },
- /**
- * Sets the entropy data with the hash that is created using the current
- * entropy data value. If the entropy counter has reached the max entropy
- * counter set, it stops the collectors
- *
- * @return the generated entropy hash
- */
- _hashUpdater: function() {
- var entropyHash = this._updateEntropyHash();
- if (this._entropyCounter >= this._maxEntropyCounter &&
- this._collectorsStarted) {
- entropyHash = this._stopCollectEntropy();
- var newPRNG = new cryptoPRNG.PRNG(entropyHash, this._tools);
- if (this._fullEntropyCallback) {
- this._fullEntropyCallback(newPRNG);
- } else {
- this._prng = newPRNG;
- }
- }
- return entropyHash;
- },
- _stopCollectEntropy: function() {
- // stop collecting entropy
- this._stopCollectors();
- var entropyHash = this._updateEntropyHash();
- this._entropy = '';
- this._entropyCounter = 0;
- return entropyHash;
- },
- _updateEntropyHash: function() {
- var digester = this._tools._mdUpdate;
- digester.update(this._entropy);
- var entropyHash = forge.util.bytesToHex(digester.digest().getBytes());
- this._entropy = entropyHash;
- return entropyHash;
- },
- /**
- * Set Private Key and an Entropy it adds to be used to collect Entropy. The
- * amount of randomness(entropy) depends on the pin that is used for Private
- * Key generating.
- *
- * @function
- * @param privateKey
- * {string} private key, as string in PEM format.
- * @param pinEntropy
- * the amount of randomness that can be extracted from the
- * Private Key.
- */
- setDataForPrivateKeyEntropyCollector: function(privateKeyPem, pinEntropy) {
- if (privateKeyPem && (!isNaN(pinEntropy)) && (pinEntropy > 0)) {
- this._privateKeyPem = privateKeyPem;
- this._pinEntropy = pinEntropy;
- this._usePrivateKeyEntropy = true;
- }
- },
- /**
- * Initializes collectors and starts them. Set Private Key and Entropy
- * before if this information should be used to collect Entropy.
- */
- startEntropyCollection: function(entropyCollectorCallback) {
- var hashUpdaterInterval = 1000;
- this._initAndStart(hashUpdaterInterval, entropyCollectorCallback);
- },
- /**
- * In the case that the maximum amount of entropy had been reached before
- * calling this method, it does not do anything, and a false is returned.
- * Otherwise, this method creates a PRNG if the collectors have not gathered
- * the maximum amount of entropy. In addition, it stops the collectors.
- *
- * This method return a true if the maximum entropy was already reached and
- * false in other case.
- */
- stopEntropyCollectionAndCreatePRNG: function() {
- var generatedWithMaximumEntropy = true;
- if (!this._prng) {
- var entropyHash = this._stopCollectEntropy();
- this._prng = new cryptoPRNG.PRNG(entropyHash, this._tools);
- generatedWithMaximumEntropy = false;
- }
- return generatedWithMaximumEntropy;
- },
- /**
- * This method creates a PRNG from a given seed, in Hexadecimal format. This
- * method is to be used from a Worker, which has received the seed from the
- * main thread.
- *
- * @param seed
- * A string of 64 characters. It represents a 32-byte array in
- * Hexadecimal.
- *
- */
- createPRNGFromSeed: function(seed) {
- this._prng = new cryptoPRNG.PRNG(seed, this._tools);
- },
- /**
- * Generates a random array of bytes, which is then formatted to hexadecimal
- * This method is to be called from the main thread, and the given string is
- * to be passed to a Worker.
- */
- generateRandomSeedInHex: function(lengthSeed) {
- this._seedLength = (lengthSeed ? lengthSeed : 32);
- var seedInBytes = this._prng.generate(this._seedLength);
- return forge.util.bytesToHex(seedInBytes);
- },
- getPRNG: function() {
- if (!this._prng) {
- throw new Error('The PRNG has not been initialized yet');
- }
- return this._prng;
- },
- getEntropyCollectedAsPercentage: function() {
- if (this._entropyCounter >= this._maxEntropyCounter) {
- return 100;
- }
- return this._entropyCounter * 100 / this._maxEntropyCounter;
- }
- };
- })();
- cryptoPRNG.Tools = (function() {
- 'use strict';
- return {
- _mdUpdate: null,
- _mdReseed: null,
- _formatKey: null,
- _formatSeed: null,
- _cipher: null,
- init: function() {
- this._mdUpdate = forge.md.sha256.create();
- this._mdReseed = forge.md.sha256.create();
- this._formatKey = function(key) {
- // convert the key into 32-bit integers
- var tmp = forge.util.createBuffer(key);
- key = [
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32()
- ];
- // return the expanded key
- return forge.aes._expandKey(key, false);
- };
- this._formatSeed = function(seed) {
- // convert seed into 32-bit integers
- var tmp = forge.util.createBuffer(seed);
- seed = [
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32(),
- tmp.getInt32()
- ];
- return seed;
- };
- this._cipher = function(key, counter) {
- var aes_output = [];
- forge.aes._updateBlock(
- this._formatKey(key), this._formatSeed('' + counter), aes_output,
- false);
- var aes_buffer = forge.util.createBuffer();
- aes_buffer.putInt32(aes_output[0]);
- aes_buffer.putInt32(aes_output[1]);
- aes_buffer.putInt32(aes_output[2]);
- aes_buffer.putInt32(aes_output[3]);
- return aes_buffer.getBytes();
- };
- return this;
- }
- };
- })();
- cryptoPRNG.PRNG = function(entropyHash, tools) {
- 'use strict';
- this._key = '';
- this._counter = 0;
- this._tools = null;
- if (tools) {
- this._tools = tools;
- } else {
- this._tools = cryptoPRNG.Tools.init();
- }
- this._entropyHash = entropyHash;
- };
- cryptoPRNG.PRNG.prototype = (function() {
- 'use strict';
- return {
- /**
- * Generates a random array of bytes using the gathered entropy data.
- *
- * @param count
- * the total number of random bytes to generate
- */
- generate: function(count) {
- var keyAux;
- if (this._key === null || this._key === '') {
- this._reseed();
- }
- // buffer where to store the random bytes
- var b = forge.util.createBuffer();
- var limitReach = 1;
- while (b.length() < count) {
- b.putBytes(this._tools._cipher(this._key, this._counter));
- this._counter++;
- if (b.length >= (limitReach * Math.pow(2, 20))) {
- keyAux = this._key;
- this._key = '';
- for (var i = 0; i < 2; i++) {
- this._key += this._tools._cipher(keyAux, this._counter);
- this._counter++;
- }
- limitReach++;
- }
- }
- // do it two times to ensure a key with 256 bits
- keyAux = this._key;
- this._key = '';
- for (var j = 0; j < 2; j++) {
- this._key += this._tools._cipher(keyAux, this._counter);
- this._counter++;
- }
- return b.getBytes(count);
- },
- /**
- * Reseeds the generator
- */
- _reseed: function() {
- var digester = this._tools._mdReseed;
- digester.start();
- digester.update(this._entropyHash);
- digester.update(this._key);
- this._key = forge.util.bytesToHex(digester.digest().getBytes());
- this._counter++;
- }
- };
- })();
- cryptoPRNG.Collectors = (function() {
- 'use strict';
- var MIN_MATH_ROUND_ENTROPY_FACTOR = 1000000;
- function _getMathRoundWithEntropy(data) {
- return Math.round(data * MIN_MATH_ROUND_ENTROPY_FACTOR);
- }
- return {
- getAjaxCollector: function() {
- return {
- startCollector: function() {
- // if jQuery is included
- if (window.jQuery !== undefined) {
- $(window)
- .ajaxStart(function() {
- cryptoPRNG._collectEntropy((+new Date()), 1);
- })
- .ajaxComplete(function() {
- cryptoPRNG._collectEntropy((+new Date()), 1);
- });
- }
- },
- stopCollector: function() {
- // if jQuery is included
- if (window.jQuery !== undefined) {
- $(window).unbind('ajaxStart');
- $(window).unbind('ajaxComplete');
- }
- return true;
- }
- };
- },
- getJSExecutionCollector: function() {
- return {
- _collectTimeout: null,
- startCollector: function() {
- var timer_start = (+new Date()), timer_end;
- this._collectTimeout = (function collect() {
- timer_end = (+new Date());
- var total_time = timer_end - timer_start;
- // because of browser baseline time checks we limit it
- if (total_time > 20) {
- cryptoPRNG._collectEntropy((+new Date()), 1);
- }
- timer_start = timer_end;
- return setTimeout(collect, 0);
- })();
- },
- stopCollector: function() {
- clearTimeout(this._collectTimeout);
- }
- };
- },
- getNavigatorInfoCollector: function() {
- return {
- startCollector: function() {
- if (typeof(navigator) !== 'undefined') {
- var _navString = '';
- for (var key in navigator) {
- if (typeof key !== 'undefined') {
- try {
- if (typeof(navigator[key]) === 'string') {
- _navString += navigator[key];
- }
- } catch (e) {
- // ignore any kind of exception
- }
- }
- }
- cryptoPRNG._collectEntropy(_navString, 1);
- }
- },
- stopCollector: function() {
- // just executed once, so no need to execute nothing more
- return true;
- }
- };
- },
- getMathRandomCollector: function() {
- return {
- startCollector: function() {
- cryptoPRNG._collectEntropy(Math.random(), 0);
- },
- stopCollector: function() {
- // just executed once, so no need to execute nothing more
- return true;
- }
- };
- },
- getPrivateKeyCollector: function(privateKeyPem, pinEntropy) {
- var privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
- return {
- pkCollector: true,
- startCollector: function() {
- cryptoPRNG._collectEntropy(privateKey.d, pinEntropy);
- },
- stopCollector: function() {
- // just executed once, so no need to execute nothing more
- return true;
- }
- };
- },
- getWebKitRandomCollector: function(globalCrypto, entropyQuantity) {
- return {
- startCollector: function() {
- var numPositions = entropyQuantity / 32;
- // get cryptographically strong entropy in Webkit
- var ab = new Uint32Array(numPositions);
- globalCrypto.getRandomValues(ab);
- var data = '';
- for (var i = 0; i < ab.length; i++) {
- data += '' + (ab[i]);
- }
- cryptoPRNG._collectEntropy(data, entropyQuantity);
- },
- stopCollector: function() {
- // just executed once, so no need to execute nothing more
- return true;
- }
- };
- },
- getMouseMoveCollector: function(ev) {
- // to ensure compatibility with IE 8
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.x || ev.clientX || ev.offsetX || 0) +
- (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
- 3);
- },
- getMouseWheelCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.offsetY || 0) + (+new Date()), 3);
- },
- getMouseDownCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.x || ev.clientX || ev.offsetX || 0) +
- (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
- 3);
- },
- getMouseUpCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.x || ev.clientX || ev.offsetX || 0) +
- (ev.y || ev.clientY || ev.offsetY || 0) + (+new Date()),
- 3);
- },
- getTouchStartCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.touches[0].pageX || ev.clientX || 0) +
- (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
- 5);
- },
- getTouchMoveCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.touches[0].pageX || ev.clientX || 0) +
- (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
- 3);
- },
- getTouchEndCollector: function() {
- cryptoPRNG._collectEntropy((+new Date()), 1);
- },
- getGestureStartCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy(
- (ev.touches[0].pageX || ev.clientX || 0) +
- (ev.touches[0].pageY || ev.clientY || 0) + (+new Date()),
- 5);
- },
- getGestureEndCollector: function() {
- cryptoPRNG._collectEntropy((+new Date()), 1);
- },
- motionX: null,
- motionY: null,
- motionZ: null,
- getDeviceMotionCollector: function(ev) {
- ev = ev || window.event;
- var acceleration = ev.accelerationIncludingGravity;
- var currentX = (_getMathRoundWithEntropy(acceleration.x) || 0);
- var currentY = (_getMathRoundWithEntropy(acceleration.y) || 0);
- var currentZ = (_getMathRoundWithEntropy(acceleration.z) || 0);
- var rotation = ev.rotationRate;
- if (rotation !== null) {
- currentX += _getMathRoundWithEntropy(rotation.alpha);
- currentY += _getMathRoundWithEntropy(rotation.beta);
- currentZ += _getMathRoundWithEntropy(rotation.gamma);
- }
- // The API detects and delivers accelerometer data 50 times per
- // second
- // even if there is any event related, so this is
- // a way to control if it really changed or not
- if ((cryptoPRNG.Collectors.motionX === null) ||
- (cryptoPRNG.Collectors.motionY === null) ||
- (cryptoPRNG.Collectors.motionZ === null) ||
- (cryptoPRNG.Collectors.motionX !== currentX) ||
- (cryptoPRNG.Collectors.motionY !== currentY) ||
- (cryptoPRNG.Collectors.motionZ !== currentZ)) {
- cryptoPRNG.Collectors.motionX = currentX;
- cryptoPRNG.Collectors.motionY = currentY;
- cryptoPRNG.Collectors.motionZ = currentZ;
- cryptoPRNG._collectEntropy(
- currentX + currentY + currentZ + (+new Date()), 1);
- }
- },
- deviceOrientationX: null,
- deviceOrientationY: null,
- deviceOrientationZ: null,
- getDeviceOrientationCollector: function(ev) {
- ev = ev || window.event;
- var currentX =
- (_getMathRoundWithEntropy(ev.gamma) ||
- _getMathRoundWithEntropy(ev.x) || 0);
- var currentY =
- (_getMathRoundWithEntropy(ev.beta) ||
- _getMathRoundWithEntropy(ev.y) || 0);
- var currentZ =
- (_getMathRoundWithEntropy(ev.alpha) ||
- _getMathRoundWithEntropy(ev.z) || 0);
- // The API detects and delivers accelerometer data 50 times per
- // second
- // even if there is any event related, so this is
- // a way to control if it really changed or not
- if ((cryptoPRNG.Collectors.deviceOrientationX === null) ||
- (cryptoPRNG.Collectors.deviceOrientationY === null) ||
- (cryptoPRNG.Collectors.deviceOrientationZ === null) ||
- (cryptoPRNG.Collectors.deviceOrientationX !== currentX) ||
- (cryptoPRNG.Collectors.deviceOrientationY !== currentY) ||
- (cryptoPRNG.Collectors.deviceOrientationZ !== currentZ)) {
- cryptoPRNG.Collectors.deviceOrientationX = currentX;
- cryptoPRNG.Collectors.deviceOrientationY = currentY;
- cryptoPRNG.Collectors.deviceOrientationZ = currentZ;
- cryptoPRNG._collectEntropy(
- currentX + currentY + currentZ + (+new Date()), 1);
- }
- },
- getKeyDownCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
- },
- getKeyUpCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
- },
- getLoadCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
- },
- getScrollCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
- },
- getRequestsCollector: function(ev) {
- ev = ev || window.event;
- cryptoPRNG._collectEntropy((ev.keyCode) + (+new Date()), 3);
- }
- };
- })();
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules = cryptolib.modules || {};
- /**
- * Defines the generation and opening of digital envelopes.
- */
- cryptolib.modules.digitalenvelope = function(box) {
- 'use strict';
- box.digitalenvelope = box.digitalenvelope || {};
- box.digitalenvelope.factory = {};
- var policies = {
- symmetric: {
- secretkey: {
- encryption: {
- lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
- .encryption.lengthBytes
- },
- mac: {
- lengthBytes:
- box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
- }
- }
- }
- };
- var exceptions;
- var converters;
- var bitOperators;
- var secretKeyFactory;
- var macDigester;
- var symmetricCipher;
- var asymmetricCipher;
- var f = function(box) {
- exceptions = box.commons.exceptions;
- converters = new box.commons.utils.Converters();
- bitOperators = new box.commons.utils.BitOperators();
- secretKeyFactory = new box.symmetric.secretkey.factory.SecretKeyFactory();
- macDigester = (new box.symmetric.mac.factory.MacFactory()).create();
- symmetricCipher =
- (new box.symmetric.cipher.factory.SymmetricCipherFactory())
- .getCryptoSymmetricCipher();
- asymmetricCipher =
- (new box.asymmetric.cipher.factory.AsymmetricCipherFactory())
- .getCryptoAsymmetricCipher();
- };
- f.policies = {
- symmetric: {
- secretkey: {
- encryption: {
- lengthBytes: box.policies.digitalenvelope.symmetric.secretkey
- .encryption.lengthBytes
- },
- mac: {
- lengthBytes:
- box.policies.digitalenvelope.symmetric.secretkey.mac.lengthBytes
- },
- secureRandom: {
- provider: box.policies.digitalenvelope.symmetric.secretkey
- .secureRandom.provider
- }
- },
- cipher: {
- provider: box.policies.digitalenvelope.symmetric.cipher.provider,
- algorithm: {
- AES128_GCM: {
- name: box.policies.digitalenvelope.symmetric.cipher.algorithm
- .AES128_GCM.name,
- keyLengthBytes: box.policies.digitalenvelope.symmetric.cipher
- .algorithm.AES128_GCM.keyLengthBytes,
- tagLengthBytes: box.policies.digitalenvelope.symmetric.cipher
- .algorithm.AES128_GCM.tagLengthBytes
- }
- },
- initializationVectorLengthBytes:
- box.policies.digitalenvelope.symmetric.cipher
- .initializationVectorLengthBytes,
- secureRandom: {
- provider: box.policies.digitalenvelope.symmetric.cipher.secureRandom
- .provider
- }
- },
- mac: {
- hash: box.policies.digitalenvelope.symmetric.mac.hash,
- provider: box.policies.digitalenvelope.symmetric.mac.provider
- }
- },
- asymmetric: {
- cipher: {
- algorithm: box.policies.digitalenvelope.asymmetric.cipher.algorithm,
- secretKeyLengthBytes:
- box.policies.digitalenvelope.asymmetric.cipher.secretKeyLengthBytes,
- ivLengthBytes:
- box.policies.digitalenvelope.asymmetric.cipher.ivLengthBytes,
- tagLengthBytes:
- box.policies.digitalenvelope.asymmetric.cipher.tagLengthBytes,
- deriver: box.policies.digitalenvelope.asymmetric.cipher.deriver,
- hash: box.policies.digitalenvelope.asymmetric.cipher.hash,
- symmetricCipher:
- box.policies.digitalenvelope.asymmetric.cipher.symmetricCipher,
- provider: box.policies.digitalenvelope.asymmetric.cipher.provider,
- secureRandom: {
- provider: box.policies.digitalenvelope.asymmetric.cipher.secureRandom
- .provider
- }
- }
- }
- };
- cryptolib('commons', 'symmetric', 'asymmetric.cipher', f);
- /**
- * Defines a factory for the creation of digital envelope generators and
- * openers.
- *
- * @class DigitalEnvelopeFactory
- * @memberof digitalenvelope
- */
- box.digitalenvelope.factory.DigitalEnvelopeFactory = function() {
- };
- box.digitalenvelope.factory.DigitalEnvelopeFactory.prototype = {
- /**
- * Obtains a new digital envelope generator.
- *
- * @function getDigitalEnvelopeGenerator
- * @return {DigitalEnvelopeGenerator} the digital envelope generator.
- */
- getDigitalEnvelopeGenerator: function() {
- try {
- return new box.digitalenvelope.DigitalEnvelopeGenerator();
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not obtain a digital envelope generator.', error);
- }
- },
- /**
- * Obtains new a digital envelope opener.
- *
- * @function getDigitalEnvelopeOpener
- * @return {DigitalEnvelopeOpener} the digital envelope opener.
- */
- getDigitalEnvelopeOpener: function() {
- try {
- return new box.digitalenvelope.DigitalEnvelopeOpener();
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not obtain a digital envelope opener.', error);
- }
- }
- };
- /**
- * Defines a digital envelope generator.
- *
- * @class DigitalEnvelopeGenerator
- * @memberof digitalenvelope
- */
- box.digitalenvelope.DigitalEnvelopeGenerator = function() {
- };
- box.digitalenvelope.DigitalEnvelopeGenerator.prototype = {
- /**
- * Generates a digital envelope for some data. The envelope can be
- * generated with one or more public keys, each of whose corresponding
- * private key can be used to open the envelope.
- *
- * @function generate
- * @param dataBase64
- * {string} the data to store in the digital envelope, as a
- * string in Base64 encoded format.
- * @param publicKeysPem
- * {string[]} a list of one or more public keys used to
- * generate the digital envelope, as an array of strings in
- * PEM format.
- * @return {DigitalEnvelope} the generated digital envelope.
- */
- generate: function(dataBase64, publicKeysPem) {
- try {
- validateGeneratorInput(dataBase64, publicKeysPem);
- // Generate encryption secret key and use it to symmetrically encrypt
- // data.
- var secretKeyForEncryptionBase64 =
- secretKeyFactory.getCryptoSecretKeyGeneratorForEncryption()
- .generate();
- var encryptedDataBase64 =
- symmetricCipher.encrypt(secretKeyForEncryptionBase64, dataBase64);
- // Generate MAC secret key and use it to generate MAC of symmetrically
- // Base64 encryption of encrypted data.
- var secretKeyForMacBase64 =
- secretKeyFactory.getCryptoSecretKeyGeneratorForMac().generate();
- var encryptedDataBase64Base64 =
- converters.base64Encode(encryptedDataBase64);
- var macBase64 = macDigester.generate(
- secretKeyForMacBase64, [encryptedDataBase64Base64]);
- // Construct bit-wise concatenation of encryption and MAC secret keys.
- var secretKeyForEncryption =
- converters.base64Decode(secretKeyForEncryptionBase64);
- var secretKeyForMac = converters.base64Decode(secretKeyForMacBase64);
- var secretKeyConcatenation =
- secretKeyForEncryption.toString() + secretKeyForMac.toString();
- var secretKeyConcatenationBase64 =
- converters.base64Encode(secretKeyConcatenation);
- // Generate list of asymmetric encryptions of the secret key
- // concatenation, each encryption created using a different one of the
- // public keys provided as input for the digital envelope generation.
- var secretKeyEncryptions = [];
- for (var i = 0; i < publicKeysPem.length; i++) {
- var publicKeyPem = publicKeysPem[i];
- var encryptedSecretKeyConcatentionBase64 = asymmetricCipher.encrypt(
- publicKeyPem, secretKeyConcatenationBase64);
- secretKeyEncryptions.push(new SecretKeyEncryption(
- encryptedSecretKeyConcatentionBase64, publicKeyPem));
- }
- return new DigitalEnvelope(
- encryptedDataBase64, macBase64, secretKeyEncryptions);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Digital envelope could not be generated.', error);
- }
- }
- };
- /**
- * Defines a digital envelope opener.
- *
- * @class DigitalEnvelopeOpener
- * @memberof digitalenvelope
- */
- box.digitalenvelope.DigitalEnvelopeOpener = function() {
- this._getEncryptedSecretKeyConcatenation = function(
- secretKeyEncryptions, privateKeyPem) {
- // Extract modulus and public exponent from private key.
- var privateKey = box.forge.pki.privateKeyFromPem(privateKeyPem);
- var modulus = privateKey.n;
- var publicExponent = privateKey.e;
- for (var i = 0; i < secretKeyEncryptions.length; i++) {
- var publicKeyPem = secretKeyEncryptions[i].getPublicKey();
- var publicKey = box.forge.pki.publicKeyFromPem(publicKeyPem);
- if (publicKey.n.equals(modulus) && publicKey.e.equals(publicExponent)) {
- return secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
- }
- }
- throw new exceptions.CryptoLibException(
- 'Could not find an asymmetric encryption of the secret key concatenation that could be decrypted using the private key provided.');
- };
- };
- box.digitalenvelope.DigitalEnvelopeOpener.prototype = {
- /**
- * Opens a digital envelope and retrieves its data. The envelope can be
- * opened with any private key corresponding to a public key that was
- * used to generate the envelope.
- *
- * @function open
- * @param digitalEnvelope
- * {DigitalEnvelope} the digital envelope to open.
- * @param privateKeyPem
- * {string} the private key used to open the digital
- * envelope, as a string in PEM format.
- * @return {string} the data stored in the digital envelope, as a string
- * in Base64 encoded format.
- */
- open: function(digitalEnvelope, privateKeyPem) {
- try {
- validateOpenerInput(digitalEnvelope, privateKeyPem);
- // Retrieve data from digital envelope.
- var encryptedDataBase64 = digitalEnvelope.getEncryptedData();
- var macBase64 = digitalEnvelope.getMac();
- var secretKeyEncryptions = digitalEnvelope.getSecretKeyEncryptions();
- // Retrieve asymmetric encryption of bit-wise concatenation of
- // encryption and MAC secret keys that can be decrypted with private
- // key provided as input.
- var encryptedSecretKeyConcatenationBase64 =
- this._getEncryptedSecretKeyConcatenation(
- secretKeyEncryptions, privateKeyPem);
- // Asymmetrically decrypt bit-wise concatenation of encryption and MAC
- // secret keys.
- var secretKeyConcatenationBase64 = asymmetricCipher.decrypt(
- privateKeyPem, encryptedSecretKeyConcatenationBase64);
- var secretKeyConcatenation =
- converters.base64Decode(secretKeyConcatenationBase64);
- // Extract secret keys from bit-wise concatenation.
- var secretKeyForEncryptionLength =
- policies.symmetric.secretkey.encryption.lengthBytes;
- var secretKeyForMacLength =
- policies.symmetric.secretkey.mac.lengthBytes;
- var secretKeyForEncryption = bitOperators.extract(
- secretKeyConcatenation, 0, secretKeyForEncryptionLength);
- var secretKeyForEncryptionBase64 =
- converters.base64Encode(secretKeyForEncryption);
- var secretKeyForMac = bitOperators.extract(
- secretKeyConcatenation, secretKeyForEncryptionLength,
- secretKeyForEncryptionLength + secretKeyForMacLength);
- var secretKeyForMacBase64 = converters.base64Encode(secretKeyForMac);
- // Check integrity of digital envelope.
- var encryptedDataBase64Base64 =
- converters.base64Encode(encryptedDataBase64);
- if (!macDigester.verify(
- macBase64, secretKeyForMacBase64,
- [encryptedDataBase64Base64])) {
- throw new exceptions.CryptoLibException(
- 'Integrity of digital envelope could not be verified.');
- }
- return symmetricCipher.decrypt(
- secretKeyForEncryptionBase64, encryptedDataBase64);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Digital envelope could not be opened.', error);
- }
- }
- };
- /**
- * Container class for a digital envelope.
- *
- * @class DigitalEnvelope
- * @param encryptedDataBase64
- * {string} the symmetrically encrypted data, as a string in
- * Base64 encoded format.
- * @param macBase64
- * {string} the MAC of the symmetrically encrypted data, as a
- * string in Base64 encoded format.
- * @param secretKeyEncryptions
- * {SecretKeyEncryption[]} the list of asymmetric encryptions of
- * the secret key concatenation, each encryption having been
- * created using a different one of the public keys provided as
- * input to the digital envelope generator.
- * @memberof digitalenvelope
- */
- function DigitalEnvelope(
- encryptedDataBase64, macBase64, secretKeyEncryptions) {
- this.encryptedDataBase64 = encryptedDataBase64;
- this.macBase64 = macBase64;
- this.secretKeyEncryptions = secretKeyEncryptions;
- var _encryptedSecretKeyConcatsBase64 = [];
- var _publicKeysPem = [];
- for (var i = 0; i < secretKeyEncryptions.length; i++) {
- _encryptedSecretKeyConcatsBase64[i] =
- secretKeyEncryptions[i].getEncryptedSecretKeyConcatenation();
- _publicKeysPem[i] = secretKeyEncryptions[i].getPublicKey();
- }
- this._getEncryptedSecretKeyConcatsBase64 = function() {
- return _encryptedSecretKeyConcatsBase64;
- };
- this._getPublicKeysPem = function() {
- return _publicKeysPem;
- };
- }
- DigitalEnvelope.prototype = {
- /**
- * @function getEncryptedData
- * @return {string} the symmetrically encrypted data, as a string in
- * Base64 encoded format.
- */
- getEncryptedData: function() {
- return this.encryptedDataBase64;
- },
- /**
- * @function getMac
- * @return {string} the MAC of the symmetrically encrypted data, as a
- * string in Base64 encoded format.
- */
- getMac: function() {
- return this.macBase64;
- },
- /**
- * @function getSecretKeyEncryptions
- * @return {SecretKeyEncryption[]} the list of asymmetric encryptions of
- * the secret key concatenation.
- */
- getSecretKeyEncryptions: function() {
- return this.secretKeyEncryptions;
- },
- /**
- * Generates a string representation of the digital envelope.
- * <p>
- * Note: in order to permit interoperability between libraries, this
- * representation should match the equivalent representation in Java.
- *
- * @function stringify
- * @return {string} the string representation of the digital envelope.
- */
- stringify: function() {
- return JSON.stringify({
- digitalEnvelope: {
- encryptedDataBase64: this.encryptedDataBase64,
- macBase64: this.macBase64,
- encryptedSecretKeyConcatsBase64:
- this._getEncryptedSecretKeyConcatsBase64(),
- publicKeysPem: this._getPublicKeysPem()
- }
- });
- }
- };
- /**
- * Container class for the asymmetric encryption of the bit-wise
- * concatenation of the secret key used to symmetrically encrypt the data of
- * a digital envelope and the secret key used to generate an MAC for
- * checking the integrity of the symmetric encryption. The public key used
- * to perform the asymmetric encryption of the secret key concatenation is
- * also included.
- *
- * @class SecretKeyEncryption
- * @param encryptedSecretKeyConcatBase64
- * {string} the asymmetric encryption of the secret key
- * concatenation, using the public key provided as input, as a
- * string in Base64 encoded format.
- * @param publicKeyPem
- * {string} the public key, of type
- * {@link java.security.PublicKey}, used to asymmetrically
- * encrypt the secret key concatenation.
- * @memberof digitalenvelope
- */
- function SecretKeyEncryption(encryptedSecretKeyConcatBase64, publicKeyPem) {
- /**
- * @function getEncryptedSecretKeyConcatenationBase64
- * @return {string} the asymmetrically encrypted secret key
- * concatenation, as a string in Base64 encoded format.
- */
- var getEncryptedSecretKeyConcatenation = function() {
- return encryptedSecretKeyConcatBase64;
- };
- /**
- * @function getPublicKey
- * @return {string} the public key used to asymmetrically encrypt the
- * secret key concatenation, as a string in PEM format.
- */
- var getPublicKey = function() {
- return publicKeyPem;
- };
- return {
- getEncryptedSecretKeyConcatenation: getEncryptedSecretKeyConcatenation,
- getPublicKey: getPublicKey
- };
- }
- /**
- * Deserializes a digital envelope.
- *
- * @function deserialize
- * @param serializedDigitalEnvelope
- * {string} the serialized digital envelope.
- * @return {DigitalEnvelope} the digital envelope after deserialization.
- * @memberof digitalenvelope
- */
- box.digitalenvelope.deserialize = function(serializedDigitalEnvelope) {
- validateDeserializerInput(serializedDigitalEnvelope);
- var digitalEnvelopeJson =
- JSON.parse(serializedDigitalEnvelope).digitalEnvelope;
- var encryptedDataBase64 = digitalEnvelopeJson.encryptedDataBase64;
- var macBase64 = digitalEnvelopeJson.macBase64;
- var encryptedSecretKeyConcatsBase64 =
- digitalEnvelopeJson.encryptedSecretKeyConcatsBase64;
- var publicKeysPem = digitalEnvelopeJson.publicKeysPem;
- var secretKeyEncryptions = [];
- for (var i = 0; i < encryptedSecretKeyConcatsBase64.length; i++) {
- secretKeyEncryptions.push(new SecretKeyEncryption(
- encryptedSecretKeyConcatsBase64[i], publicKeysPem[i]));
- }
- return new DigitalEnvelope(
- encryptedDataBase64, macBase64, secretKeyEncryptions);
- };
- function validateGeneratorInput(dataBase64, publicKeysPem) {
- if (typeof dataBase64 === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'Data provided to digital envelope generator is undefined.');
- }
- if (converters.base64Decode(dataBase64) === '') {
- throw new exceptions.CryptoLibException(
- 'Data provided to digital envelope generator is empty.');
- }
- if (typeof dataBase64 !== 'string') {
- throw new exceptions.CryptoLibException(
- 'Base64 encoded data provided to digital envelope generator is not a String.');
- }
- if (typeof publicKeysPem === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'Public key array provided to digital envelope generator is undefined.');
- }
- if (!(publicKeysPem instanceof Array)) {
- throw new exceptions.CryptoLibException(
- 'Public key array provided to digital envelope generator is not of type Array.');
- }
- if (publicKeysPem.length === 0) {
- throw new exceptions.CryptoLibException(
- 'Public key array provided to digital envelope generator is empty.');
- }
- }
- function validateOpenerInput(digitalEnvelope, privateKeyPem) {
- if (typeof digitalEnvelope === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'Digital envelope provided to digital envelope opener is undefined.');
- }
- if (!(digitalEnvelope instanceof Object)) {
- throw new exceptions.CryptoLibException(
- 'Digital envelope provided to digital envelope generator is not of type Object.');
- }
- if (typeof privateKeyPem === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'Private key provided to digital envelope opener is undefined.');
- }
- if (typeof privateKeyPem !== 'string') {
- throw new exceptions.CryptoLibException(
- 'Private key PEM provided to digital envelope opener is not of type String.');
- }
- }
- function validateDeserializerInput(serializedDigitalEnvelope) {
- if (typeof serializedDigitalEnvelope === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'Serialized object provided to digital envelope deserializer is undefined.');
- }
- if (typeof serializedDigitalEnvelope !== 'string') {
- throw new exceptions.CryptoLibException(
- 'Serialized object provided to digital envelope deserializer is not of type String.');
- }
- if (serializedDigitalEnvelope.length === 0) {
- throw new exceptions.CryptoLibException(
- 'Serialized object provided to digital envelope deserializer is empty.');
- }
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.digitalenvelope = cryptolib.modules.digitalenvelope || {};
- /**
- * Defines the digital envelope service.
- *
- * @namespace digitalenvelope
- */
- cryptolib.modules.digitalenvelope.service = function(box) {
- 'use strict';
- box.digitalenvelope = box.digitalenvelope || {};
- box.digitalenvelope.service = {};
- var digitalEnvelopeFactory;
- cryptolib('digitalenvelope', function(box) {
- digitalEnvelopeFactory =
- new box.digitalenvelope.factory.DigitalEnvelopeFactory();
- });
- /**
- * Creates a digital envelope, using one or more public keys, each of whose
- * corresponding private key can be used to open the envelope and retrieve
- * the data.
- *
- * @function createDigitalEnvelope
- * @param dataBase64
- * {string} the data to store in the digital envelope, as a
- * string in Base64 encoded format.
- * @param publicKeysPem
- * {string[]} a list of one or more public keys used to generate
- * the digital envelope, as an array of strings in PEM format.
- * @return {DigitalEnvelope} the newly created digital envelope.
- */
- box.digitalenvelope.service.createDigitalEnvelope = function(
- dataBase64, publicKeysPem) {
- var generator = digitalEnvelopeFactory.getDigitalEnvelopeGenerator();
- return generator.generate(dataBase64, publicKeysPem);
- };
- /**
- * Opens an existing digital envelope and retrieves the data that it
- * contains. The envelope can be opened with any private key corresponding
- * to a public key that was used to generate the envelope.
- *
- * @function openDigitalEnvelope
- * @param digitalEnvelope
- * {DigitalEnvelope} the digital envelope to open.
- * @param privateKeyPem
- * {string} the private key used to open the digital envelope, as
- * a string in PEM format.
- * @return {string} the data contained in the digital envelope, as a string
- * in Base64 encoded format.
- */
- box.digitalenvelope.service.openDigitalEnvelope = function(
- digitalEnvelope, privateKeyPem) {
- var opener = digitalEnvelopeFactory.getDigitalEnvelopeOpener();
- return opener.open(digitalEnvelope, privateKeyPem);
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
- cryptolib.modules.homomorphic.cipher = function(box) {
- 'use strict';
- box.homomorphic = box.homomorphic || {};
- box.homomorphic.cipher = {};
- /**
- * A submodule that holds ElGamal cipher functionalities.
- *
- * @exports homomorphic/cipher/factory
- */
- box.homomorphic.cipher.factory = {};
- var converters, exceptions, randomFactory, mathematical, keyPairFactory;
- var f = function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- mathematical = box.commons.mathematical;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- keyPairFactory = new box.homomorphic.keypair.factory.KeyFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.homomorphic.cipher.secureRandom.provider}
- }
- };
- cryptolib('commons', 'primitives.securerandom', 'homomorphic.keypair', f);
- /** @class */
- box.homomorphic.cipher.factory.ElGamalCipherFactory = function() {
- };
- box.homomorphic.cipher.factory.ElGamalCipherFactory.prototype = {
- /**
- * @function createEncrypter
- * @returns ElGamalEncrypter
- */
- createEncrypter: function(elGamalPublicKey, cryptoRandomInteger) {
- if (typeof cryptoRandomInteger === 'undefined') {
- cryptoRandomInteger = randomFactory.getCryptoRandomInteger();
- }
- return new ElGamalEncrypter(elGamalPublicKey, cryptoRandomInteger);
- },
- /**
- * @function createDecrypter
- * @returns ElGamalDecrypter
- */
- createDecrypter: function(elGamalPrivateKey) {
- return new ElGamalDecrypter(elGamalPrivateKey);
- },
- /**
- * @function createRandomDecrypter
- * @returns ElGamalRandomDecrypter
- */
- createRandomDecrypter: function(elGamalPublicKey, cryptoRandomInteger) {
- return new ElGamalRandomDecrypter(elGamalPublicKey, cryptoRandomInteger);
- }
- };
- function validateArray(inputArray) {
- if (typeof inputArray === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The given array should be initialized');
- }
- if (!(inputArray instanceof Array)) {
- throw new exceptions.CryptoLibException(
- 'The given array are not from the expected type');
- }
- if (inputArray === []) {
- throw new exceptions.CryptoLibException(
- 'The given array cannot be empty');
- }
- }
- /**
- * Defines an ElGamal encrypter.
- * <P>
- * The methods specified in this object allow data to be encrypted using an
- * implementation of the ElGamal cryptosystem.
- *
- * @class ElGamalEncrypter
- * @param {ElGamalPublicKey}
- * elGamalPublicKey The public key.
- * @param {Object}
- * cryptoRandomInteger The source of randomness.
- * @returns {ElGamalEncrypter}
- */
- function ElGamalEncrypter(elGamalPublicKey, cryptoRandomInteger) {
- var _elGamalPublicKey = elGamalPublicKey;
- var _cryptoRandomInteger = cryptoRandomInteger;
- /**
- * @function getElGamalPublicKey
- *
- * @returns {ElGamalPublicKey}
- */
- this.getElGamalPublicKey = function() {
- return _elGamalPublicKey;
- };
- /**
- * @function getCryptoRandomInteger
- *
- * @returns {ElGamalPublicKey}
- */
- this.getCryptoRandomInteger = function() {
- return _cryptoRandomInteger;
- };
- // Private methods
- this._validateMessagesNotLargerThanKeySize = function(length) {
- if (_elGamalPublicKey.getGroupElementsArray().length < length) {
- throw new exceptions.CryptoLibException(
- 'The list of messages to encrypt was larger than the number of public key elements.');
- }
- };
- this._validatePrePhisNotLargerThanKeySize = function(phis) {
- if (_elGamalPublicKey.getGroupElementsArray().length < phis.length) {
- throw new exceptions.CryptoLibException(
- 'The list of prePhis was larger than the number of public key elements.');
- }
- };
- this._preCompute = function(useShortExponent) {
- var gamma;
- var prePhis = [];
- try {
- var publicKeyElements = _elGamalPublicKey.getGroupElementsArray();
- var group = _elGamalPublicKey.getGroup();
- if (useShortExponent &&
- !group.isQuadraticResidueGroup()) {
- throw new exceptions.CryptoLibException(
- 'Attempt to ElGamal encrypt using short exponent for Zp subgroup that is not of type quadratic residue.');
- }
- var randomExponent = mathematical.groupUtils.generateRandomExponent(
- group, _cryptoRandomInteger, useShortExponent);
- gamma = group.getGenerator().exponentiate(randomExponent);
- // For each element in the array of public key elements, compute the
- // following: element: prephi[i] = pubKey[i]^(random)
- var pubKeyElementRaised;
- for (var i = 0; i < publicKeyElements.length; i++) {
- pubKeyElementRaised =
- publicKeyElements[i].exponentiate(randomExponent);
- prePhis.push(pubKeyElementRaised);
- }
- return new ElGamalEncrypterValues(randomExponent, gamma, prePhis);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'There was an error while precomputing values.', error);
- }
- };
- this._compute = function(messages, computationValues) {
- var compressedComputationValues = compressComputationValuesIfNecessary(
- messages.length, computationValues);
- var phis = [];
- // For each element in the array of messages, compute the following:
- // element:phi[i]=message[i]*prePhi[i]
- for (var i = 0; i < compressedComputationValues.getPhis().length; i++) {
- phis.push(
- messages[i].multiply(compressedComputationValues.getPhis()[i]));
- }
- return new box.homomorphic.cipher.ElGamalComputationValues(
- compressedComputationValues.getGamma(), phis);
- };
- this._getListAsQuadraticResidues = function(messages) {
- var valuesZpSubgroupElements = [];
- var group = _elGamalPublicKey.getGroup();
- var groupElement;
- for (var i = 0; i < messages.length; i++) {
- groupElement = new mathematical.ZpGroupElement(
- new box.forge.jsbn.BigInteger(messages[i]), group.getP(),
- group.getQ());
- valuesZpSubgroupElements.push(groupElement);
- }
- return valuesZpSubgroupElements;
- };
- function compressComputationValuesIfNecessary(
- numMessages, computationValues) {
- var phis = computationValues.getPhis();
- if (phis.length <= numMessages) {
- return computationValues;
- }
- var compressedPhiArray =
- mathematical.groupUtils.buildListWithCompressedFinalElement(
- _elGamalPublicKey.getGroup(), phis, numMessages);
- return new box.homomorphic.cipher.ElGamalComputationValues(
- computationValues.getGamma(), compressedPhiArray);
- }
- }
- ElGamalEncrypter.prototype = {
- /**
- * Encrypt the received list of messages (which are represented as
- * ZpGroupElements).
- * <p>
- * The length of the received list of messages must be equal to, or less
- * than, the length of the public key of this encrypter. If this
- * condition is not met, then an exception will be thrown.
- *
- * @function encryptGroupElements
- *
- * @param {Array}
- * messages an array of ZpGroupElements.
- * @param {Object} [encryptionOption] an optional input parameter. If this option is of type
- * {boolean}, then the encryption will be pre-computed, using
- * the value of the boolean to determine whether or not to
- * use a short random exponent for the pre-computation. If
- * the option is of type {ElGamalEncrypterValues} then it
- * will be used as the pre-computation of the encryption.
- *
- * @returns {ElGamalEncrypterValues}
- */
- encryptGroupElements: function(messages, encryptionOption) {
- validateArray(messages);
- this._validateMessagesNotLargerThanKeySize(messages.length);
- var useShortExponent;
- var preComputedValues;
- if (typeof encryptionOption !== 'undefined' &&
- typeof encryptionOption === 'boolean') {
- useShortExponent = encryptionOption;
- } else {
- preComputedValues = encryptionOption;
- }
-
- if (!preComputedValues) {
- preComputedValues = this._preCompute(useShortExponent);
- } else {
- var prePhis = preComputedValues.getPhis();
- validateArray(prePhis);
- this._validatePrePhisNotLargerThanKeySize(prePhis);
- }
- var computationValues = this._compute(
- messages, preComputedValues.getElGamalComputationValues());
- return new ElGamalEncrypterValues(
- preComputedValues.getR(), computationValues.getGamma(),
- computationValues.getPhis());
- },
- /**
- * Pre-compute the ElGamal encrypter values, based on the ElGamal public
- * key provided to the encrypter.
- *
- * @param {boolean}
- * [useShortExponent] true if a short exponent is to be used
- * for the pre-computations. Default value is false.
- * @returns {ElGamalEncrypterValues}
- */
- preCompute: function(useShortExponent) {
- return this._preCompute(useShortExponent);
- },
- /**
- * Encrypt the received list of messages (which are represented as
- * Strings).
- * <p>
- * The length of the received list of messages must be equal to, or less
- * than, the length of the public key of this encrypter. If this
- * condition is not met, then an exception will be thrown.
- *
- * @function encryptStrings
- *
- * @param {Array}
- * messages an array of strings.
- * @param {ElGamalEncrypterValues}
- * [preComputedValues] an optional parameter. If it is not
- * provided, then pre-computations are made.
- *
- * @returns {ElGamalEncrypterValues} the pre-computed values.
- */
- encryptStrings: function(messages, preComputedValues) {
- var messagesAsGroupElements = this._getListAsQuadraticResidues(messages);
- if (!preComputedValues) {
- return this.encryptGroupElements(messagesAsGroupElements);
- } else {
- return this.encryptGroupElements(
- messagesAsGroupElements, preComputedValues);
- }
- }
- };
- /**
- * Defines an ElGamal decrypter.
- *
- * @class ElGamalDecrypter
- * @param {ElGamalPrivateKey}
- * elGamalPrivateKey The ElGamal private key.
- * @returns {ElGamalDecrypter}
- */
- function ElGamalDecrypter(elGamalPrivateKey) {
- function validateCorrectGroup(elGamalPrivateKey) {
- var exponentsArray = elGamalPrivateKey.getExponentsArray();
- var group = elGamalPrivateKey.getGroup();
- for (var i = 0; i < exponentsArray.length; i++) {
- if (!(group.getQ().equals(exponentsArray[i].getQ()))) {
- throw new exceptions.CryptoLibException(
- 'Each Exponent must be of the specified group order.');
- }
- }
- }
- validateCorrectGroup(elGamalPrivateKey);
- var _elGamalPrivateKey = elGamalPrivateKey;
- this.getElGamalPrivateKey = function() {
- return _elGamalPrivateKey;
- };
- this._areGroupMembers = function(cipherText) {
- for (var i = 0; i < cipherText.getPhis().length; i++) {
- var next = cipherText.getPhis()[i];
- if (!(_elGamalPrivateKey.getGroup().isGroupMember(next))) {
- return false;
- }
- }
- return true;
- };
- this._validateCiphertextSize = function(cipherText) {
- if (_elGamalPrivateKey.getExponentsArray().length <
- cipherText.getPhis().length) {
- throw new exceptions.CryptoLibException(
- 'The list of ciphertext was larger than the number of private key exponents.');
- }
- };
- this._compressKeyIfNecessary = function(numRequired) {
- var exponents = _elGamalPrivateKey.getExponentsArray();
- var group = _elGamalPrivateKey.getGroup();
- if (exponents.length <= numRequired) {
- return _elGamalPrivateKey;
- }
- var listWithCompressedFinalExponent =
- mathematical.groupUtils.buildListWithCompressedFinalExponent(
- group, exponents, numRequired);
- return keyPairFactory.createPrivateKey(
- listWithCompressedFinalExponent, _elGamalPrivateKey.getGroup());
- };
- }
- ElGamalDecrypter.prototype = {
- /**
- * Decrypts a ciphertext.
- * <P>
- * The encrypted message parameter will be a list of group elements,
- * encapsulated within an ComputationValues object.
- * <P>
- * The length of the received ciphertext (number of group elements
- * contained within it) must be equal to, or less than, the length of
- * the private key of this decrypter. If this condition is not met, then
- * an exception will be thrown.
- *
- * @function decrypt
- *
- * @param {Array}
- * cipherText the encrypted message to be decrypted.
- * @param {Boolean}
- * [confirmGroupMembership] if true, a confirmation is made that
- * each element in
- * {@code ciphertext} is a member of the mathematical group
- * over which this decrypter operates. Default value is false.
- * @returns {Array} the decrypted ciphertext.
- */
- decrypt: function(cipherText, confirmGroupMembership) {
- if (confirmGroupMembership === true &&
- !this._areGroupMembers(cipherText)) {
- throw new exceptions.CryptoLibException(
- 'All values to decrypt must be group elements.');
- }
- this._validateCiphertextSize(cipherText);
- var privateKeyAfterCompression =
- this._compressKeyIfNecessary(cipherText.getPhis().length);
- var plaintext = [];
- var negatedExponent;
- var exponentsArray = privateKeyAfterCompression.getExponentsArray();
- for (var i = 0; i < cipherText.getPhis().length; i++) {
- // Compute the e = negate (-) of privKey[i]
- negatedExponent = exponentsArray[i].negate();
- // Compute dm[i]= gamma^(e) * phi[i]
- plaintext.push(cipherText.getGamma()
- .exponentiate(negatedExponent)
- .multiply(cipherText.getPhis()[i]));
- }
- return plaintext;
- }
- };
- /**
- * Defines an ElGamal decrypter that can be used to decrypt some ciphertext,
- * given the public key and the source of randomness used to generate the
- * ciphertext.
- *
- * @class ElGamalRandomDecrypter
- * @param {ElGamalPublicKey}
- * elGamalPublicKey The ElGamal public key.
- * @param {Object} cryptoRandomInteger The source of randomness.
- * @returns {ElGamalDecrypter} The ElGamal decrypter.
- */
- function ElGamalRandomDecrypter(elGamalPublicKey, cryptoRandomInteger) {
- function validateCorrectGroup(elGamalPublicKey) {
- var elementsArray = elGamalPublicKey.getGroupElementsArray();
- var group = elGamalPublicKey.getGroup();
- for (var i = 0; i < elementsArray.length; i++) {
- if (!(group.getP().equals(elementsArray[i].getP()))) {
- throw new exceptions.CryptoLibException(
- 'Each element must be of the specified group modulus.');
- }
- if (!(group.getQ().equals(elementsArray[i].getQ()))) {
- throw new exceptions.CryptoLibException(
- 'Each element must be of the specified group order.');
- }
- }
- }
- validateCorrectGroup(elGamalPublicKey);
- var _elGamalPublicKey = elGamalPublicKey;
- var _cryptoRandomInteger = cryptoRandomInteger;
- this.getElGamalPublicKey = function() {
- return _elGamalPublicKey;
- };
- this.getCryptoRandomInteger = function() {
- return _cryptoRandomInteger;
- };
- this._areGroupMembers = function(cipherText) {
- for (var i = 0; i < cipherText.getPhis().length; i++) {
- var next = cipherText.getPhis()[i];
- if (!(_elGamalPublicKey.getGroup().isGroupMember(next))) {
- return false;
- }
- }
- return true;
- };
- this._validateCiphertextSize = function(cipherText) {
- if (_elGamalPublicKey.getGroupElementsArray().length <
- cipherText.getPhis().length) {
- throw new exceptions.CryptoLibException(
- 'The list of ciphertext was larger than the number of public key elements.');
- }
- };
- this._compressKeyIfNecessary = function(numRequired) {
- var publicKeyElements = _elGamalPublicKey.getGroupElementsArray();
- var group = _elGamalPublicKey.getGroup();
- if (publicKeyElements.length <= numRequired) {
- return _elGamalPublicKey;
- }
- var listWithCompressedFinalElement =
- mathematical.groupUtils.buildListWithCompressedFinalElement(
- group, publicKeyElements, numRequired);
- return keyPairFactory.createPublicKey(
- listWithCompressedFinalElement, _elGamalPublicKey.getGroup());
- };
- }
- ElGamalRandomDecrypter.prototype = {
- /**
- * Decrypts a ciphertext, using the public key and the source of randomness
- * used to generate the ciphertext. <P> The encrypted message parameter will
- * be a list of group elements, encapsulated within an ComputationValues
- * object. <P> The length of the received ciphertext (number of group
- * elements contained within it) must be equal to, or less than, the length
- * of the public key of this decrypter. If this condition is not met, then
- * an exception will be thrown.
- *
- * @function decrypt
- *
- * @param {Array}
- * cipherText the encrypted message to be decrypted.
- * @param {Boolean}
- * [confirmGroupMembership] if true, a confirmation is made that
- * each element in
- * {@code ciphertext} is a member of the mathematical group
- * over which this decrypter operates. Default value is false.
- * @param {boolean}
- * [useShortExponent] set to true if a short exponent was used
- * for the encryption. Default value is false.
- * @returns {Array} the decrypted messages.
- */
- decrypt: function(cipherText, confirmGroupMembership, useShortExponent) {
- if (confirmGroupMembership === true &&
- !this._areGroupMembers(cipherText)) {
- throw new exceptions.CryptoLibException(
- 'All values to decrypt must be group elements.');
- }
- if (typeof useShortExponent === 'undefined') {
- useShortExponent = false;
- }
- this._validateCiphertextSize(cipherText);
- var publicKeyAfterCompression =
- this._compressKeyIfNecessary(cipherText.getPhis().length);
- var group = publicKeyAfterCompression.getGroup();
- var publicKeyElements = publicKeyAfterCompression.getGroupElementsArray();
- var plaintext = [];
- var negatedExponent;
- var randomExponent = mathematical.groupUtils.generateRandomExponent(
- group, this.getCryptoRandomInteger(), useShortExponent);
- negatedExponent = randomExponent.negate();
- for (var i = 0; i < cipherText.getPhis().length; i++) {
- // Compute dm[i]= publicKeyElement^(-e) * phi[i]
- plaintext.push(publicKeyElements[i]
- .exponentiate(negatedExponent)
- .multiply(cipherText.getPhis()[i]));
- }
- return plaintext;
- }
- };
- /**
- * Class which encapsulates an 'r' value (random exponent) and a set of
- * ElGamal encryption values (a gamma value and a list of phi values).
- *
- * @class ElGamalEncrypterValues
- * @param {Exponent}
- * exponent the Exponent to set.
- * @param {ZpGroupElement}
- * gamma the gamma (first element) of the ciphertext.
- * @param {Array}
- * phis the phi values of the ciphertext.
- * @returns {ElGamalEncrypterValues}
- */
- function ElGamalEncrypterValues(exponent, gamma, phis) {
- var _r = exponent;
- var _gamma = gamma;
- var _phis = phis;
- /**
- * @function
- *
- * @returns {Exponent}
- */
- this.getR = function() {
- return _r;
- };
- /**
- * @function
- *
- * @returns {ZpGroupElement}
- */
- this.getGamma = function() {
- return _gamma;
- };
- /**
- * @function
- *
- * @returns {Array}
- */
- this.getPhis = function() {
- return _phis;
- };
- this.getElGamalComputationValues = function() {
- return new box.homomorphic.cipher.ElGamalComputationValues(_gamma, _phis);
- };
- }
- box.homomorphic.cipher.ElGamalEncrypterValues = ElGamalEncrypterValues;
- /**
- * Encapsulates encryption parameters.
- * <p>
- * These parameters should have been generated as defined below:
- * <ul>
- * <li> For p and q:
- * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
- * <li> For g:
- * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
- * <li> For f:
- * http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
- * </ul>
- * <p>
- * Note that p, q, and g are received within the mathematical group.
- *
- *
- * @class EncryptionParameters
- * @param {ZpSubgroup}
- * group the group of the encryption parameters.
- *
- * @returns {EncryptionParameters}
- */
- box.homomorphic.cipher.EncryptionParameters = function(group) {
- var _group = group;
- /**
- * @function
- *
- * @returns {ZpSubgroup}
- */
- this.getEncParamGroup = function() {
- return _group;
- };
- };
- /**
- * Class which encapsulates a gamma and a set of phi values that are Zp
- * subgroup elements.
- *
- * @class ElGamalComputationValues
- * @param {ZpGroupElement}
- * gamma the gamma (first element) of the ciphertext.
- * @param {Array}
- * phis the phi values of the ciphertext.
- */
- box.homomorphic.cipher.ElGamalComputationValues = function(gamma, phis) {
- this._gamma = gamma;
- this._phis = phis;
- };
- box.homomorphic.cipher.ElGamalComputationValues.prototype = {
- getGamma: function() {
- return this._gamma;
- },
- getPhis: function() {
- return this._phis;
- },
- stringify: function() {
- var phis = Array();
- for (var i = 0; i < this._phis.length; i++) {
- phis[i] =
- converters.base64FromBigInteger(this._phis[i].getElementValue());
- }
- return JSON.stringify({
- ciphertext: {
- p: converters.base64FromBigInteger(this._gamma.getP()),
- q: converters.base64FromBigInteger(this._gamma.getQ()),
- gamma: converters.base64FromBigInteger(this._gamma.getElementValue()),
- phis: phis
- }
- });
- }
- };
- box.homomorphic.cipher.deserializeElGamalComputationValues = function(
- serializedObject) {
- var valuesJson = JSON.parse(serializedObject).ciphertext;
- var p = converters.base64ToBigInteger(valuesJson.p);
- var q = converters.base64ToBigInteger(valuesJson.q);
- var gamma = new mathematical.ZpGroupElement(
- converters.base64ToBigInteger(valuesJson.gamma), p, q);
- var phis = [];
- for (var i = 0; i < valuesJson.phis.length; i++) {
- phis.push(new mathematical.ZpGroupElement(
- converters.base64ToBigInteger(valuesJson.phis[i]), p, q));
- }
- return new box.homomorphic.cipher.ElGamalComputationValues(gamma, phis);
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
- cryptolib.modules.homomorphic.keypair = function(box) {
- 'use strict';
- box.homomorphic = box.homomorphic || {};
- box.homomorphic.keypair = {};
- /**
- * A submodule that holds ElGamal key pair functionalities.
- * @exports homomorphic/keypair/factory
- */
- box.homomorphic.keypair.factory = {};
- var converters;
- var mathematical;
- var f = function(box) {
- converters = new box.commons.utils.Converters();
- mathematical = box.commons.mathematical;
- };
- cryptolib('commons.exceptions', 'commons.utils', 'commons.mathematical', f);
- /** @class */
- box.homomorphic.keypair.factory.KeyFactory = function() {
- };
- box.homomorphic.keypair.factory.KeyFactory.prototype = {
- /**
- * @function
- * @returns ElGamalKeyPair
- */
- createKeyPair: function(elGamalPublicKey, elGamalPrivateKey) {
- return new ElGamalKeyPair(elGamalPublicKey, elGamalPrivateKey);
- },
- /**
- * @function
- * @returns ElGamalPublicKey
- */
- createPublicKey: function(
- serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup) {
- return new ElGamalPublicKey(
- serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup);
- },
- /**
- * @function
- * @returns ElGamalPrivateKey
- */
- createPrivateKey: function(
- serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup) {
- return new ElGamalPrivateKey(
- serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup);
- }
- };
- /**
- * Representation of an ElGamal key pair. This key pair is composed of a
- * private key and a public key.
- * @class ElGamalKeyPair
- * @param elGamalPublicKey
- * ElGamal public key.
- * @param elGamalPrivateKey
- * ElGamal private key.
- * @returns {ElGamalKeyPair}
- */
- function ElGamalKeyPair(elGamalPublicKey, elGamalPrivateKey) {
- var _elGamalPublicKey = elGamalPublicKey;
- var _elGamalPrivateKey = elGamalPrivateKey;
- this.getPublicKey = function() {
- return _elGamalPublicKey;
- };
- this.getPrivateKey = function() {
- return _elGamalPrivateKey;
- };
- }
- /**
- * Encapsulates an ElGamal public key.
- * <P>
- * This class includes the key itself (which is actually a list of
- * elements), as well as the mathematical group that this key belongs to.
- * @class ElGamalPublicKey
- * @param {String_or_Array} serializedElGamalPublicKeyB64OrListOfGroupElements
- * this parameter can be either a string containing the
- * serialized ElGamal public key to JSON string, or an array of
- * ZpGroupElement.
- * @param {ZpSubgroup} keyGroup
- * the ZpSubgroup of the public key.
- * @returns {ElGamalPublicKey}
- */
- function ElGamalPublicKey(
- serializedElGamalPublicKeyB64OrListOfGroupElements, keyGroup) {
- var _group;
- var _groupElementsArray = [];
- var _fromJson = function(serializedElGamalPublicKey) {
- var parsedPublicKey = JSON.parse(serializedElGamalPublicKey).publicKey;
- var p = converters.base64ToBigInteger(
- parsedPublicKey.zpSubgroup.p.toString());
- var q = converters.base64ToBigInteger(
- parsedPublicKey.zpSubgroup.q.toString());
- var generator = converters.base64ToBigInteger(
- parsedPublicKey.zpSubgroup.g.toString());
- _group = new mathematical.ZpSubgroup(generator, p, q);
- for (var i = 0; i < parsedPublicKey.elements.length; i++) {
- var elementValue =
- converters.base64ToBigInteger(parsedPublicKey.elements[i]);
- var element = new mathematical.ZpGroupElement(
- elementValue, _group.getP(), _group.getQ());
- _groupElementsArray.push(element);
- }
- };
- if (typeof keyGroup === 'undefined') {
- var serializedElGamalPublicKey = converters.base64Decode(
- serializedElGamalPublicKeyB64OrListOfGroupElements);
- _fromJson(serializedElGamalPublicKey);
- } else {
- _groupElementsArray = serializedElGamalPublicKeyB64OrListOfGroupElements;
- _group = keyGroup;
- }
- this.getGroup = function() {
- return _group;
- };
- this.getGroupElementsArray = function() {
- return _groupElementsArray;
- };
- }
- /**
- * Encapsulates an ElGamal private key.
- * <P>
- * This class includes the key itself (which is actually a list of
- * exponents), as well as the mathematical group that this key belongs to.
- * @class ElGamalPrivateKey
- * @param {String_or_Array} serializedElGamalPrivateKeyB64OrListOfExponents
- * this parameter can be either a string containing the
- * serialized to JSON string ElGamal private key
- * or an array of Exponents.
- * @param {ZpSubgroup} keyGroup
- * the ZpSubgroup of the private key.
- * @returns {ElGamalPrivateKey}
- */
- function ElGamalPrivateKey(
- serializedElGamalPrivateKeyB64OrListOfExponents, keyGroup) {
- var _group;
- var _exponentsArray = [];
- var _fromJson = function(serializedElGamalPrivateKey) {
- var parsedPrivateKey = JSON.parse(serializedElGamalPrivateKey).privateKey;
- var p = converters.base64ToBigInteger(
- parsedPrivateKey.zpSubgroup.p.toString());
- var q = converters.base64ToBigInteger(
- parsedPrivateKey.zpSubgroup.q.toString());
- var generator = converters.base64ToBigInteger(
- parsedPrivateKey.zpSubgroup.g.toString());
- _group = new mathematical.ZpSubgroup(generator, p, q);
- for (var i = 0; i < parsedPrivateKey.exponents.length; i++) {
- var exponentValue =
- converters.base64ToBigInteger(parsedPrivateKey.exponents[i]);
- var exponent = new mathematical.Exponent(_group.getQ(), exponentValue);
- _exponentsArray.push(exponent);
- }
- };
- if (typeof keyGroup === 'undefined') {
- var serializedElGamalPrivateKey = converters.base64Decode(
- serializedElGamalPrivateKeyB64OrListOfExponents);
- _fromJson(serializedElGamalPrivateKey);
- } else {
- _exponentsArray = serializedElGamalPrivateKeyB64OrListOfExponents;
- _group = keyGroup;
- }
- this.getGroup = function() {
- return _group;
- };
- this.getExponentsArray = function() {
- return _exponentsArray;
- };
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.homomorphic = cryptolib.modules.homomorphic || {};
- cryptolib.modules.homomorphic.service = function(box) {
- 'use strict';
- box.homomorphic = box.homomorphic || {};
- /**
- * A module that provides high-level ElGamal cryptographic services.
- *
- * @exports homomorphic/service
- */
- box.homomorphic.service = {};
- var elGamalFactory;
- var keyFactory;
- cryptolib('homomorphic.cipher', 'homomorphic.keypair', function(box) {
- elGamalFactory = new box.homomorphic.cipher.factory.ElGamalCipherFactory();
- keyFactory = new box.homomorphic.keypair.factory.KeyFactory();
- });
- /**
- * @function createElGamalKeyPair
- * @param elGamalPublicKey
- * {Object} an ElGamal public key.
- * @param elGamalPrivateKey
- * {Object} an ElGamal private key.
- *
- * @returns {Object} an object of ElGamalKeyPair.
- */
- box.homomorphic.service.createElGamalKeyPair = function(
- elGamalPublicKey, elGamalPrivateKey) {
- return keyFactory.createKeyPair(elGamalPublicKey, elGamalPrivateKey);
- };
- /**
- * @function createElGamalPublicKey
- * @param serializedElGamalPublicKeyB64
- * {String] a serialized ElGamalPublicKey, in base 64 encoded
- * format.
- *
- * @returns {Object} a ElGamalPublicKey, as an object.
- */
- box.homomorphic.service.createElGamalPublicKey = function(
- serializedElGamalPublicKeyB64) {
- return keyFactory.createPublicKey(serializedElGamalPublicKeyB64);
- };
- /**
- * @function createElGamalPrivateKey
- * @param serializedElGamalPrivateKeyB64
- * {String} a serialized ElGamalPrivateKey, in base 64 encoded
- * format.
- *
- * @returns {Object} a ElGamalPrivateKey, as an object.
- */
- box.homomorphic.service.createElGamalPrivateKey = function(
- serializedElGamalPrivateKeyB64) {
- return keyFactory.createPrivateKey(serializedElGamalPrivateKeyB64);
- };
- /**
- * @function createEncrypter
- * @param elGamalPublicKey
- * {Object} a public key, as an ElGamalPublicKey object.
- * @param [cryptoRandomInteger] {Object} an optional parameter to set the
- * source of randomness for the generation of the ElGamal encryption
- * exponent. If not provided, the source will be created internally.
- *
- * @returns {Object} an ElGamalEncrypter.
- */
- box.homomorphic.service.createEncrypter = function(
- elGamalPublicKey, cryptoRandomInteger) {
- return elGamalFactory.createEncrypter(
- elGamalPublicKey, cryptoRandomInteger);
- };
- /**
- * @function createDecrypter
- * @param elGamalPrivateKey
- * {Object} a private key, as an ElGamalPrivateKey object.
- *
- * @returns {Object} an ElGamalDecrypter.
- */
- box.homomorphic.service.createDecrypter = function(elGamalPrivateKey) {
- return elGamalFactory.createDecrypter(elGamalPrivateKey);
- };
- /**
- * @function createRandomDecrypter
- * @param elGamalPublicKey
- * {Object} a public key, as an ElGamalPublicKey object.
- * @param cryptoRandomInteger {Object} the
- * source of randomness for the generation of the ElGamal encryption
- * exponent.
- * @returns {Object} an ElGamalRandomDecrypter.
- */
- box.homomorphic.service.createRandomDecrypter = function(
- elGamalPublicKey, cryptoRandomInteger) {
- return elGamalFactory.createRandomDecrypter(
- elGamalPublicKey, cryptoRandomInteger);
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.primitives = cryptolib.modules.primitives || {};
- /** @namespace primitives/derivation */
- cryptolib.modules.primitives.derivation = function(box) {
- 'use strict';
- box.primitives = box.primitives || {};
- box.primitives.derivation = {};
- /**
- * A module that holds derivation functionalities.
- *
- * @exports primitives/derivation
- */
- box.primitives.derivation.factory = {};
- var policies = {
- pbkdf: {
- provider: box.policies.primitives.derivation.pbkdf.provider,
- hash: box.policies.primitives.derivation.pbkdf.hash,
- saltLengthBytes: box.policies.primitives.derivation.pbkdf.saltLengthBytes,
- keyLengthBytes: box.policies.primitives.derivation.pbkdf.keyLengthBytes,
- iterations: box.policies.primitives.derivation.pbkdf.iterations
- }
- };
- var exceptions, converters;
- cryptolib('rnd', 'commons', function(box) {
- exceptions = box.commons.exceptions;
- converters = new box.commons.utils.Converters();
- });
- /**
- * A factory class for generating {@link CryptoForgePBKDFSecretKeyGenerator}
- * objects.
- *
- * @class
- */
- box.primitives.derivation.factory.SecretKeyGeneratorFactory = function() {
- };
- box.primitives.derivation.factory.SecretKeyGeneratorFactory.prototype = {
- /**
- * Creates a generator for deriving passwords.
- *
- * @function
- * @returns {primitives/derivation.CryptoForgePBKDFSecretKeyGenerator} a
- * {@link primitives/derivation.CryptoForgePBKDFSecretKeyGenerator}
- * object.
- */
- createPBKDF: function() {
- var provider = policies.pbkdf.provider;
- try {
- if (provider === Config.primitives.derivation.pbkdf.provider.FORGE) {
- return new CryptoForgePBKDFSecretKeyGenerator();
- } else {
- throw new exceptions.CryptoLibException(
- 'The specified provider ' + provider + ' is not supported.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoPBKDFSecretKeyGenerator object could not be created.',
- error);
- }
- }
- };
- /**
- *
- * @class
- * @memberof primitives/derivation
- */
- function CryptoForgePBKDFSecretKeyGenerator() {
- validateHash(policies.pbkdf.hash);
- validateKeyLengthBytes(policies.pbkdf.keyLengthBytes);
- validateSaltLengthBytes(policies.pbkdf.saltLengthBytes);
- validateIterations(policies.pbkdf.iterations);
- this.keyLengthBytes = policies.pbkdf.keyLengthBytes;
- }
- CryptoForgePBKDFSecretKeyGenerator.prototype = {
- /**
- * @param {string}
- * password the password, as a string of bytes in Base64
- * encoded format.
- * @param {string}
- * salt the salt, as a string of bytes in Base64 encoded
- * format. Note that the salt length should coincide with the
- * one required by the hash algorithm.
- *
- * @return {string} the derived key, as a string of bytes in Base64
- * encoded format.
- */
- generateSecret: function(passwordB64, saltB64) {
- var password = converters.base64Decode(passwordB64);
- var salt = converters.base64Decode(saltB64);
- if (salt.length < policies.pbkdf.saltLengthBytes) {
- throw new exceptions.CryptoLibException(
- 'The salt byte length ' + salt.length +
- ' is less than the minimum allowed salt length ' +
- policies.pbkdf.saltLengthBytes +
- ' set by the cryptographic policy.');
- }
- var derivedKey = sjcl.misc.pbkdf2(
- password, sjcl.codec.base64.toBits(saltB64),
- policies.pbkdf.iterations, this.keyLengthBytes * 8,
- hashCallback(policies.pbkdf.hash));
- return sjcl.codec.base64.fromBits(derivedKey);
- }
- };
- function hashCallback(algorithm) {
- if (algorithm === Config.primitives.derivation.pbkdf.hash.SHA256) {
- return null;
- } else {
- throw new exceptions.CryptoLibException(
- 'Hash algorithm \'' + algorithm + '\' is unsupported');
- }
- }
- function validateHash(hash) {
- var supportedHashAlgorithms =
- [Config.primitives.derivation.pbkdf.hash.SHA256];
- if (supportedHashAlgorithms.indexOf(hash) < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified hash algorithm ' + hash +
- ' is not one of the supported options: ' + supportedHashAlgorithms);
- }
- }
- function validateSaltLengthBytes(saltLengthBytes) {
- var supportedSaltLengthBytes = [
- Config.primitives.derivation.pbkdf.saltLengthBytes.SL_20,
- Config.primitives.derivation.pbkdf.saltLengthBytes.SL_32
- ];
- if (typeof saltLengthBytes !== 'number' || saltLengthBytes % 1 !== 0 ||
- saltLengthBytes < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified salt byte length ' + saltLengthBytes +
- ' is not a positive integer.');
- }
- if (supportedSaltLengthBytes.indexOf(saltLengthBytes) < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified salt byte length ' + saltLengthBytes +
- ' is not one of the supported options: ' + supportedSaltLengthBytes);
- }
- }
- function validateKeyLengthBytes(keyLengthBytes) {
- var supportedKeyLengthBytes = [
- Config.primitives.derivation.pbkdf.keyLengthBytes.KL_16,
- Config.primitives.derivation.pbkdf.keyLengthBytes.KL_32
- ];
- if (typeof keyLengthBytes !== 'number' || keyLengthBytes % 1 !== 0 ||
- keyLengthBytes < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified key byte length ' + keyLengthBytes +
- ' is not a positive number.');
- }
- if (supportedKeyLengthBytes.indexOf(keyLengthBytes) < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified key byte length ' + keyLengthBytes +
- ' is not one of the supported options: ' + supportedKeyLengthBytes);
- }
- }
- function validateIterations(iterations) {
- var supportedIterations = [
- Config.primitives.derivation.pbkdf.iterations.I_1,
- Config.primitives.derivation.pbkdf.iterations.I_8000,
- Config.primitives.derivation.pbkdf.iterations.I_16000,
- Config.primitives.derivation.pbkdf.iterations.I_32000,
- Config.primitives.derivation.pbkdf.iterations.I_64000
- ];
- if (typeof iterations !== 'number' || iterations % 1 !== 0 ||
- iterations < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified number of iterations ' + iterations +
- ' is not a positive integer.');
- }
- if (supportedIterations.indexOf(iterations) < 0) {
- throw new exceptions.CryptoLibException(
- 'The specified number of iterations ' + iterations +
- ' is not one of the supported options: ' + supportedIterations);
- }
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.primitives = cryptolib.modules.primitives || {};
- /**
- * @namespace primitives/messagedigest
- */
- cryptolib.modules.primitives.messagedigest = function(box) {
- 'use strict';
- box.primitives = box.primitives || {};
- box.primitives.messagedigest = box.primitives.messagedigest || {};
- /**
- * A module that holds message digest functionalities.
- * @exports primitives/messagedigest
- */
- box.primitives.messagedigest.factory =
- box.primitives.messagedigest.factory || {};
- var policies = {
- messagedigest: {
- algorithm: box.policies.primitives.messagedigest.algorithm,
- provider: box.policies.primitives.messagedigest.provider
- }
- };
- var converters, exceptions;
- cryptolib('commons', function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- });
- /**
- * A factory class for creating a message digest generator and verifier.
- * @class
- */
- box.primitives.messagedigest.factory.MessageDigestFactory = function() {};
- box.primitives.messagedigest.factory.MessageDigestFactory.prototype = {
- /**
- * Gets a message dister object.
- * @function
- * @returns {primitives/messagedigest.CryptoForgeMessageDigest}
- */
- getCryptoMessageDigest: function() {
- try {
- if (policies.messagedigest.provider ===
- Config.primitives.messagedigest.provider.FORGE) {
- return this.getCryptoForgeMessageDigest();
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoSymmetricCipher could not be obtained.', error);
- }
- },
- getCryptoForgeMessageDigest: function() {
- return new CryptoForgeMessageDigest();
- }
- };
- /**
- * Defines a message digest hash function.
- * @class
- * @memberof primitives/messagedigest
- */
- function CryptoForgeMessageDigest() {
- this.digester = null;
- try {
- if (policies.messagedigest.algorithm ===
- Config.primitives.messagedigest.algorithm.SHA256) {
- this.digester = forge.md.sha256.create();
- } else if (
- policies.messagedigest.algorithm ===
- Config.primitives.messagedigest.algorithm.SHA512_224) {
- this.digester = forge.md.sha512.sha224.create();
- } else {
- var errorMessage = 'Message digester type \'' +
- policies.messagedigest.algorithm +
- '\' not recognized by CryptoForgeMessageDigest.';
- throw new exceptions.CryptoLibException(errorMessage);
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoForgeMessageDigest could not be created.', error);
- }
- }
- CryptoForgeMessageDigest.prototype = {
- /**
- * Initializes the message digest generator.
- * @function
- */
- start: function() {
- try {
- this.digester.start();
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Message digest could not be initialized.', error);
- }
- },
- /**
- * Updates the message digest generator.
- * @function
- * @param {Array} arrayDataBase64
- * data to compute the hash, as an array of string in Base64
- * encoded format.
- */
- update: function(arrayDataBase64) {
- try {
- if (!arrayDataBase64 || arrayDataBase64.length < 1) {
- throw new exceptions.CryptoLibException(
- 'The array of data in Base64 should contain at least one element.');
- }
- for (var i = 0; i < arrayDataBase64.length; i++) {
- this.digester.update(converters.base64Decode(arrayDataBase64[i]));
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Message digest could not be updated.', error);
- }
- },
- /**
- * Generates the message digest for the updated data.
- * @function
- * @returns {string} Message digest, as string in Base64 encoded format.
- */
- digest: function() {
- try {
- var messageDigest = this.digester.digest();
- var rawOutput = messageDigest.getBytes();
- var encodedOutput = converters.base64Encode(rawOutput);
- return encodedOutput;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Message digest could not be generated.', error);
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.primitives = cryptolib.modules.primitives || {};
- /**
- * @namespace primitives/securerandom
- */
- cryptolib.modules.primitives.securerandom = function(box) {
- 'use strict';
- box.primitives = box.primitives || {};
- box.primitives.securerandom = {};
- /**
- * A module that holds secure random functionalities.
- *
- * @exports primitives/securerandom
- */
- box.primitives.securerandom.factory = {};
- var policies = {
- secureRandom: {provider: box.policies.primitives.secureRandom.provider}
- };
- var converters, exceptions;
- cryptolib('commons', function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- });
- /**
- * A factory class for creating random generators.
- *
- * @class
- */
- box.primitives.securerandom.factory.SecureRandomFactory = function() {
- };
- box.primitives.securerandom.factory.SecureRandomFactory.prototype = {
- /**
- * Instantiates a random byte generator.
- *
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomBytes}
- */
- getCryptoRandomBytes: function() {
- try {
- if (policies.secureRandom.provider ===
- Config.primitives.secureRandom.provider.SCYTL) {
- return this.getCryptoScytlRandomBytes();
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoRandomBytes could not be obtained.', error);
- }
- },
- /**
- * Instantiates a Scytl random byte generator.
- *
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomBytes}
- */
- getCryptoScytlRandomBytes: function() {
- return new CryptoScytlRandomBytes();
- },
- /**
- * Instantiates a random integer generator.
- *
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomBytes}
- */
- getCryptoRandomInteger: function() {
- try {
- if (policies.secureRandom.provider ===
- Config.primitives.secureRandom.provider.SCYTL) {
- return this.getCryptoScytlRandomInteger();
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoRandomBytes could not be obtained.', error);
- }
- },
- /**
- * Instantiates a Scytl random integer generator.
- *
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomBytes}
- */
- getCryptoScytlRandomInteger: function() {
- return new CryptoScytlRandomInteger();
- }
- };
- var validate = function(length) {
- try {
- if (typeof length !== 'number') {
- throw new exceptions.CryptoLibException(
- 'The given length is not a number');
- }
- if (length < 1) {
- throw new exceptions.CryptoLibException(
- 'The given length should be a strictly positive integer.');
- }
- if (length > box.MAXIMUM_LENGTH_TO_GENERATE_DATA) {
- throw new exceptions.CryptoLibException(
- 'The given length should be lower than or equal to ' +
- box.MAXIMUM_LENGTH_TO_GENERATE_DATA);
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Random generation failed.', error);
- }
- };
- /**
- * The SCYTL Bytes Random Generator
- *
- * @class
- * @memberof primitives/securerandom
- */
- function CryptoScytlRandomBytes() {}
- CryptoScytlRandomBytes.prototype = {
- /**
- * Generates secure random bytes.
- *
- * @function
- * @param {number}
- * numBytes number of bytes to be generated..
- * @returns {string} secure random string.
- */
- nextRandom: function(length) {
- validate(length);
- var randomBytes = box.prng.generate(length);
- return randomBytes.toString();
- },
- /**
- * Method to be compliant with the Forge library.
- *
- * @function
- * @param {number}
- * numBytes number of bytes to be generated..
- * @returns {string} secure random string.
- */
- getBytesSync: function(length) {
- return this.nextRandom(length);
- }
- };
- /**
- * The SCYTL Integer Random Generator
- *
- * @class
- * @memberof primitives/securerandom
- */
- function CryptoScytlRandomInteger() {}
- CryptoScytlRandomInteger.prototype = {
- /**
- * Generates a secure random big integer (Forge).
- *
- * @function
- * @params {number} length the bit length of the random integer.
- * @returns {object} secure random big integer.
- */
- nextRandom: function(length) {
- validate(length);
- var n = ((new box.forge.jsbn.BigInteger('10')).pow(length))
- .subtract(box.forge.jsbn.BigInteger.ONE);
- var bitLength = n.bitLength();
- var numberOfBytes = bitLength / box.NUMBER_OF_BITS_PER_BYTE;
- numberOfBytes = Math.floor(numberOfBytes);
- var modBytes = bitLength % box.NUMBER_OF_BITS_PER_BYTE;
- if (modBytes !== 0) {
- numberOfBytes++;
- }
- var generatedInteger;
- do {
- var randomBytes = box.prng.generate(numberOfBytes);
- randomBytes = '\x00' + randomBytes;
- randomBytes = converters.bytesFromString(randomBytes);
- generatedInteger = new box.forge.jsbn.BigInteger(randomBytes);
- } while ((generatedInteger.compareTo(forge.jsbn.BigInteger.ZERO) <= 0) ||
- (generatedInteger.compareTo(n) > 0));
- return generatedInteger;
- },
- /**
- * Generates a secure random big integer according to the specified bit
- * length.
- *
- * @function
- * @params {number} bitsLength the bit length of the random integer.
- * @returns {object} Secure random big integer.
- */
- nextRandomByBits: function(bitsLength) {
- var byteLength = Math.ceil(bitsLength / box.NUMBER_OF_BITS_PER_BYTE);
- var modBytes = box.NUMBER_OF_BITS_PER_BYTE -
- (bitsLength % box.NUMBER_OF_BITS_PER_BYTE);
- var randomBytes = box.prng.generate(byteLength);
- randomBytes = '\x00' + randomBytes;
- randomBytes = converters.bytesFromString(randomBytes);
- var generatedInteger = new box.forge.jsbn.BigInteger(randomBytes);
- generatedInteger = generatedInteger.shiftRight(modBytes);
- return generatedInteger;
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.primitives = cryptolib.modules.primitives || {};
- /**
- * Defines primitives services.
- * @namespace primitives/service
- */
- cryptolib.modules.primitives.service = function(box) {
- 'use strict';
- box.primitives = box.primitives || {};
- /**
- * A module that holds primitives API.
- * @exports primitives/service
- */
- box.primitives.service = {};
- var securerandomFactory, messageDigestFactory, secretKeyGeneratorFactory;
- cryptolib(
- 'primitives.securerandom', 'commons.exceptions',
- 'primitives.messagedigest', 'primitives.derivation', function(box) {
- securerandomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- messageDigestFactory =
- new box.primitives.messagedigest.factory.MessageDigestFactory();
- secretKeyGeneratorFactory =
- new box.primitives.derivation.factory.SecretKeyGeneratorFactory();
- });
- /**
- * Provides a random bytes generator.
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomBytes} a CryptoRandomBytes object.
- */
- box.primitives.service.getCryptoRandomBytes = function() {
- return securerandomFactory.getCryptoRandomBytes();
- };
- /**
- * Provides a random integer generator.
- * @function
- * @returns {primitives/securerandom.CryptoScytlRandomInteger} a CryptoRandomInteger object.
- */
- box.primitives.service.getCryptoRandomInteger = function() {
- return securerandomFactory.getCryptoRandomInteger();
- };
- /**
- * Generates a hash for the given data.
- * @function
- * @parameter {array} ArrayDataBase64 the input data for the hash.
- * @returns {string} the hash, as a string in Base64 encoded format.
- */
- box.primitives.service.getHash = function(ArrayDataBase64) {
- var hashFunction = messageDigestFactory.getCryptoMessageDigest();
- hashFunction.start();
- hashFunction.update(ArrayDataBase64);
- return hashFunction.digest();
- };
- /**
- * Provides a derived secret key generator.
- * @function
- * @returns {primitives/derivation.CryptoForgePBKDFSecretKeyGenerator} a the pbkdf Generator.
- */
- box.primitives.service.getPbkdfSecretKeyGenerator = function() {
- return secretKeyGeneratorFactory.createPBKDF();
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules = cryptolib.modules || {};
- cryptolib.modules.proofs = cryptolib.modules.proofs || {};
- /**
- * Defines Zero-Knowledge Proofs (ZKPs).
- */
- cryptolib.modules.proofs.implementation = function(box) {
- 'use strict';
- box.proofs = box.proofs || {};
- var exceptions, mathematical, utils, converters, secureRandomFactory,
- messageDigestFactory;
- var f = function(box) {
- exceptions = box.commons.exceptions;
- mathematical = box.commons.mathematical;
- utils = box.commons.utils;
- converters = new box.commons.utils.Converters();
- secureRandomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- messageDigestFactory =
- new box.primitives.messagedigest.factory.MessageDigestFactory();
- };
- f.policies = {
- primitives: {
- messagedigest: {
- algorithm: box.policies.proofs.messagedigest.algorithm,
- provider: box.policies.proofs.messagedigest.provider
- },
- secureRandom: {provider: box.policies.proofs.secureRandom.provider}
- }
- };
- cryptolib(
- 'commons.exceptions', 'commons.mathematical', 'primitives.messagedigest',
- 'commons.utils', 'primitives.securerandom', f);
- /**
- * Schnorr proof generator.
- */
- box.proofs.SchnorrProofGenerator = function(voterID, electionID, group) {
- checkNotEmpty('voter ID', voterID);
- checkNotEmpty('election ID', electionID);
- checkDefined('group', group);
- var computationRules = [[[1, 1]]];
- var _voterID = voterID;
- var _electionID = electionID;
- var _progressMeter;
- var _numOutputs = 1;
- var buildListOfBaseElements = function() {
- var baseElements = [];
- baseElements.push(group.getGenerator());
- return baseElements;
- };
- var phiFunctionSchnorr = new box.proofs.PhiFunction(
- group, 1, _numOutputs, buildListOfBaseElements(), computationRules);
- var _prover = new box.proofs.Prover(group, phiFunctionSchnorr);
- this._buildListPublicValues = function(exponentiatedElement) {
- var publicList = [];
- publicList.push(exponentiatedElement);
- return publicList;
- };
- this._getProver = function() {
- return _prover;
- };
- this._buildListExponents = function(witness) {
- var exponentList = [];
- exponentList.push(witness);
- return exponentList;
- };
- this._buildDataString = function() {
- return 'SchnorrProof:VoterID=' + _voterID +
- 'ElectionEventID=' + _electionID;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.SchnorrProofGenerator.prototype = {
- preCompute: function() {
- return this._getProver().preCompute(1, this._getProgressMeter());
- },
- generate: function(exponentiatedElement, witness, preComputedValues) {
- checkDefined('exponentiated element', exponentiatedElement);
- checkDefined('witness', witness);
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this._getProver().prove(
- this._buildListPublicValues(exponentiatedElement),
- this._buildListExponents(witness), this._buildDataString(),
- preComputedValues);
- }
- };
- /**
- * Exponentiation proof generator.
- */
- box.proofs.ExponentiationProofGenerator = function(baseElements, group) {
- checkDefined('base elements', baseElements);
- checkDefined('group', group);
- var buildComputationRules = function(k) {
- var rules = [];
- for (var i = 0; i < k; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- }
- return rules;
- };
- var _numOutputs = baseElements.length;
- var phiFunctionExponentiation = new box.proofs.PhiFunction(
- group, 1, _numOutputs, baseElements,
- buildComputationRules(_numOutputs));
- var _prover = new box.proofs.Prover(group, phiFunctionExponentiation);
- var _progressMeter;
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- this.check = function(exponentiatedElements) {
- if (exponentiatedElements.length !== _numOutputs) {
- throw new exceptions.CryptoLibException(
- 'The number of exponentiated elements must be equal to the number of base elements');
- }
- };
- this._getProver = function() {
- return _prover;
- };
- };
- box.proofs.ExponentiationProofGenerator.prototype = {
- preCompute: function() {
- var EXPONENT_QUANTITY = 1;
- return this._getProver().preCompute(
- EXPONENT_QUANTITY, this._getProgressMeter());
- },
- generate: function(exponentiatedElements, exponent, preComputedValues) {
- checkDefined('exponentiatedElements', exponentiatedElements);
- checkDefined('exponent', exponent);
- this.check(exponentiatedElements);
- var exponents = [];
- exponents.push(exponent);
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this._getProver().prove(
- exponentiatedElements, exponents,
- box.EXPONENTIATION_PROOF_AUXILIARY_DATA, preComputedValues);
- }
- };
- /**
- * Plaintext proof generator.
- */
- box.proofs.PlaintextProofGenerator = function(publicKey, group) {
- checkDefined('public key', publicKey);
- checkDefined('group', group);
- var buildListOfBaseElements = function() {
- var list = [];
- list.push(group.getGenerator());
- list.addAll(publicKey.getGroupElementsArray());
- return list;
- };
- var buildComputationRules = function(k) {
- var rules = [];
- for (var i = 0; i < (k + 1); i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- }
- return rules;
- };
- var _publicKeyLength = publicKey.getGroupElementsArray().length;
- var numOutputs = _publicKeyLength + 1;
- var phiFunctionPlaintext = new box.proofs.PhiFunction(
- group, 1, numOutputs, buildListOfBaseElements(),
- buildComputationRules(_publicKeyLength));
- var _prover = new box.proofs.Prover(group, phiFunctionPlaintext);
- var _progressMeter;
- this._buildListPublicValues = function(ciphertext, plaintext) {
- var dividedCiphertext =
- mathematical.groupUtils.divide(ciphertext.getPhis(), plaintext);
- var publicValues = [];
- publicValues.push(ciphertext.getGamma());
- publicValues.addAll(dividedCiphertext);
- return publicValues;
- };
- this._getPublicKeyLength = function() {
- return _publicKeyLength;
- };
- this._getProver = function() {
- return _prover;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _publicKeyLength + 1, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.PlaintextProofGenerator.prototype = {
- preCompute: function() {
- return this._getProver().preCompute(1, this._getProgressMeter());
- },
- generate: function(ciphertext, plaintext, witness, preComputedValues) {
- checkDefined('ciphertext', ciphertext);
- checkDefined('plaintext', plaintext);
- checkDefined('witness', witness);
- var publicKeyLength = this._getPublicKeyLength();
- var numPhis = ciphertext.getPhis().length;
- if (publicKeyLength !== numPhis) {
- throw new exceptions.CryptoLibException(
- 'The length of the ciphertext must be equal to the length of the public key + 1.');
- }
- if (publicKeyLength !== plaintext.length) {
- throw new exceptions.CryptoLibException(
- 'The public key and the plaintext must have the same number of elements');
- }
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- var exponents = [];
- exponents.push(witness);
- return this._getProver().prove(
- this._buildListPublicValues(ciphertext, plaintext), exponents,
- box.PLAINTEXT_PROOF_AUXILIARY_DATA, preComputedValues);
- }
- };
- /**
- * Simple plaintext equality proof generator.
- */
- box.proofs.SimplePlaintextEqualityProofGenerator = function(
- primaryPublicKey, secondaryPublicKey, group) {
- checkDefined('primary public key', primaryPublicKey);
- checkDefined('secondary public key', secondaryPublicKey);
- checkDefined('group', group);
- var _primaryPublicKey = primaryPublicKey;
- var _secondaryPublicKey = secondaryPublicKey;
- var _group = group;
- var buildComputationRules = function(k) {
- var rules = [];
- var firstDimensionLength = k + 1;
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- for (var i = 1; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][1] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- rules[i][1].push(i + 1 + k);
- rules[i][1].push(1);
- }
- return rules;
- };
- var buildSecondaryInvertedPublicKey = function() {
- var listInvertedElements = [];
- var keys = _secondaryPublicKey.getGroupElementsArray();
- for (var i = 0; i < keys.length; i++) {
- listInvertedElements.push(keys[i].invert());
- }
- return listInvertedElements;
- };
- var buildListOfBaseElements = function() {
- var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
- var baseElements = [];
- baseElements.push(group.getGenerator());
- baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
- baseElements.addAll(invertedSecondaryKeyValues);
- return baseElements;
- };
- var primaryPublicKeyLength =
- primaryPublicKey.getGroupElementsArray().length;
- var secondaryPublicKeyLength =
- secondaryPublicKey.getGroupElementsArray().length;
- if (primaryPublicKeyLength !== secondaryPublicKeyLength) {
- throw new exceptions.CryptoLibException(
- 'The number of elements in the primary and secondary public keys must be equal');
- }
- var _progressMeter;
- var _numKeyElements = primaryPublicKey.getGroupElementsArray().length;
- var numOutputs = _numKeyElements + 1;
- var rules = buildComputationRules(_numKeyElements);
- var phiFunctionSimplePlaintextEquality = new box.proofs.PhiFunction(
- group, 1, numOutputs, buildListOfBaseElements(), rules);
- var _prover =
- new box.proofs.Prover(_group, phiFunctionSimplePlaintextEquality);
- this._buildListExponents = function(witness) {
- var exponentList = [];
- exponentList.push(witness);
- return exponentList;
- };
- this._buildInputList = function(primaryCiphertext, secondaryCiphertext) {
- var dividedSubCiphertext = mathematical.groupUtils.divide(
- primaryCiphertext.getPhis(), secondaryCiphertext.getPhis());
- var generatedList = [];
- generatedList.push(secondaryCiphertext.getGamma());
- generatedList.addAll(dividedSubCiphertext);
- return generatedList;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numKeyElements * 2 + 1, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- this._getProver = function() {
- return _prover;
- };
- this._check = function(primaryCiphertextLength) {
- if (primaryCiphertextLength !== (primaryPublicKeyLength + 1)) {
- throw new exceptions.CryptoLibException(
- 'The number of elements in the ciphertext must be equal to the number in the public key + 1');
- }
- };
- };
- box.proofs.SimplePlaintextEqualityProofGenerator.prototype = {
- preCompute: function() {
- return this._getProver().preCompute(1, this._getProgressMeter());
- },
- generate: function(
- primaryCiphertext, secondaryCiphertext, witness, preComputedValues) {
- checkDefined('primary ciphertext', primaryCiphertext);
- checkDefined('secondary ciphertext', secondaryCiphertext);
- checkDefined('witness', witness);
- var primaryCiphertextLength = primaryCiphertext.getPhis().length + 1;
- var secondaryCiphertextLength = secondaryCiphertext.getPhis().length + 1;
- if (primaryCiphertextLength !== secondaryCiphertextLength) {
- throw new exceptions.CryptoLibException(
- 'The number of elements in the primary and secondary ciphertext must be equal');
- }
- this._check(primaryCiphertextLength);
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this._getProver().prove(
- this._buildInputList(primaryCiphertext, secondaryCiphertext),
- this._buildListExponents(witness),
- box.SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
- preComputedValues);
- }
- };
- /**
- * Plaintext equality proof generator.
- */
- box.proofs.PlaintextEqualityProofGenerator = function(
- primaryPublicKey, secondaryPublicKey, group) {
- checkDefined('primary public key', primaryPublicKey);
- checkDefined('secondary public key', secondaryPublicKey);
- checkDefined('group', group);
- var numPrimaryPublicKeyElements =
- primaryPublicKey.getGroupElementsArray().length;
- var numSecondaryPublicKeyElements =
- secondaryPublicKey.getGroupElementsArray().length;
- if (numPrimaryPublicKeyElements !== numSecondaryPublicKeyElements) {
- throw new exceptions.CryptoLibException(
- 'The primary and secondary public keys contain different numbers of elements: ' +
- numPrimaryPublicKeyElements + ', ' + numSecondaryPublicKeyElements);
- }
- var _primaryPublicKey = primaryPublicKey;
- var _secondaryPublicKey = secondaryPublicKey;
- var _group = group;
- var _progressMeter;
- this._buildListExponents = function(primaryWitness, secondaryWitness) {
- var exponentList = [];
- exponentList.push(primaryWitness);
- exponentList.push(secondaryWitness);
- return exponentList;
- };
- this._buildInputList = function(primaryCiphertext, secondaryCiphertext) {
- var dividedSubCiphertext = mathematical.groupUtils.divide(
- primaryCiphertext.getPhis(), secondaryCiphertext.getPhis());
- var generatedList = [];
- generatedList.push(primaryCiphertext.getGamma());
- generatedList.push(secondaryCiphertext.getGamma());
- generatedList.addAll(dividedSubCiphertext);
- return generatedList;
- };
- function buildComputationRules(k) {
- var firstDimensionLength = k + 2;
- var rules = [];
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- rules[1] = [];
- rules[1][0] = [];
- rules[1][0].push(1);
- rules[1][0].push(2);
- for (var i = 2; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(i);
- rules[i][0].push(1);
- rules[i][1] = [];
- rules[i][1].push(i + k);
- rules[i][1].push(2);
- }
- return rules;
- }
- function buildListOfBaseElements() {
- var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
- var baseElements = [];
- baseElements.push(group.getGenerator());
- baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
- baseElements.addAll(invertedSecondaryKeyValues);
- return baseElements;
- }
- function buildSecondaryInvertedPublicKey() {
- var listInvertedElements = [];
- var keys = _secondaryPublicKey.getGroupElementsArray();
- for (var i = 0; i < keys.length; i++) {
- listInvertedElements.push(keys[i].invert());
- }
- return listInvertedElements;
- }
- var numKeyElements = primaryPublicKey.getGroupElementsArray().length;
- var _numOutputs = numKeyElements + 2;
- var rules = buildComputationRules(numKeyElements);
- var phiFunctionPlaintextEquality = new box.proofs.PhiFunction(
- group, 2, _numOutputs, buildListOfBaseElements(), rules);
- var _prover = new box.proofs.Prover(group, phiFunctionPlaintextEquality);
- this.getPrimaryPublicKey = function() {
- return _primaryPublicKey;
- };
- this.getSecondaryPublicKey = function() {
- return _secondaryPublicKey;
- };
- this.getGroup = function() {
- return _group;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- numKeyElements * 2 + 2, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- this._getProver = function() {
- return _prover;
- };
- this.check = function(numPrimaryCiphertextElements) {
- if (numPrimaryCiphertextElements !== (numPrimaryPublicKeyElements + 1)) {
- throw new exceptions.CryptoLibException(
- 'The number of ciphertext elements is not equal to the number public key elements plus one.');
- }
- };
- };
- box.proofs.PlaintextEqualityProofGenerator.prototype = {
- preCompute: function() {
- return this._getProver().preCompute(2, this._getProgressMeter());
- },
- generate: function(
- primaryCiphertext, primaryWitness, secondaryCiphertext,
- secondaryWitness, preComputedValues) {
- checkDefined('primary ciphertext', primaryCiphertext);
- checkDefined('primary witness', primaryWitness);
- checkDefined('secondary ciphertext', secondaryCiphertext);
- checkDefined('secondary witness', secondaryWitness);
- var numPrimaryCiphertextElements = primaryCiphertext.getPhis().length + 1;
- var numSecondaryCiphertextElements =
- secondaryCiphertext.getPhis().length + 1;
- if (numPrimaryCiphertextElements !== numSecondaryCiphertextElements) {
- throw new exceptions.CryptoLibException(
- 'The primary and secondary ciphertexts contain different numbers of elements: ' +
- numPrimaryCiphertextElements + ', ' +
- numSecondaryCiphertextElements);
- }
- this.check(numPrimaryCiphertextElements);
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this._getProver().prove(
- this._buildInputList(primaryCiphertext, secondaryCiphertext),
- this._buildListExponents(primaryWitness, secondaryWitness),
- box.PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA, preComputedValues);
- }
- };
- /**
- * Plaintext exponent equality proof generator.
- */
- box.proofs.PlaintextExponentEqualityProofGenerator = function(
- baseElements, group) {
- var buildComputationRules = function(k) {
- var rules = [];
- var firstDimensionLength = k + 1;
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- for (var i = 1; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][1] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- rules[i][1].push(i + 1 + k);
- rules[i][1].push(2);
- }
- return rules;
- };
- checkDefined('base elements', baseElements);
- checkDefined('group', group);
- var _numBaseElements = baseElements.length;
- var _progressMeter;
- var k = (_numBaseElements - 1) / 2;
- var numOutputs = k + 1;
- var phiFunctionPlaintextExponentEquality = new box.proofs.PhiFunction(
- group, 2, numOutputs, baseElements, buildComputationRules(k));
- var _prover =
- new box.proofs.Prover(group, phiFunctionPlaintextExponentEquality);
- this._buildListExponents = function(witness1, witness2) {
- var exponentList = [];
- exponentList.push(witness1);
- exponentList.push(witness2);
- return exponentList;
- };
- this._buildListPublicValues = function(ciphertext) {
- var list = [];
- list.push(ciphertext.getGamma());
- list.addAll(ciphertext.getPhis());
- return list;
- };
- this._getProver = function() {
- return _prover;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numBaseElements, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- this._checkLengthOf = function(ciphertext) {
- var k = ciphertext.getPhis().length;
- var expectedNumBaseElements = (2 * k) + 1;
- if (_numBaseElements !== expectedNumBaseElements) {
- throw new exceptions.CryptoLibException(
- 'The lengths of the ciphertext and the base elements do not have the expected relationship.');
- }
- };
- };
- box.proofs.PlaintextExponentEqualityProofGenerator.prototype = {
- preCompute: function() {
- return this._getProver().preCompute(2, this._getProgressMeter());
- },
- generate: function(ciphertext, witness1, witness2, preComputedValues) {
- checkDefined('ciphertext', ciphertext);
- checkDefined('witness1', witness1);
- checkDefined('witness2', witness2);
- this._checkLengthOf(ciphertext);
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this._getProver().prove(
- this._buildListPublicValues(ciphertext),
- this._buildListExponents(witness1, witness2),
- box.PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA,
- preComputedValues);
- }
- };
- /**
- * OR-proof generator.
- */
- box.proofs.ORProofGenerator = function(publicKey, numElements, group) {
- checkPublicKey(publicKey);
- checkNumElements(numElements);
- checkGroup(group);
- var _publicKey = publicKey;
- var _numElements = numElements;
- var _group = group;
- var _numOutputs = _numElements * 2;
- var _progressMeter;
- function checkPublicKey(publicKey) {
- checkDefined('public key', publicKey);
- checkNotNull('public key', publicKey);
- var publicKeyLength = publicKey.getGroupElementsArray().length;
- if (publicKeyLength !== 1) {
- throw new exceptions.CryptoLibException(
- 'Expected public key length: 1 ; Found: ' + publicKeyLength);
- }
- }
- function checkNumElements(numElements) {
- checkDefined('numElements', numElements);
- checkNotNull('numElements', numElements);
- if (numElements < 2) {
- throw new exceptions.CryptoLibException(
- 'Expected number of elements to be greater than 1 ; Found: ' +
- numElements);
- }
- }
- function checkGroup(group) {
- checkDefined('group', group);
- checkNotNull('group', group);
- }
- function buildBaseElements() {
- var baseElements = [];
- baseElements.push(_group.getGenerator());
- baseElements.push(_publicKey.getGroupElementsArray()[0]);
- return baseElements;
- }
- function buildComputationRules(numOutputs) {
- var rules = [];
- var index1;
- var index2 = 0;
- for (var i = 0; i < numOutputs; i++) {
- index1 = 1 + (i % 2);
- if (i % 2 === 0) {
- index2++;
- }
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(index1);
- rules[i][0].push(index2);
- }
- return rules;
- }
- var phiFunctionOR = new box.proofs.PhiFunction(
- group, _numElements, _numOutputs, buildBaseElements(),
- buildComputationRules(_numOutputs));
- var _prover = new box.proofs.Prover(_group, phiFunctionOR);
- this.getNumElements = function() {
- return _numElements;
- };
- this.getProver = function() {
- return _prover;
- };
- this.buildPublicValues = function(ciphertext) {
- var publicValues = [];
- publicValues.push(ciphertext.getGamma());
- publicValues.push(ciphertext.getPhis()[0]);
- return publicValues;
- };
- this.getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.ORProofGenerator.prototype = {
- preCompute: function() {
- return this.getProver().preCompute(
- this.getNumElements(), this.getProgressMeter());
- },
- generate: function(
- ciphertext, witness, elements, index, data, preComputedValues) {
- checkCiphertext(ciphertext);
- checkWitness(witness);
- checkElements(elements, this.getNumElements());
- checkIndex(index, this.getNumElements());
- checkDefined('data', data);
- function checkCiphertext(ciphertext) {
- checkDefined('ciphertext', ciphertext);
- checkNotNull('ciphertext', ciphertext);
- var ciphertextLength = ciphertext.getPhis().length + 1;
- if (ciphertextLength !== 2) {
- throw new exceptions.CryptoLibException(
- 'Expected ciphertext length: 2 ; Found: ' + ciphertextLength);
- }
- }
- function checkWitness(witness) {
- checkDefined('witness', witness);
- checkNotNull('witness', witness);
- }
- function checkElements(elements, numElementsExpected) {
- checkDefined('elements', elements);
- checkNotNull('elements', elements);
- var numElementsFound = elements.length;
- if (numElementsFound !== numElementsExpected) {
- throw new exceptions.CryptoLibException(
- 'Expected number of elements: ' + numElementsExpected +
- ' ; Found: ' + numElementsFound);
- }
- }
- function checkIndex(index, numElements) {
- checkDefined('index', index);
- checkNotNull('index', index);
- if (index < 0) {
- throw new exceptions.CryptoLibException(
- 'Expected index of encrypted element to be positive ; Found: ' +
- index);
- }
- if (index >= numElements) {
- throw new exceptions.CryptoLibException(
- 'Expected index of encrypted element to be less than number of elements: ' +
- numElements + ' ; Found: ' + index);
- }
- }
- var publicValues = this.buildPublicValues(ciphertext);
- var privateValues = [];
- privateValues.push(witness);
- if (data === null) {
- data = '';
- }
- if (!preComputedValues) {
- preComputedValues = this.preCompute();
- }
- return this.getProver().prove(
- publicValues, privateValues, data, preComputedValues, elements,
- index);
- }
- };
- /**
- * Schnorr proof verifier.
- */
- box.proofs.SchnorrProofVerifier = function(
- exponentiatedElement, voterID, electionID, proof, group) {
- checkDefined('exponentiated element', exponentiatedElement);
- checkNotEmpty('voter ID', voterID);
- checkNotEmpty('election ID', electionID);
- checkDefined('proof', proof);
- checkDefined('group', group);
- var _exponentiatedElement = exponentiatedElement;
- var _voterID = voterID;
- var _electionID = electionID;
- var _proof = proof;
- var _group = group;
- var _progressMeter;
- this._buildListOfBaseElements = function() {
- var baseElements = [];
- baseElements.push(_group.getGenerator());
- return baseElements;
- };
- this._buildExponentiatedElementsList = function() {
- var exponentiatedElements = [];
- exponentiatedElements.push(_exponentiatedElement);
- return exponentiatedElements;
- };
- this._buildDataString = function() {
- return 'SchnorrProof:VoterID=' + _voterID +
- 'ElectionEventID=' + _electionID;
- };
- var computationRules = [[[1, 1]]];
- var _numOutputs = 1;
- var phiFunction = new box.proofs.PhiFunction(
- _group, 1, _numOutputs, this._buildListOfBaseElements(),
- computationRules);
- var _verifier = new box.proofs.Verifier(_group, phiFunction);
- this._getProof = function() {
- return _proof;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.SchnorrProofVerifier.prototype = {
- verify: function() {
- return this._getVerifier().verify(
- this._buildExponentiatedElementsList(), this._getProof(),
- this._buildDataString(), this._getProgressMeter());
- }
- };
- /**
- * Exponentiation proof verifier.
- */
- box.proofs.ExponentiationProofVerifier = function(
- exponentiatedElements, baseElements, proof, group) {
- checkDefined('exponentiated elements', exponentiatedElements);
- checkDefined('base elements', baseElements);
- checkDefined('proof', proof);
- checkDefined('group', group);
- var _exponentiatedElements = exponentiatedElements;
- var _proof = proof;
- var _progressMeter;
- this._buildComputationRules = function(k) {
- var rules = [];
- for (var i = 0; i < k; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- }
- return rules;
- };
- var _numOutputs = exponentiatedElements.length;
- var phiFunctionExponentiation = new box.proofs.PhiFunction(
- group, 1, _numOutputs, baseElements,
- this._buildComputationRules(_numOutputs));
- var _verifier = new box.proofs.Verifier(group, phiFunctionExponentiation);
- this._getProof = function() {
- return _proof;
- };
- this.getExponentiatedElements = function() {
- return _exponentiatedElements;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.ExponentiationProofVerifier.prototype = {
- verify: function() {
- return this._getVerifier().verify(
- this.getExponentiatedElements(), this._getProof(),
- box.EXPONENTIATION_PROOF_AUXILIARY_DATA, this._getProgressMeter());
- }
- };
- /**
- * Plaintext proof verifier.
- */
- box.proofs.PlaintextProofVerifier = function(publicKey, group) {
- checkDefined('public key', publicKey);
- checkDefined('group', group);
- var _publicKey = publicKey;
- var _group = group;
- var _progressMeter;
- this._buildListOfBaseElements = function() {
- var list = [];
- list.push(_group.getGenerator());
- list.addAll(_publicKey.getGroupElementsArray());
- return list;
- };
- this._buildListPublicValues = function(ciphertext, plaintext) {
- var dividedCiphertext =
- mathematical.groupUtils.divide(ciphertext.getPhis(), plaintext);
- var publicValues = [];
- publicValues.push(ciphertext.getGamma());
- publicValues.addAll(dividedCiphertext);
- return publicValues;
- };
- this._buildComputationRules = function(k) {
- var rules = [];
- for (var i = 0; i < (k + 1); i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- }
- return rules;
- };
- var _publicKeyLength = _publicKey.getGroupElementsArray().length;
- var numOutputs = _publicKeyLength + 1;
- var phiFunctionPlaintext = new box.proofs.PhiFunction(
- _group, 1, numOutputs, this._buildListOfBaseElements(),
- this._buildComputationRules(_publicKeyLength));
- var _verifier = new box.proofs.Verifier(_group, phiFunctionPlaintext);
- this.getPublicKey = function() {
- return _publicKey;
- };
- this.getGroup = function() {
- return _group;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _publicKeyLength + 1, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.PlaintextProofVerifier.prototype = {
- verify: function(ciphertext, plaintext, proof) {
- checkDefined('ciphertext', ciphertext);
- checkDefined('plaintext', plaintext);
- checkDefined('proof', proof);
- return this._getVerifier().verify(
- this._buildListPublicValues(ciphertext, plaintext), proof,
- box.PLAINTEXT_PROOF_AUXILIARY_DATA, this._getProgressMeter());
- }
- };
- /**
- * Simple plaintext equality proof verifier.
- */
- box.proofs.SimplePlaintextEqualityProofVerifier = function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group) {
- checkDefined('primary ciphertext', primaryCiphertext);
- checkDefined('primary public key', primaryPublicKey);
- checkDefined('secondary ciphertext', secondaryCiphertext);
- checkDefined('secondary public key', secondaryPublicKey);
- checkDefined('proof', proof);
- checkDefined('group', group);
- var numPrimaryCiphertextElements = primaryCiphertext.getPhis().length + 1;
- var numPrimaryPublicKeyElements =
- primaryPublicKey.getGroupElementsArray().length;
- var numSecondaryCiphertextElements =
- secondaryCiphertext.getPhis().length + 1;
- var numSecondaryPublicKeyElements =
- secondaryPublicKey.getGroupElementsArray().length;
- if (numPrimaryCiphertextElements !== numSecondaryCiphertextElements) {
- throw new exceptions.CryptoLibException(
- 'The primary and secondary ciphertexts contain different numbers of elements: ' +
- numPrimaryCiphertextElements + ', ' + numSecondaryCiphertextElements);
- }
- if (numPrimaryPublicKeyElements !== numSecondaryPublicKeyElements) {
- throw new exceptions.CryptoLibException(
- 'The primary and secondary public keys contain different numbers of elements: ' +
- numPrimaryPublicKeyElements + ', ' + numSecondaryPublicKeyElements);
- }
- if (numPrimaryCiphertextElements !== (numPrimaryPublicKeyElements + 1)) {
- throw new exceptions.CryptoLibException(
- 'The number of ciphertext elements is not equal to the number public key elements plus one.');
- }
- var _primaryCiphertext = primaryCiphertext;
- var _primaryPublicKey = primaryPublicKey;
- var _secondaryCiphertext = secondaryCiphertext;
- var _secondaryPublicKey = secondaryPublicKey;
- var _proof = proof;
- var _progressMeter;
- function buildComputationRules(k) {
- var rules = [];
- var firstDimensionLength = k + 1;
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- for (var i = 1; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][1] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- rules[i][1].push(i + 1 + k);
- rules[i][1].push(1);
- }
- return rules;
- }
- function buildListOfBaseElements() {
- var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
- var baseElements = [];
- baseElements.push(group.getGenerator());
- baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
- baseElements.addAll(invertedSecondaryKeyValues);
- return baseElements;
- }
- function buildSecondaryInvertedPublicKey() {
- var listInvertedElements = [];
- var keys = _secondaryPublicKey.getGroupElementsArray();
- for (var i = 0; i < keys.length; i++) {
- listInvertedElements.push(keys[i].invert());
- }
- return listInvertedElements;
- }
- var _primarySubCiphertext = _primaryCiphertext.getPhis();
- var _secondarySubCiphertext = _secondaryCiphertext.getPhis();
- var _numKeyElements = _primaryPublicKey.getGroupElementsArray().length;
- var numOutputs = _numKeyElements + 1;
- var phiFunctionSimplePlaintextEquality = new box.proofs.PhiFunction(
- group, 1, numOutputs, buildListOfBaseElements(),
- buildComputationRules(_numKeyElements));
- var _verifier =
- new box.proofs.Verifier(group, phiFunctionSimplePlaintextEquality);
- this._buildInputList = function() {
- var dividedSubCiphertext = mathematical.groupUtils.divide(
- _primarySubCiphertext, _secondarySubCiphertext);
- var generatedList = [];
- generatedList.push(_primaryCiphertext.getGamma());
- generatedList.addAll(dividedSubCiphertext);
- return generatedList;
- };
- this._getProof = function() {
- return _proof;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numKeyElements * 2 + 1, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- };
- box.proofs.SimplePlaintextEqualityProofVerifier.prototype = {
- verify: function() {
- return this._getVerifier().verify(
- this._buildInputList(), this._getProof(),
- box.SIMPLE_PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
- this._getProgressMeter());
- }
- };
- /**
- * Plaintext equality proof verifier.
- */
- box.proofs.PlaintextEqualityProofVerifier = function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group) {
- checkDefined('primary ciphertext', primaryCiphertext);
- checkDefined('primary public key', primaryPublicKey);
- checkDefined('secondary ciphertext', secondaryCiphertext);
- checkDefined('secondary public key', secondaryPublicKey);
- checkDefined('proof', proof);
- checkDefined('group', group);
- var _primaryCiphertext = primaryCiphertext;
- var _primaryPublicKey = primaryPublicKey;
- var _secondaryCiphertext = secondaryCiphertext;
- var _secondaryPublicKey = secondaryPublicKey;
- var _proof = proof;
- var buildComputationRules = function(k) {
- var firstDimensionLength = k + 2;
- var rules = [];
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- rules[1] = [];
- rules[1][0] = [];
- rules[1][0].push(1);
- rules[1][0].push(2);
- for (var i = 2; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][1] = [];
- rules[i][0].push(i);
- rules[i][0].push(1);
- rules[i][1].push(i + k);
- rules[i][1].push(2);
- }
- return rules;
- };
- function buildListOfBaseElements() {
- var invertedSecondaryKeyValues = buildSecondaryInvertedPublicKey();
- var baseElements = [];
- baseElements.push(group.getGenerator());
- baseElements.addAll(_primaryPublicKey.getGroupElementsArray());
- baseElements.addAll(invertedSecondaryKeyValues);
- return baseElements;
- }
- function buildSecondaryInvertedPublicKey() {
- var listInvertedElements = [];
- var keys = _secondaryPublicKey.getGroupElementsArray();
- for (var i = 0; i < keys.length; i++) {
- listInvertedElements.push(keys[i].invert());
- }
- return listInvertedElements;
- }
- var _progressMeter;
- var _primarySubCiphertext = _primaryCiphertext.getPhis();
- var _secondarySubCiphertext = _secondaryCiphertext.getPhis();
- var _numKeyElements = primaryPublicKey.getGroupElementsArray().length;
- var numOutputs = _numKeyElements + 2;
- var phiFunctionPlaintextEquality = new box.proofs.PhiFunction(
- group, 2, numOutputs, buildListOfBaseElements(),
- buildComputationRules(_numKeyElements));
- var _verifier =
- new box.proofs.Verifier(group, phiFunctionPlaintextEquality);
- this._buildInputList = function() {
- var dividedSubCiphertext = mathematical.groupUtils.divide(
- _primarySubCiphertext, _secondarySubCiphertext);
- var generatedList = [];
- generatedList.push(_primaryCiphertext.getGamma());
- generatedList.push(_secondaryCiphertext.getGamma());
- generatedList.addAll(dividedSubCiphertext);
- return generatedList;
- };
- this._getProof = function() {
- return _proof;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numKeyElements * 2 + 2, progressCallback,
- progressPercentMinCheckInterval);
- return this;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- };
- box.proofs.PlaintextEqualityProofVerifier.prototype = {
- verify: function() {
- return this._getVerifier().verify(
- this._buildInputList(), this._getProof(),
- box.PLAINTEXT_EQUALITY_PROOF_AUXILIARY_DATA,
- this._getProgressMeter());
- }
- };
- /**
- * Plaintext exponent equality proof verifier.
- */
- box.proofs.PlaintextExponentEqualityProofVerifier = function(
- ciphertext, baseElements, proof, group) {
- checkDefined('ciphertext', ciphertext);
- checkDefined('base elements', baseElements);
- checkDefined('proof', proof);
- checkDefined('group', group);
- var _ciphertext = ciphertext;
- var _baseElements = baseElements;
- var _proof = proof;
- var _group = group;
- var _progressMeter;
- this._buildComputationRules = function(k) {
- var rules = [];
- var firstDimensionLength = k + 1;
- rules[0] = [];
- rules[0][0] = [];
- rules[0][0].push(1);
- rules[0][0].push(1);
- for (var i = 1; i < firstDimensionLength; i++) {
- rules[i] = [];
- rules[i][0] = [];
- rules[i][1] = [];
- rules[i][0].push(i + 1);
- rules[i][0].push(1);
- rules[i][1].push(i + 1 + k);
- rules[i][1].push(2);
- }
- return rules;
- };
- this._buildListPublicValues = function() {
- var list = [];
- list.push(_ciphertext.getGamma());
- list.addAll(_ciphertext.getPhis());
- return list;
- };
- var _k = _ciphertext.getPhis().length;
- var numOutputs = _k + 1;
- var phiFunctionPlaintextExponentEquality = new box.proofs.PhiFunction(
- _group, 2, numOutputs, _baseElements, this._buildComputationRules(_k));
- var _verifier =
- new box.proofs.Verifier(_group, phiFunctionPlaintextExponentEquality);
- this._getProof = function() {
- return _proof;
- };
- this._getVerifier = function() {
- return _verifier;
- };
- this._getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _k * 2 + 1, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.PlaintextExponentEqualityProofVerifier.prototype = {
- verify: function() {
- return this._getVerifier().verify(
- this._buildListPublicValues(), this._getProof(),
- box.PLAINTEXT_EXPONENT_EQUALITY_PROOF_AUXILIARY_DATA,
- this._getProgressMeter());
- }
- };
- /**
- * OR-proof verifier.
- */
- box.proofs.ORProofVerifier = function(publicKey, numElements, group) {
- checkPublicKey(publicKey);
- checkNumElements(numElements);
- checkGroup(group);
- var _publicKey = publicKey;
- var _numElements = numElements;
- var _group = group;
- var _numOutputs = _numElements * 2;
- var _progressMeter;
- function checkPublicKey(publicKey) {
- checkDefined('public key', publicKey);
- checkNotNull('public key', publicKey);
- var publicKeyLength = publicKey.getGroupElementsArray().length;
- if (publicKeyLength !== 1) {
- throw new exceptions.CryptoLibException(
- 'Expected public key length: 1 ; Found: ' + publicKeyLength);
- }
- }
- function checkNumElements(numElements) {
- checkDefined('numElements', numElements);
- checkNotNull('numElements', numElements);
- if (numElements < 2) {
- throw new exceptions.CryptoLibException(
- 'Expected number of elements to be greater than 1 ; Found: ' +
- numElements);
- }
- }
- function checkGroup(group) {
- checkDefined('group', group);
- checkNotNull('group', group);
- }
- function buildBaseElements() {
- var baseElements = [];
- baseElements.push(_group.getGenerator());
- baseElements.push(_publicKey.getGroupElementsArray()[0]);
- return baseElements;
- }
- function buildComputationRules(numOutputs) {
- var rules = [];
- var index1;
- var index2 = 0;
- for (var i = 0; i < numOutputs; i++) {
- index1 = 1 + (i % 2);
- if (i % 2 === 0) {
- index2++;
- }
- rules[i] = [];
- rules[i][0] = [];
- rules[i][0].push(index1);
- rules[i][0].push(index2);
- }
- return rules;
- }
- var phiFunctionOR = new box.proofs.PhiFunction(
- _group, _numElements, _numOutputs, buildBaseElements(),
- buildComputationRules(_numOutputs));
- var _verifier = new box.proofs.Verifier(_group, phiFunctionOR);
- this.buildPublicValues = function(ciphertext) {
- var publicValues = [];
- publicValues.push(ciphertext.getGamma());
- publicValues.push(ciphertext.getPhis()[0]);
- return publicValues;
- };
- this.getNumElements = function() {
- return _numElements;
- };
- this.getVerifier = function() {
- return _verifier;
- };
- this.getProgressMeter = function() {
- return _progressMeter;
- };
- this.initProgressMeter = function(
- progressCallback, progressPercentMinCheckInterval) {
- _progressMeter = createProgressMeter(
- _numOutputs, progressCallback, progressPercentMinCheckInterval);
- return this;
- };
- };
- box.proofs.ORProofVerifier.prototype = {
- verify: function(ciphertext, elements, data, proof) {
- checkCiphertext(ciphertext);
- checkElements(elements, this.getNumElements());
- checkDefined('data', data);
- checkProof(proof);
- function checkCiphertext(ciphertext) {
- checkDefined('ciphertext', ciphertext);
- checkNotNull('ciphertext', ciphertext);
- var ciphertextLength = ciphertext.getPhis().length + 1;
- if (ciphertextLength !== 2) {
- throw new exceptions.CryptoLibException(
- 'Expected ciphertext length: 2 ; Found: ' + ciphertextLength);
- }
- }
- function checkElements(elements, numElementsExpected) {
- checkDefined('elements', elements);
- checkNotNull('elements', elements);
- var numElementsFound = elements.length;
- if (numElementsFound !== numElementsExpected) {
- throw new exceptions.CryptoLibException(
- 'Expected number of elements: ' + numElementsExpected +
- ' ; Found: ' + numElementsFound);
- }
- }
- function checkProof(proof) {
- checkDefined('proof', proof);
- checkNotNull('proof', proof);
- }
- if (data === null) {
- data = '';
- }
- return this.getVerifier().verify(
- this.buildPublicValues(ciphertext), proof, data, elements,
- this.getProgressMeter());
- }
- };
- /**
- * Proofs factory, can be used for creating proof generators and verifiers.
- */
- box.proofs.ProofsFactory = function() {
- };
- box.proofs.ProofsFactory.prototype = {
- createSchnorrProofGenerator: function(voterID, electionID, group) {
- return new box.proofs.SchnorrProofGenerator(voterID, electionID, group);
- },
- createExponentiationProofGenerator: function(baseElements, group) {
- return new box.proofs.ExponentiationProofGenerator(baseElements, group);
- },
- createPlaintextProofGenerator: function(publicKey, group) {
- return new box.proofs.PlaintextProofGenerator(publicKey, group);
- },
- createSimplePlaintextEqualityProofGenerator: function(
- primaryPublicKey, secondaryPublicKey, group) {
- return new box.proofs.SimplePlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group);
- },
- createPlaintextEqualityProofGenerator: function(
- primaryPublicKey, secondaryPublicKey, group) {
- return new box.proofs.PlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group);
- },
- createPlaintextExponentEqualityProofGenerator: function(
- baseElements, group) {
- return new box.proofs.PlaintextExponentEqualityProofGenerator(
- baseElements, group);
- },
- createORProofGenerator: function(publicKey, numElements, group) {
- return new box.proofs.ORProofGenerator(publicKey, numElements, group);
- },
- createSchnorrProofVerifier: function(
- element, voterID, electionEventID, proof, group) {
- return new box.proofs.SchnorrProofVerifier(
- element, voterID, electionEventID, proof, group);
- },
- createExponentiationProofVerifier: function(
- exponentiatedElements, baseElements, proof, group) {
- return new box.proofs.ExponentiationProofVerifier(
- exponentiatedElements, baseElements, proof, group);
- },
- createPlaintextProofVerifier: function(
- publicKey, ciphertext, plaintext, proof, group) {
- return new box.proofs.PlaintextProofVerifier(
- publicKey, ciphertext, plaintext, proof, group);
- },
- createSimplePlaintextEqualityProofVerifier: function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group) {
- return new box.proofs.SimplePlaintextEqualityProofVerifier(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group);
- },
- createPlaintextEqualityProofVerifier: function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group) {
- return new box.proofs.PlaintextEqualityProofVerifier(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group);
- },
- createPlaintextExponentEqualityProofVerifier: function(
- ciphertext, baseElements, proof, group) {
- return new box.proofs.PlaintextExponentEqualityProofVerifier(
- ciphertext, baseElements, proof, group);
- },
- createORProofVerifier: function(publicKey, numElements, group) {
- return new box.proofs.ORProofVerifier(publicKey, numElements, group);
- }
- };
- /**
- * Represents the PHI function of Maurer's Unified Zero-Knowledge Proof of
- * Knowledge (ZK-PoK) scheme.
- */
- box.proofs.PhiFunction = function(
- group, numInputs, numOutputs, baseElements, computationRules) {
- var validateComputationRules = function(
- numInputs, numOutputs, baseElements, computationRules) {
- // Validate that both of the values in each of the
- // pairs of rules have values in the correct ranges
- var numBaseElements = baseElements.length;
- for (var i = 0; i < numOutputs; i++) {
- for (var j = 0; j < computationRules[i].length; j++) {
- // Validate the first value of the pair
- var pairValue1 = computationRules[i][j][0];
- if ((pairValue1 < 1) || (pairValue1 > numBaseElements)) {
- throw new exceptions.CryptoLibException(
- 'Invalid first value in index pair - should be in the range 1 to ' +
- numBaseElements + ', but it was ' + pairValue1);
- }
- // Validate the second value of the pair
- var pairValue2 = computationRules[i][j][1];
- if ((pairValue2 < 1) || (pairValue2 > numInputs)) {
- throw new exceptions.CryptoLibException(
- 'Invalid second value in index pair - should be in the range 1 to ' +
- numInputs + ', but it was ' + pairValue2);
- }
- }
- }
- };
- checkDefined('group', group);
- checkIsPositive('number of inputs', numInputs);
- checkIsPositive('number of outputs', numOutputs);
- checkInitializedArray('base elements', baseElements);
- checkDefined('computation rules', computationRules);
- validateComputationRules(
- numInputs, numOutputs, baseElements, computationRules);
- var _numInputs = numInputs;
- var _numOutputs = numOutputs;
- var _baseElements = baseElements;
- var _computationRules = computationRules;
- /**
- * @return The number of inputs
- */
- this.getNumInputs = function() {
- return _numInputs;
- };
- /**
- * @return The number of outputs
- */
- this.getNumOutputs = function() {
- return _numOutputs;
- };
- /**
- * @return The list of base elements
- */
- this.getBaseElements = function() {
- return _baseElements;
- };
- /**
- * @return The computation rules.
- */
- this.getComputationRules = function() {
- return _computationRules;
- };
- };
- box.proofs.PhiFunction.prototype = {
- calculatePhi: function(inputs, progressMeter) {
- checkDefined('inputs', inputs);
- if (progressMeter === undefined) {
- progressMeter = new utils.ProgressMeter();
- }
- checkDefined('progressMeter', progressMeter);
- var computationsRules = this.getComputationRules();
- var baseElements = this.getBaseElements();
- var partialResult;
- var resultForThisListOfPairs;
- var result = [];
- var progress = 0;
- for (var i = 0; i < computationsRules.length; i++) {
- var numPairsInList = computationsRules[i].length;
- resultForThisListOfPairs =
- baseElements[computationsRules[i][0][0] - 1].exponentiate(
- inputs[computationsRules[i][0][1] - 1]);
- progressMeter.update(++progress);
- for (var j = 1; j < numPairsInList; j++) {
- var index1 = computationsRules[i][j][0];
- index1 = index1 - 1;
- var index2 = computationsRules[i][j][1];
- index2 = index2 - 1;
- partialResult = baseElements[index1].exponentiate(inputs[index2]);
- resultForThisListOfPairs =
- resultForThisListOfPairs.multiply(partialResult);
- progressMeter.update(++progress);
- }
- result.push(resultForThisListOfPairs);
- }
- return result;
- }
- };
- /**
- * Acts as a prover in a Zero-Knowledge Proof of Knowledge (ZK-PoK) exchange
- * using Maurer's unified PHI function.
- */
- box.proofs.Prover = function(group, phiFunction) {
- checkDefined('group', group);
- checkDefined('phiFunction', phiFunction);
- var _group = group;
- var _phiFunction = phiFunction;
- var _cryptoRandomInteger = secureRandomFactory.getCryptoRandomInteger();
- /**
- * @return Get the group.
- */
- this.getGroup = function() {
- return _group;
- };
- /**
- * @return Get the phi function.
- */
- this.getPhiFunction = function() {
- return _phiFunction;
- };
- this._calculateRandomExponents = function(numExponentsNeeded) {
- var exponentsArray = [];
- for (var i = 0; i < numExponentsNeeded; i++) {
- var randomExponent = mathematical.groupUtils.generateRandomExponent(
- _group, _cryptoRandomInteger);
- exponentsArray.push(randomExponent);
- }
- return exponentsArray;
- };
- this._generateHash = function(publicValues, phiOutputs, data) {
- var hashBuilder = new box.proofs.HashBuilder();
- var hashB64 =
- hashBuilder.buildHashForProof(publicValues, phiOutputs, data);
- var hash = converters.base64Decode(hashB64);
- var hashBytes = converters.bytesFromString(hash);
- hashBytes.unshift(0);
- var value = new box.forge.jsbn.BigInteger(hashBytes);
- return new mathematical.Exponent(_group.getQ(), value);
- };
- this._generateValuesList = function(
- privateValues, hash, randomExponents, index) {
- var proofValues = [];
- var proofValue;
- if (typeof index === 'undefined') {
- for (var i = 0; i < privateValues.length; i++) {
- proofValue = randomExponents[i].getValue().add(
- privateValues[i].getValue().multiply(hash.getValue()));
- proofValues.push(
- new mathematical.Exponent(_group.getQ(), proofValue));
- }
- } else {
- var numElements = randomExponents.length / 2;
- var updatedHash = hash;
- for (var j = 0; j < numElements; j++) {
- if (j === index) {
- for (var k = 0; k < numElements; k++) {
- if (k !== index) {
- updatedHash = updatedHash.subtract(randomExponents[k]);
- }
- }
- proofValues.push(updatedHash);
- } else {
- proofValues.push(randomExponents[j]);
- }
- }
- for (var m = numElements; m < (numElements * 2); m++) {
- if (m === (numElements + index)) {
- proofValue = randomExponents[m].getValue().add(
- privateValues[0].getValue().multiply(updatedHash.getValue()));
- proofValues.push(
- new mathematical.Exponent(_group.getQ(), proofValue));
- } else {
- proofValues.push(randomExponents[m]);
- }
- }
- }
- return proofValues;
- };
- this._updatePreComputedValues = function(
- preComputedValues, publicValues, elements, index) {
- var gamma = publicValues[0];
- var phi = publicValues[1];
- var numElements = elements.length;
- var challenges = this._calculateRandomExponents(numElements);
- var updatedExponents = [];
- updatedExponents.addAll(challenges);
- updatedExponents.addAll(preComputedValues.getExponents());
- var updatedPhiOutputs = [];
- var phiOutputs = preComputedValues.getPhiOutputs();
- for (var j = 0; j < numElements; j++) {
- var offset = 2 * j;
- if (j === index) {
- updatedPhiOutputs.push(phiOutputs[offset]);
- updatedPhiOutputs.push(phiOutputs[offset + 1]);
- } else {
- var gammaFactor = gamma.invert().exponentiate(challenges[j]);
- var phiFactor =
- (phi.invert().multiply(elements[j])).exponentiate(challenges[j]);
- updatedPhiOutputs.push(phiOutputs[offset].multiply(gammaFactor));
- updatedPhiOutputs.push(phiOutputs[offset + 1].multiply(phiFactor));
- }
- }
- return new box.proofs.ProofPreComputedValues(
- updatedExponents, updatedPhiOutputs);
- };
- };
- box.proofs.Prover.prototype = {
- /**
- * Pre-compute time-consuming values, so they can be used later for
- * method prove().
- */
- preCompute: function(privateValuesLength, progressMeter) {
- var randomExponents = this._calculateRandomExponents(privateValuesLength);
- var phiOutputs =
- this.getPhiFunction().calculatePhi(randomExponents, progressMeter);
- return new box.proofs.ProofPreComputedValues(randomExponents, phiOutputs);
- },
- /**
- * Performs prover steps in a ZK-PoK exchange using Maurer's unified PHI
- * function. This involves generating a proof, using the received inputs
- * and this Prover's internal fields.
- */
- prove: function(
- publicValues, privateValues, data, preComputedValues, elements, index) {
- checkDefined('public values', publicValues);
- checkDefined('private values', privateValues);
- checkDefined('data', data);
- if (!preComputedValues ||
- typeof preComputedValues.getPhiOutputs() === 'undefined' ||
- typeof preComputedValues.getExponents() === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The precomputed values must be initialized');
- }
- if (typeof elements !== 'undefined') {
- preComputedValues = this._updatePreComputedValues(
- preComputedValues, publicValues, elements, index);
- }
- var hash = this._generateHash(
- publicValues, preComputedValues.getPhiOutputs(), data);
- var proofValues = this._generateValuesList(
- privateValues, hash, preComputedValues.getExponents(), index);
- return new box.proofs.Proof(hash, proofValues);
- }
- };
- /**
- * Acts as a verifier in a Zero-Knowledge Proof of Knowledge (ZK-PoK)
- * exchange using Maurer's unified PHI function.
- */
- box.proofs.Verifier = function(group, phiFunction) {
- checkDefined('group', group);
- checkDefined('phiFunction', phiFunction);
- var _group = group;
- var _phiFunction = phiFunction;
- /**
- * @return Get the group.
- */
- this.getGroup = function() {
- return _group;
- };
- /**
- * @return Get the phi function.
- */
- this.getPhiFunction = function() {
- return _phiFunction;
- };
- this._calculateComputedValues = function(
- publicValues, phiOutputs, proofHashValueOrElements, challenges) {
- var proofHashValue;
- var elements;
- if (!isArray(proofHashValueOrElements)) {
- proofHashValue = proofHashValueOrElements;
- } else {
- elements = proofHashValueOrElements;
- }
- var computedValues = [];
- if (typeof proofHashValue !== 'undefined') {
- for (var i = 0; i < phiOutputs.length; i++) {
- computedValues.push(phiOutputs[i].multiply(
- publicValues[i].exponentiate(proofHashValue.negate())));
- }
- } else {
- var gamma = publicValues[0];
- var phi = publicValues[1];
- for (var j = 0; j < challenges.length; j++) {
- var offset = 2 * j;
- var gammaFactor = gamma.invert().exponentiate(challenges[j]);
- var phiFactor =
- (phi.invert().multiply(elements[j])).exponentiate(challenges[j]);
- computedValues.push(phiOutputs[offset].multiply(gammaFactor));
- computedValues.push(phiOutputs[offset + 1].multiply(phiFactor));
- }
- }
- return computedValues;
- };
- this._calculateHash = function(publicValues, computedValues, data) {
- var hashBuilder = new box.proofs.HashBuilder();
- var hashB64 =
- hashBuilder.buildHashForProof(publicValues, computedValues, data);
- var hash = converters.base64Decode(hashB64);
- var hashBytes = converters.bytesFromString(hash);
- hashBytes.unshift(0);
- var value = new box.forge.jsbn.BigInteger(hashBytes);
- return new mathematical.Exponent(_group.getQ(), value);
- };
- };
- box.proofs.Verifier.prototype = {
- /**
- * Verifies the received input as being true or false.
- */
- verify: function(
- publicValues, proof, data, elementsOrProgressMeter, progressMeter) {
- checkDefined('public values', publicValues);
- checkDefined('proof', proof);
- checkDefined('data', data);
- var elements;
- if (!isArray(elementsOrProgressMeter)) {
- progressMeter = elementsOrProgressMeter;
- } else {
- elements = elementsOrProgressMeter;
- }
- var proofHashValue = proof.getHash();
- var phiOutputs;
- var computedValues;
- if (typeof elements === 'undefined') {
- phiOutputs = this.getPhiFunction().calculatePhi(
- proof.getValues(), progressMeter);
- computedValues = this._calculateComputedValues(
- publicValues, phiOutputs, proofHashValue);
- } else {
- var numElements = elements.length;
- var proofValues = proof.getValues();
- var challenges = proofValues.slice(0, numElements);
- var phiInputs = proofValues.slice(numElements, numElements * 2);
- phiOutputs =
- this.getPhiFunction().calculatePhi(phiInputs, progressMeter);
- computedValues = this._calculateComputedValues(
- publicValues, phiOutputs, elements, challenges);
- }
- var calculatedHash =
- this._calculateHash(publicValues, computedValues, data);
- return proofHashValue.equals(calculatedHash);
- }
- };
- /**
- * @class ProofPreComputedValues stores randomly created exponents and
- * outputs of box.proofs.PhiFunction.calculatePhi().
- */
- box.proofs.ProofPreComputedValues = function(exponents, phiOutputs) {
- this.className = 'ProofPreComputedValues';
- var _exponents = exponents;
- var _phiOutputs = phiOutputs;
- /**
- * @return the exponents.
- */
- this.getExponents = function() {
- return _exponents;
- };
- /**
- * @return the phi function output.
- */
- this.getPhiOutputs = function() {
- return _phiOutputs;
- };
- };
- box.proofs.ProofPreComputedValues.prototype = {
- stringify: function() {
- var exponentValues = Array();
- var phiOutputValues = Array();
- for (var i = 0; i < this.getExponents().length; i++) {
- exponentValues[i] =
- converters.base64FromBigInteger(this.getExponents()[i].getValue());
- }
- for (var j = 0; j < this.getPhiOutputs().length; j++) {
- phiOutputValues[j] = converters.base64FromBigInteger(
- this.getPhiOutputs()[j].getElementValue());
- }
- return JSON.stringify({
- preComputed: {
- p: converters.base64FromBigInteger(this.getPhiOutputs()[0].getP()),
- q: converters.base64FromBigInteger(this.getPhiOutputs()[0].getQ()),
- exponents: exponentValues,
- phiOutputs: phiOutputValues
- }
- });
- }
- };
- /**
- * Represents a proof in a ZKP exchange.
- */
- box.proofs.Proof = function(hashValue, values) {
- checkDefined('hash value', hashValue);
- checkDefined('values', values);
- var _hashValue = hashValue;
- var _values = values;
- /**
- * @return Get the hash value of this proof.
- */
- this.getHash = function() {
- return _hashValue;
- };
- /**
- * @return Get the list of values of this proof.
- */
- this.getValues = function() {
- return _values;
- };
- };
- box.proofs.Proof.prototype = {
- /**
- * @return true if the given proof has the same hash and values.
- */
- equals: function(proof) {
- return proof.getHash().equals(this.getHash()) &&
- proof.getValues().equals(this.getValues());
- },
- /**
- * Displays a string representation of this proof JSON.
- * <p>
- * Note: in order to permit interoperability between libraries, this
- * representation should match the equivalent representation in Java.
- *
- * @function
- * @returns a string representation of this proof JSON.
- */
- stringify: function() {
- var values = Array();
- for (var i = 0; i < this.getValues().length; i++) {
- values[i] =
- converters.base64FromBigInteger(this.getValues()[i].getValue());
- }
- return JSON.stringify({
- zkProof: {
- q: converters.base64FromBigInteger(this.getHash().getQ()),
- hash: converters.base64FromBigInteger(this.getHash().getValue()),
- values: values
- }
- });
- }
- };
- /**
- * A class which provides utility methods for generating a hash from a set
- * of inputs.
- */
- box.proofs.HashBuilder = function() {
- /**
- * Convert an integer to a byte array
- */
- this._getInt64Bytes = function(x) {
- var bytes = [];
- var i = 8;
- do {
- bytes[--i] = x & (255);
- x = x >> 8;
- } while (i);
- return bytes;
- };
- /**
- * Converts an array to a String.
- */
- this._arrayElementValuesToString = function(groupElements) {
- var str = '';
- for (var i = 0; i < groupElements.length; i++) {
- if (groupElements[i].getElementValue() !== undefined) {
- str += groupElements[i].getElementValue();
- } else {
- throw new exceptions.CryptoLibException(
- 'Group Element must implement getElementValue() method.');
- }
- }
- return str;
- };
- };
- box.proofs.HashBuilder.prototype = {
- /**
- * Generates a hash value based on the element values of publicValues
- * and generatedValues and the data.
- *
- * @function
- * @param publicValues
- * {array} group elements representing public values.
- * @param generatedValues
- * {array} group elements representing generated values.
- * @param data
- * {string} some data encoded as a String.
- * @returns a generated hash code.
- * @throws CryptoLibException
- * if any of the received objects has unsupported type.
- */
- buildHashForProof: function(publicValues, generatedValues, data) {
- checkInitializedArray('public values', publicValues);
- checkInitializedArray('generated values', generatedValues);
- var messageDigester = messageDigestFactory.getCryptoMessageDigest();
- messageDigester.start();
- messageDigester = update(
- messageDigester, this._arrayElementValuesToString(publicValues));
- messageDigester = update(
- messageDigester, this._arrayElementValuesToString(generatedValues));
- messageDigester = update(messageDigester, data);
- return messageDigester.digest();
- }
- };
- /**
- * Utility method that updates messageDigester with the provided string.
- */
- function update(messageDigester, str) {
- var stringRepresentationB64 = converters.base64Encode(str);
- var arrayToHash = [];
- arrayToHash.push(stringRepresentationB64);
- messageDigester.update(arrayToHash);
- return messageDigester;
- }
- /**
- * Utility method that checks that value is defined and not null and throws
- * related exception otherwise.
- */
- function checkDefined(key, value) {
- if (typeof value === 'undefined') {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must be defined');
- }
- }
- /**
- * Utility method that checks that value is initialized array and throws
- * related exception otherwise.
- */
- function checkInitializedArray(key, value) {
- checkDefined(key, value);
- if (!isArray(value)) {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must be an initialized array');
- }
- }
- /**
- * Utility method that checks that value is not null and throws related
- * exception otherwise.
- */
- function checkNotNull(key, value) {
- checkDefined(key, value);
- if (value === null) {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must not be null');
- }
- }
- /**
- * Utility method that checks that value is not empty and throws related
- * exception otherwise.
- */
- function checkNotEmpty(key, value) {
- checkDefined(key, value);
- if (value.length === 0) {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must not be empty');
- }
- }
- /**
- * Utility method that checks that value is positive and throws related
- * exception otherwise.
- */
- function checkIsPositive(key, value) {
- checkDefined(key, value);
- if (isNaN(value)) {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must be a number; Found ' + value);
- }
- if (value <= 0) {
- throw new exceptions.CryptoLibException(
- 'The ' + key + ' must be positive; Found ' + value);
- }
- }
- /**
- * Utility method that checks that values are defined and throws related
- * exception otherwise.
- */
- var checkDefinedProgressParams = function(
- progressCallback, progressPercentMinCheckInterval) {
- if (typeof progressCallback !== 'undefined' &&
- typeof progressCallback !== 'function') {
- throw new exceptions.CryptoLibException(
- 'The progress callback function provided as input is not a function');
- }
- if (typeof progressPercentMinCheckInterval !== 'undefined' &&
- isNaN(progressPercentMinCheckInterval)) {
- throw new exceptions.CryptoLibException(
- 'The progress percentage check interval provided as input is not a number');
- }
- };
- function isArray(a) {
- return (!!a) && (a.constructor === Array);
- }
- /**
- * Utility method that creates a new instance of ProgressMeter.
- */
- function createProgressMeter(
- progressMax, progressCallback, progressPercentMinCheckInterval) {
- checkDefinedProgressParams(
- progressCallback, progressPercentMinCheckInterval);
- return new utils.ProgressMeter(
- progressMax, progressCallback, progressPercentMinCheckInterval);
- }
- /**
- * Provides utility functionality for working with proofs.
- *
- * @class utils
- * @memberof proofs
- */
- box.proofs.utils = (function() {
- /**
- * Deserializes a Proof JSON string representation to a Proof object.
- *
- * @function
- * @memberof proofs.utils
- * @param jsonAsString
- * {JSON} a JSON representation of a proof.
- * @returns a new Proof, created from the received string.
- */
- function deserializeProof(jsonAsString) {
- var proofJson = JSON.parse(jsonAsString).zkProof;
- var q = converters.base64ToBigInteger(proofJson.q);
- var hash = new box.commons.mathematical.Exponent(
- q, converters.base64ToBigInteger(proofJson.hash));
- var values = [];
- for (var i = 0; i < proofJson.values.length; i++) {
- values.push(new box.commons.mathematical.Exponent(
- q, converters.base64ToBigInteger(proofJson.values[i])));
- }
- return new box.proofs.Proof(hash, values);
- }
- /**
- * Deserializes a ProofPreComputedValues JSON string representation to a
- * ProofPreComputedValues object.
- *
- * @function
- * @memberof proofs.utils
- * @param jsonAsString
- * {JSON} a JSON representation of a pre-computed value.
- * @returns a new ProofPreComputedValues, created from the received
- * string.
- */
- function deserializeProofPreComputedValues(jsonAsString) {
- var proofPreComputedValuesJson = JSON.parse(jsonAsString).preComputed;
- var p = converters.base64ToBigInteger(proofPreComputedValuesJson.p);
- var q = converters.base64ToBigInteger(proofPreComputedValuesJson.q);
- var exponentValues = proofPreComputedValuesJson.exponents;
- var exponents = [];
- var value;
- for (var i = 0; i < exponentValues.length; i++) {
- value = converters.base64ToBigInteger(exponentValues[i]);
- exponents.push(new box.commons.mathematical.Exponent(q, value));
- }
- var phiOutputValues = proofPreComputedValuesJson.phiOutputs;
- var phiOutputs = [];
- for (var j = 0; j < phiOutputValues.length; j++) {
- value = converters.base64ToBigInteger(phiOutputValues[j]);
- phiOutputs.push(
- new box.commons.mathematical.ZpGroupElement(value, p, q));
- }
- return new box.proofs.ProofPreComputedValues(exponents, phiOutputs);
- }
- return {
- deserializeProof: deserializeProof,
- deserializeProofPreComputedValues: deserializeProofPreComputedValues
- };
- })();
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.proofs = cryptolib.modules.proofs || {};
- /**
- * Allows several cryptographic proofs to be generated and verified.
- * <P>
- */
- cryptolib.modules.proofs.service = function(box) {
- 'use strict';
- box.proofs = box.proofs || {};
- box.proofs.service = {};
- var proofsFactory;
- var f = function(box) {
- proofsFactory = new box.proofs.ProofsFactory();
- };
- f.policies = {
- proofs: {
- messagedigest: {
- algorithm: box.policies.proofs.messagedigest.algorithm,
- provider: box.policies.proofs.messagedigest.provider
- },
- secureRandom: {provider: box.policies.proofs.secureRandom.provider},
- charset: box.policies.proofs.charset
- },
- primitives: {
- secureRandom: {provider: box.policies.primitives.secureRandom.provider}
- }
- };
- cryptolib(
- 'proofs.implementation', 'primitives.securerandom', 'commons.exceptions',
- 'commons.mathematical', f);
- /**
- * Creates a Schnorr proof.
- *
- * @param voterID
- * The voter ID. This should be a string.
- * @param electionID
- * The election event ID. This should be a string.
- * @param exponentiatedElement
- * The exponentiated element. This should be an element of the
- * received group.
- * @param witness
- * The witness. This should be an Exponent of the received group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The Schnorr proof.
- */
- box.proofs.service.createSchnorrProof = function(
- voterID, electionID, exponentiatedElement, witness, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createSchnorrProofGenerator(voterID, electionID, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(exponentiatedElement, witness);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- exponentiatedElement, witness, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(exponentiatedElement, witness);
- }
- };
- /**
- * Creates an exponentiation proof.
- *
- * @param exponentiatedElements
- * The exponentiated elements. These should consist of the
- * following base elements, exponentiated with the specified
- * exponent.
- * @param baseElements
- * The base elements used for the exponentiations. These should
- * correspond to elements of the specified group.
- * @param exponent
- * The exponent for which this proof is to be generated. It
- * should be an exponent of the specified group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The exponentiation proof.
- */
- box.proofs.service.createExponentiationProof = function(
- exponentiatedElements, baseElements, exponent, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createExponentiationProofGenerator(baseElements, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(exponentiatedElements, exponent);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- exponentiatedElements, exponent, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(exponentiatedElements, exponent);
- }
- };
- /**
- * Creates a plaintext proof.
- *
- * @param publicKey
- * The primary public key. This should be an ElGamal public key.
- * @param ciphertext
- * The ciphertext. This should be the output from ElGamal
- * encryption.
- * @param plaintext
- * The plaintext. This should be an array of elements of the
- * received group.
- * @param witness
- * The witness. This should be an Exponent of the received group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext proof.
- */
- box.proofs.service.createPlaintextProof = function(
- publicKey, ciphertext, plaintext, witness, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createPlaintextProofGenerator(publicKey, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(ciphertext, plaintext, witness);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- ciphertext, plaintext, witness, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(ciphertext, plaintext, witness);
- }
- };
- /**
- * Creates a simple plaintext equality Proof.
- *
- * @param primaryCiphertext
- * The primary ciphertext. This should be the output from ElGamal
- * encryption.
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param witness
- * The witness of the proof. This should be an Exponent of the
- * received group.
- * @param secondaryCiphertext
- * The secondary ciphertext. This should be the output from
- * ElGamal encryption.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The simple plaintext equality proof.
- */
- box.proofs.service.createSimplePlaintextEqualityProof = function(
- primaryCiphertext, primaryPublicKey, witness, secondaryCiphertext,
- secondaryPublicKey, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createSimplePlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(
- primaryCiphertext, secondaryCiphertext, witness);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- primaryCiphertext, secondaryCiphertext, witness, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(primaryCiphertext, secondaryCiphertext, witness);
- }
- };
- /**
- * Creates a plaintext equality proof.
- *
- * @param primaryCiphertext
- * The primary ciphertext. This should be the output from ElGamal
- * encryption.
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param primaryWitness
- * The primary witness of the proof. This should be an Exponent
- * of the received group.
- * @param secondaryCiphertext
- * The secondary ciphertext. This should be the output from
- * ElGamal encryption.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param secondaryWitness
- * The secondary witness of the proof. This should be an Exponent
- * of the received group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext equality proof.
- */
- box.proofs.service.createPlaintextEqualityProof = function(
- primaryCiphertext, primaryPublicKey, primaryWitness, secondaryCiphertext,
- secondaryPublicKey, secondaryWitness, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator = proofsFactory.createPlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(
- primaryCiphertext, primaryWitness, secondaryCiphertext,
- secondaryWitness);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- primaryCiphertext, primaryWitness, secondaryCiphertext,
- secondaryWitness, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(
- primaryCiphertext, primaryWitness, secondaryCiphertext,
- secondaryWitness);
- }
- };
- /**
- * Creates a plaintext exponent equality proof.
- *
- * @param ciphertext
- * The ciphertext. This should be the output from ElGamal
- * encryption.
- * @param plaintext
- * The plaintext. It should be an array of members of the
- * received group.
- * @param primaryWitness
- * The primary witness. This should be an Exponent of the
- * received group.
- * @param secondaryWitness
- * The secondary witness. This should be an Exponent of the
- * received group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext exponent equality proof.
- */
- box.proofs.service.createPlaintextExponentEqualityProof = function(
- ciphertext, plaintext, primaryWitness, secondaryWitness, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createPlaintextExponentEqualityProofGenerator(
- plaintext, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(
- ciphertext, primaryWitness, secondaryWitness);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- ciphertext, primaryWitness, secondaryWitness, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(ciphertext, primaryWitness, secondaryWitness);
- }
- };
- /**
- * Creates an OR-proof.
- *
- * @param publicKey
- * The public key. This should be an ElGamal public key.
- * @param ciphertext
- * The ciphertext of the mathematical group element that was
- * encrypted. This should be the output from ElGamal encryption.
- * @param witness
- * The witness used to generate the ciphertext. This should be an
- * Exponent of the received group.
- * @param elements
- * The mathematical group elements, one of which was encrypted.
- * This should be an array of elements of the received group.
- * @param index
- * The index of the mathematical group element that was
- * encrypted. This should be an integer.
- * @param data
- * Any extra data to use for the proof generation. This should be
- * a String. NOTE: If this parameter is null, then data will be set
- * to empty string.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallbackOrPreComputedValues
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The OR-proof.
- */
- box.proofs.service.createORProof = function(
- publicKey, ciphertext, witness, elements, index, data, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- var proofGenerator =
- proofsFactory.createORProofGenerator(publicKey, elements.length, group);
- if (!progressCallbackOrPreComputedValues) {
- return proofGenerator.generate(
- ciphertext, witness, elements, index, data);
- } else if (isPreComputedValues(progressCallbackOrPreComputedValues)) {
- var preComputedValues = progressCallbackOrPreComputedValues;
- return proofGenerator.generate(
- ciphertext, witness, elements, index, data, preComputedValues);
- } else {
- var progressCallback = progressCallbackOrPreComputedValues;
- return proofGenerator
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .generate(ciphertext, witness, elements, index, data);
- }
- };
- /**
- * Verifies a Schnorr proof.
- *
- * @param exponentiatedElement
- * The exponentiated element. This should be an element of the
- * specified group.
- * @param voterID
- * The voter IS. This should be a string.
- * @param electionID
- * The election event ID. This should be a string.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- *
- * @returns true if the Schnorr Proof can be verified, false otherwise.
- */
- box.proofs.service.verifySchnorrProof = function(
- element, voterID, electionEventID, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createSchnorrProofVerifier(
- element, voterID, electionEventID, proof, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify();
- };
- /**
- * Verifies an exponentiation proof.
- *
- * @param exponentiatedElements
- * The exponentiated elements. These should consist of the
- * following base elements, exponentiated with the specified
- * exponent.
- * @param baseElements
- * The base elements used for the exponentiations. These should
- * correspond to elements of the specified group.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- *
- * @returns true if the exponentiation proof can be verified, false
- * otherwise.
- */
- box.proofs.service.verifyExponentiationProof = function(
- exponentiatedElements, baseElements, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createExponentiationProofVerifier(
- exponentiatedElements, baseElements, proof, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify();
- };
- /**
- * Verifies a plaintext proof.
- *
- * @param publicKey
- * The primary public key. This should be an ElGamal public key.
- * @param ciphertext
- * The ciphertext. This should be the output from ElGamal
- * encryption.
- * @param plaintext
- * The plaintext. This should be an array of elements of the
- * received group.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- * @returns true if the plaintext proof can be verified, false otherwise.
- */
- box.proofs.service.verifyPlaintextProof = function(
- publicKey, ciphertext, plaintext, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory.createPlaintextProofVerifier(publicKey, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify(ciphertext, plaintext, proof);
- };
- /**
- * Verifies a simple plaintext equality proof.
- *
- * @param primaryCiphertext
- * The primary ciphertext. This should be the output from ElGamal
- * encryption.
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param secondaryCiphertext
- * The secondary ciphertext. This should be the output from
- * ElGamal encryption.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- *
- * @returns true if the simple plaintext equality proof can be verified,
- * false otherwise.
- */
- box.proofs.service.verifySimplePlaintextEqualityProof = function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createSimplePlaintextEqualityProofVerifier(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify();
- };
- /**
- * Verifies a plaintext equality proof.
- *
- * @param primaryCiphertext
- * The primary ciphertext. This should be the output from ElGamal
- * encryption.
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param secondaryCiphertext
- * The secondary ciphertext. This should be the output from
- * ElGamal encryption.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- *
- * @returns true if the plaintext equality proof can be verified, false
- * otherwise.
- */
- box.proofs.service.verifyPlaintextEqualityProof = function(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createPlaintextEqualityProofVerifier(
- primaryCiphertext, primaryPublicKey, secondaryCiphertext,
- secondaryPublicKey, proof, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify();
- };
- /**
- * Verifies a plaintext exponent equality proof.
- *
- * @param ciphertext
- * The ciphertext. This should be the output from ElGamal
- * encryption.
- * @param baseElements
- * The array of base elements. All of these elements should be
- * members of the received group.
- * @param witness1
- * The primary witness. This should be an Exponent.
- * @param witness2
- * The secondary witness. This should be an Exponent.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- *
- * @returns true if the plaintext exponent equality proof can be verified,
- * false otherwise.
- */
- box.proofs.service.verifyPlaintextExponentEqualityProof = function(
- ciphertext, baseElements, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createPlaintextExponentEqualityProofVerifier(
- ciphertext, baseElements, proof, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify();
- };
- /**
- * Verifies an OR-proof.
- *
- * @param publicKey
- * The public key. This should be an ElGamal public key.
- * @param ciphertext
- * The ciphertext of the mathematical group element that was
- * encrypted. This should be the output from ElGamal encryption.
- * @param elements
- * The mathematical group elements, one of which was encrypted.
- * This should be an array of elements of the received group.
- * @param data
- * Any extra data used for the proof generation. This should be a
- * String. NOTE: If this parameter is null, then data will be set
- * to empty string.
- * @param proof
- * The proof that is to be verified.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval (optional).
- * @returns true if the OR-proof can be verified, false otherwise.
- */
- box.proofs.service.verifyORProof = function(
- publicKey, ciphertext, elements, data, proof, group, progressCallback,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createORProofVerifier(publicKey, elements.length, group)
- .initProgressMeter(progressCallback, progressPercentMinCheckInterval)
- .verify(ciphertext, elements, data, proof);
- };
- /**
- * Pre-computes a Schnorr proof. IMPORTANT: The same pre-computed values
- * must not be used twice.
- *
- * @param voterID
- * The voter ID. This should be a string.
- * @param electionID
- * The election event ID. This should be a string.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The Schnorr proof pre-computed values.
- */
- box.proofs.service.preComputeSchnorrProof = function(
- voterID, electionID, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- return proofsFactory.createSchnorrProofGenerator(voterID, electionID, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Pre-computes an exponentiation proof. IMPORTANT: The same pre-computed
- * values must not be used twice.
- *
- * @param baseElements
- * The base elements used for the exponentiations. These should
- * correspond to elements of the specified group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The exponentiation proof pre-computed values.
- */
- box.proofs.service.preComputeExponentiationProof = function(
- baseElements, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- return proofsFactory.createExponentiationProofGenerator(baseElements, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Pre-computes a plaintext proof. IMPORTANT: The same pre-computed values
- * must not be used twice.
- *
- * @param publicKey
- * The primary public key. This should be an ElGamal public key.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext proof pre-computed values.
- */
- box.proofs.service.preComputePlaintextProof = function(
- publicKey, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- return proofsFactory.createPlaintextProofGenerator(publicKey, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Pre-computes values for a simple plaintext equality proof. IMPORTANT: The
- * same pre-computed values must not be used twice.
- *
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The simple plaintext equality proof pre-computed values.
- */
- box.proofs.service.preComputeSimplePlaintextEqualityProof = function(
- primaryPublicKey, secondaryPublicKey, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- return proofsFactory
- .createSimplePlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Pre-computes values for a plaintext equality proof. IMPORTANT: The same
- * pre-computed values must not be used twice.
- *
- * @param primaryPublicKey
- * The primary public key. This should be an ElGamal public key.
- * @param secondaryPublicKey
- * The secondary public key. This should be an ElGamal public
- * key.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext equality proof pre-computed values.
- */
- box.proofs.service.preComputePlaintextEqualityProof = function(
- primaryPublicKey, secondaryPublicKey, group,
- progressCallbackOrPreComputedValues, progressPercentMinCheckInterval) {
- return proofsFactory
- .createPlaintextEqualityProofGenerator(
- primaryPublicKey, secondaryPublicKey, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Returns pre-computed values for a plaintext exponent equality proof.
- * IMPORTANT: The same pre-computed values must not be used twice.
- *
- * @param plaintext
- * The plaintext. It should be an array of members of the
- * received group.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The plaintext exponent equality proof pre-computed values.
- */
- box.proofs.service.preComputePlaintextExponentEqualityProof = function(
- plaintext, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- return proofsFactory
- .createPlaintextExponentEqualityProofGenerator(plaintext, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Pre-computes an OR-proof. IMPORTANT: The same pre-computed values must
- * not be used twice.
- *
- * @param publicKey
- * The public key. This should be an ElGamal public key.
- * @param numElements
- * The number of elements belonging to the received mathematical
- * group that will be used for the proof, one of which will be
- * encrypted.
- * @param group
- * The mathematical group. This should be a Zp subgroup.
- * @param progressCallback
- * Progress callback function or pre-computed values (optional).
- * @param progressPercentMinCheckInterval
- * Progress percentage minimum check interval, if the previous
- * parameter is a progressCallback function (optional).
- *
- * @returns The OR-proof pre-computed values.
- */
- box.proofs.service.preComputeORProof = function(
- publicKey, numElements, group, progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval) {
- return proofsFactory.createORProofGenerator(publicKey, numElements, group)
- .initProgressMeter(
- progressCallbackOrPreComputedValues,
- progressPercentMinCheckInterval)
- .preCompute();
- };
- /**
- * Utility method that checks if the argument is instance of type
- * ProofPreComputedValues.
- *
- * @param values
- * argument to check.
- * @returns {boolean} true if values is instance of ProofPreComputedValues.
- */
- function isPreComputedValues(values) {
- return !!(values) && values.className === 'ProofPreComputedValues';
- }
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.stores = cryptolib.modules.stores || {};
- /**
- * Defines a pkcs12 store.
- */
- cryptolib.modules.stores.pkcs12 = function(box) {
- 'use strict';
- box.stores = box.stores || {};
- box.stores.pkcs12 = {};
- var converters;
- var exceptions;
- cryptolib('commons', function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- });
- /**
- * Defines a PKCS12.
- *
- * @param pkcs12DerB64
- * PKCS12, as string in Base64 encoded DER format.
- */
- box.stores.pkcs12.Pkcs12 = function(pkcs12DerB64) {
- this.pkcs12Der = converters.base64Decode(pkcs12DerB64);
- this.pkcs12Asn1 = forge.asn1.fromDer(this.pkcs12Der, false);
- };
- box.stores.pkcs12.Pkcs12.prototype = {
- /**
- * Retrieves the private key of the PKCS12.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @return Private key of PKCS12, as string in PEM format.
- */
- getPrivateKey: function(passwordB64) {
- var aliases = Array.prototype.slice.call(arguments, 1);
- function isAliasInList(alias) {
- var returnValue = false;
- if (aliases.indexOf(alias) >= 0) {
- returnValue = true;
- }
- return returnValue;
- }
- var privateKeyAlias = '';
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- // Retrieve private key safe bag from PKCS12.
- var privateKeys = {};
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
- privateKeyAlias = safeBag.attributes.friendlyName[0];
- if (aliases.length === 0 || isAliasInList(privateKeyAlias)) {
- privateKeys[privateKeyAlias] =
- forge.pki.privateKeyToPem(safeBag.key);
- }
- }
- }
- }
- // Check whether any private key safe bags were found.
- if (Object.getOwnPropertyNames(privateKeys).length === 0) {
- throw new exceptions.CryptoLibException(
- 'Could not find any private key safe bags in PKCS12.');
- }
- return privateKeys;
- } catch (error) {
- var errorMsg = 'Could not retrieve private key from PKCS12.';
- if (privateKeyAlias.length > 0) {
- errorMsg = 'Could not retrieve private key with alias ' +
- privateKeyAlias + ' from PKCS12.';
- }
- throw new exceptions.CryptoLibException(errorMsg);
- }
- },
- /**
- * Retrieves the private key chain from the PKCS12.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @return Private key chain of PKCS12, as PrivateKeyChain object.
- */
- getPrivateKeyChain: function(passwordB64) {
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- // Retrieve private key safe bags from PKCS12.
- var privateKeyChain = new box.stores.pkcs12.PrivateKeyChain();
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
- var alias = safeBag.attributes.friendlyName[0];
- var privateKeyPem = forge.pki.privateKeyToPem(safeBag.key);
- privateKeyChain.add(alias, privateKeyPem);
- }
- }
- }
- // Check whether any private key safe bags were found.
- if (privateKeyChain.length === 0) {
- throw new exceptions.CryptoLibException(
- 'Could not find any private key safe bags in PKCS12.');
- }
- return privateKeyChain;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not retrieve private key chain from PKCS12.', error);
- }
- },
- /**
- * Retrieves the certificate chain of the PKCS12.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @return Certificate chain of PKCS12, as array of strings in PEM
- * format.
- */
- getCertificateChain: function(passwordB64) {
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- // Retrieve certificate safe bags from PKCS12.
- var certificatePemChain = [];
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.certBag) {
- var certificatePem = forge.pki.certificateToPem(safeBag.cert);
- certificatePemChain.push(certificatePem);
- }
- }
- }
- // Check whether any certificate safe bags were found.
- if (certificatePemChain.length === 0) {
- throw new exceptions.CryptoLibException(
- 'Could not find any certificate safe bags in PKCS12.');
- }
- return certificatePemChain;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not retrieve certificate chain from PKCS12.', error);
- }
- },
- /**
- * Retrieves the certificate chain of the PKCS12 filtered by alias.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @param alias
- * Alias to filter
- * @return Certificate chain of PKCS12, as array of strings in PEM
- * format.
- */
- getCertificateChainByAlias: function(passwordB64, alias) {
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- var discardedBags = {};
- var nextBagId = null;
- // Retrieve certificate safe bags from PKCS12.
- var certificatePemChain = [];
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.certBag) {
- var bagFound = null;
- // if not initializated the chain, find the one with alias
- // or if is the one that goes next into the list take it
- if ((!nextBagId && safeBag.attributes &&
- safeBag.attributes.friendlyName &&
- safeBag.attributes.friendlyName[0] === alias) ||
- (nextBagId && nextBagId === safeBag.cert.subject.hash)) {
- bagFound = safeBag;
- }
- // otherwise, if not initializated and it's not the alias, save it
- // for later use
- else {
- discardedBags[safeBag.cert.subject.hash] = safeBag;
- }
- // add the bag and check if we have the next one in the list we
- // had
- while (bagFound) {
- // transform the current to PEM and save it
- var certificatePem = forge.pki.certificateToPem(bagFound.cert);
- certificatePemChain.push(certificatePem);
- // we arrived to the root so we are done!
- if (bagFound.cert.subject.hash === bagFound.cert.issuer.hash) {
- return certificatePemChain;
- }
- // save which is the next bag we need
- nextBagId = bagFound.cert.issuer.hash;
- // go for the next in the list of discarded ones
- bagFound = discardedBags[nextBagId];
- }
- }
- }
- }
- // Check whether any certificate safe bags were found.
- if (certificatePemChain.length === 0) {
- throw new exceptions.CryptoLibException(
- 'Could not find any certificates for that alias.');
- }
- return certificatePemChain;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not retrieve certificate chain from PKCS12.', error);
- }
- },
- /**
- * Retrieves an issuer certificate from the certificate chain of the
- * PKCS12, given the issuer common name.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @param issuerCn
- * Issuer common name of certificate to retrieve, as string.
- * @return Certificate with given issuer common name, as string in PEM
- * format.
- */
- getCertificateByIssuer: function(passwordB64, issuerCn) {
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- // Retrieve certificate from PKCS12.
- var certificate = null;
- var certificateFound = false;
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.certBag &&
- safeBag.cert.issuer.getField('CN').value === issuerCn) {
- certificate = safeBag.cert;
- certificateFound = true;
- break;
- }
- }
- if (certificateFound) {
- break;
- }
- }
- // Check whether certificate was found.
- if (certificate === null) {
- throw new exceptions.CryptoLibException(
- 'Could not find certificate in PKCS12 with issuer common name ' +
- issuerCn);
- }
- return forge.pki.certificateToPem(certificate);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not retrieve certificate with issuer common name ' +
- issuerCn + ' from PKCS12.',
- error);
- }
- },
- /**
- * Retrieves the subject certificate from the certificate chain of the
- * PKCS12, given the subject common name.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @param subjectCn
- * Subject common name of certificate to retrieve, as string.
- * @return Certificate with given issuer common name, as string in PEM
- * format.
- */
- getCertificateBySubject: function(passwordB64, subjectCn) {
- try {
- var password = converters.base64Decode(passwordB64);
- var pkcs12 =
- forge.pkcs12.pkcs12FromAsn1(this.pkcs12Asn1, false, password);
- // Retrieve subject certificate from PKCS12.
- var certificate = null;
- var certificateFound = false;
- for (var i = 0; i < pkcs12.safeContents.length; i++) {
- var safeContents = pkcs12.safeContents[i];
- for (var j = 0; j < safeContents.safeBags.length; j++) {
- var safeBag = safeContents.safeBags[j];
- if (safeBag.type === forge.pki.oids.certBag &&
- safeBag.cert.subject.getField('CN').value === subjectCn) {
- certificate = safeBag.cert;
- certificateFound = true;
- break;
- }
- }
- if (certificateFound) {
- break;
- }
- }
- // Check whether certificate was found.
- if (certificate === null) {
- throw new exceptions.CryptoLibException(
- 'Could not find certificate in PKCS12 with subject common name ' +
- subjectCn);
- }
- return forge.pki.certificateToPem(certificate);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Could not retrieve certificate with subject common name ' +
- subjectCn + ' from PKCS12.',
- error);
- }
- },
- /**
- * Retrieves the PKCS12 as a Base64 encoded DER string.
- *
- * @return PKCS12, as Base64 encoded DER string.
- */
- getBase64Encoded: function() {
- return converters.base64Encode(this.pkcs12Der);
- }
- };
- /**
- * Container class for a chain of private keys to be inserted in a key
- * store.
- */
- box.stores.pkcs12.PrivateKeyChain = function() {
- this.map = {};
- };
- box.stores.pkcs12.PrivateKeyChain.prototype = {
- /**
- * Adds a private key to the chain.
- *
- * @param alias
- * Alias of private key, as string.
- * @param privateKeyPem
- * Private key to add, as string in PEM format.
- */
- add: function(alias, privateKeyPem) {
- this.map[alias] = privateKeyPem;
- },
- /**
- * Retrieves a private key from the chain.
- *
- * @return Private key chain, as array of strings in PEM format.
- */
- get: function(alias) {
- return this.map[alias];
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.stores = cryptolib.modules.stores || {};
- /**
- * A module that provides stores services.
- * <P>
- */
- cryptolib.modules.stores.service = function(box) {
- 'use strict';
- box.stores = box.stores || {};
- box.stores.service = {};
- var sks;
- cryptolib('stores.sks', function(box) {
- sks = box.stores.sks;
- });
- /**
- * @static
- *
- * @returns a Sks object.
- */
- box.stores.service.loadStore = function(store) {
- return new sks.SksReader(store);
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- /**
- * Scytl Key Store. It is a custom keystore.
- */
- cryptolib.modules.stores.sks = function(box) {
- 'use strict';
- box.stores = box.stores || {};
- box.stores.sks = {};
- var converters;
- var secretKeyGeneratorFactory;
- var cipher;
- var pkcs12Module;
- var exceptions;
- var homomorphicKeyFactory;
- var f = function(box) {
- converters = new box.commons.utils.Converters();
- cipher = (new box.symmetric.cipher.factory.SymmetricCipherFactory())
- .getCryptoSymmetricCipher();
- secretKeyGeneratorFactory =
- new box.primitives.derivation.factory.SecretKeyGeneratorFactory();
- pkcs12Module = box.stores.pkcs12;
- exceptions = box.commons.exceptions;
- homomorphicKeyFactory = new box.homomorphic.keypair.factory.KeyFactory();
- };
- f.policies = {
- symmetric: {
- secretkey: {
- encryption:
- {length: box.policies.symmetric.secretkey.encryption.length},
- mac: {length: box.policies.symmetric.secretkey.mac.length},
- secureRandom:
- {provider: box.policies.symmetric.secretkey.secureRandom.provider}
- },
- cipher: {
- provider: box.policies.symmetric.cipher.provider,
- algorithm: box.policies.symmetric.cipher.algorithm,
- initializationVectorLengthBytes:
- box.policies.symmetric.cipher.initializationVectorLengthBytes,
- secureRandom:
- {provider: box.policies.symmetric.cipher.secureRandom.provider}
- }
- },
- primitives: {
- derivation: {
- pbkdf: {
- provider: box.policies.primitives.derivation.pbkdf.provider,
- hash: box.policies.primitives.derivation.pbkdf.hash,
- saltLengthBytes:
- box.policies.primitives.derivation.pbkdf.saltLengthBytes,
- keyLengthBytes:
- box.policies.primitives.derivation.pbkdf.keyLengthBytes,
- iterations: box.policies.primitives.derivation.pbkdf.iterations
- }
- }
- }
- };
- cryptolib(
- 'commons', 'primitives.derivation', 'symmetric.cipher', 'stores.pkcs12',
- 'homomorphic.keypair', f);
- /**
- * Defines a SksReader.
- *
- * @param data.
- */
- box.stores.sks.SksReader = function(data) {
- // A cache of keys derived from store passwords, to prevent consecutive
- // operations on a keystore to derive keys each time.
- var bigintKeys = {};
- var derivedKeys = {};
- // Create the PBKDF generator.
- var cryptoPbkdfSecretKeyGenerator = secretKeyGeneratorFactory.createPBKDF();
- try {
- var loadKeyStore = function(data) {
- var keyStore;
- if (data) {
- if (typeof data === 'string') {
- keyStore = JSON.parse(data);
- } else if (typeof data === 'object') {
- keyStore = data;
- }
- }
- return keyStore;
- };
- var validateKeyStoreStructure = function(keyStore) {
- if (typeof keyStore.salt === 'undefined') {
- throw new Error('Missing salt');
- }
- if (typeof keyStore.store === 'undefined') {
- throw new Error('Missing store');
- }
- };
- this.keyStore = loadKeyStore(data);
- validateKeyStoreStructure(this.keyStore);
- this.store = new pkcs12Module.Pkcs12(this.keyStore.store);
- } catch (error) {
- throw new Error('Invalid keyStore: ' + error.message);
- }
- function validateEncryptedKey(encryptedKey, keyType) {
- if (!encryptedKey) {
- throw new exceptions.CryptoLibException(
- 'The keyStore does not contain a key of type ' + keyType);
- }
- }
- /**
- * Derive a key from the keystore password.
- *
- * @param {string} passwordB64 the Base64-encoded keystore password
- * @returns the Base64-encoded key derived from the password
- */
- this._deriveKey = function(passwordB64) {
- return cryptoPbkdfSecretKeyGenerator.generateSecret(
- passwordB64, this.keyStore.salt);
- };
- /**
- * Get the Base64-encoded key derived from the store password.
- *
- * @param {string} passwordB64 the Base64-encoded store password
- * @return the Base64-encoded key derived from the store password
- */
- this._getDerivedKey = function(passwordB64) {
- if (!derivedKeys.hasOwnProperty(passwordB64)) {
- derivedKeys[passwordB64] = this._deriveKey(passwordB64);
- }
- return derivedKeys[passwordB64];
- };
- /**
- * Get the Base64-encoded BigInteger representation of the key derived from
- * the store password.
- *
- * @param {string} passwordB64 the Base64-encoded store password
- * @returns the Base64-encoded BigInteger representation of the key derived
- * from the store password
- */
- this._getBigIntKey = function(passwordB64) {
- if (!bigintKeys.hasOwnProperty(passwordB64)) {
- var derivedPasswordBase64 = this._getDerivedKey(passwordB64);
- var derivedPassword = converters.bytesFromString(
- converters.base64Decode(derivedPasswordBase64));
- var derivedPasswordString =
- new box.forge.jsbn.BigInteger(derivedPassword);
- var longPasswordB64 =
- converters.base64Encode(derivedPasswordString.toString(36));
- bigintKeys[passwordB64] = longPasswordB64;
- }
- return bigintKeys[passwordB64];
- };
- this._getKey = function(alias, encryptedKey, passwordB64, keyType) {
- validateEncryptedKey(encryptedKey, keyType);
- var aliasAndKeyBase64 = this.decryptKey(encryptedKey, passwordB64);
- var aliasAndKey = converters.base64Decode(aliasAndKeyBase64);
- var decryptedAlias = aliasAndKey.slice(0, alias.length);
- if (decryptedAlias !== alias) {
- throw new exceptions.CryptoLibException(
- 'The decrypted ' + keyType +
- ' key does not correspond to the given alias.');
- }
- var key = aliasAndKey.slice(alias.length, aliasAndKey.length);
- var keyBase64 = converters.base64Encode(key);
- return keyBase64;
- };
- };
- box.stores.sks.SksReader.prototype = {
- getPrivateKeys: function(passwordB64) {
- var updateArguments = function(bigIntKey, args) {
- var argumentsCopy = Array.prototype.slice.call(args, 1);
- argumentsCopy.unshift(bigIntKey);
- return argumentsCopy;
- };
- return this.store.getPrivateKey.apply(
- this.store,
- updateArguments(this._getBigIntKey(passwordB64), arguments));
- },
- getSecretKey: function(alias, passwordB64) {
- var encryptedKey = this.keyStore.secrets[alias];
- return this._getKey(alias, encryptedKey, passwordB64, 'secret');
- },
- getElGamalPrivateKey: function(alias, passwordB64) {
- var encryptedKey = this.keyStore.egPrivKeys[alias];
- var keyBase64 =
- this._getKey(alias, encryptedKey, passwordB64, 'ElGamal private');
- return homomorphicKeyFactory.createPrivateKey(keyBase64);
- },
- decryptKey: function(encryptedKey, passwordB64) {
- return cipher.decrypt(this._getDerivedKey(passwordB64), encryptedKey);
- },
- /**
- * Retrieves the private key chain
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @return Private key chain of as PrivateKeyChain object, which
- * contains aliases and their related private keys in PEM
- * format.
- */
- getPrivateKeyChain: function(passwordB64) {
- return this.store.getPrivateKeyChain(this._getBigIntKey(passwordB64));
- },
- /**
- * Retrieves the full certificate chain.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @return Certificate chain as array of strings in PEM format.
- */
- getCertificateChain: function(passwordB64) {
- return this.store.getCertificateChain(this._getBigIntKey(passwordB64));
- },
- /**
- * Retrieves a certificate chain by private key alias
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @param alias
- * Alias to filter
- * @return Certificate chain as array of strings in PEM format.
- */
- getCertificateChainByAlias: function(passwordB64, alias) {
- return this.store.getCertificateChainByAlias(
- this._getBigIntKey(passwordB64), alias);
- },
- /**
- * Retrieves a certificate by subject common name.
- *
- * @param passwordB64
- * Password as string in Base64 encoded format.
- * @param subjectCn
- * Subject common name of certificate to retrieve, as string.
- * @return Certificate with given subject common name, as string in PEM
- * format.
- */
- getCertificateBySubject: function(passwordB64, subjectCn) {
- return this.store.getCertificateBySubject(
- this._getBigIntKey(passwordB64), subjectCn);
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
- /**
- * Defines the symmetric ciphers.
- *
- * @namespace symmetric/cipher
- */
- cryptolib.modules.symmetric.cipher = function(box) {
- 'use strict';
- box.symmetric = box.symmetric || {};
- box.symmetric.cipher = {};
- /**
- * Allows a symmetric cipher factory to be obtained.
- *
- * @exports symmetric/cipher/factory
- */
- box.symmetric.cipher.factory = {};
- var policies = {
- cipher: {
- algorithm: box.policies.symmetric.cipher.algorithm,
- provider: box.policies.symmetric.cipher.provider,
- initializationVectorLengthBytes:
- box.policies.symmetric.cipher.initializationVectorLengthBytes
- }
- };
- for (var prop in policies.cipher.algorithm) {
- if (typeof prop !== 'undefined') {
- policies.cipher.algorithm = policies.cipher.algorithm[prop];
- }
- }
- var utils, exceptions, randomFactory;
- var f = function(box) {
- utils = box.commons.utils;
- exceptions = box.commons.exceptions;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.symmetric.cipher.secureRandom.provider}
- }
- };
- cryptolib('commons', 'primitives.securerandom', f);
- /**
- * Factory class that allows a symmetric cipher to be obtained.
- *
- * @class
- */
- box.symmetric.cipher.factory.SymmetricCipherFactory = function() {};
- box.symmetric.cipher.factory.SymmetricCipherFactory.prototype = {
- /**
- * Create a new symmetric cipher.
- * <p>
- * The particular cipher that is returned depends on the policies.
- *
- * @function
- * @returns a new symmetric cipher.
- */
- getCryptoSymmetricCipher: function() {
- var secureRandom;
- try {
- if (policies.cipher.provider ===
- Config.symmetric.cipher.provider.FORGE) {
- secureRandom = randomFactory.getCryptoRandomBytes();
- return this.getCryptoForgeSymmetricCipher(secureRandom);
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoSymmetricCipher could not be obtained.', error);
- }
- },
- /**
- * Create a new CryptoForgeSymmetricCipher.
- *
- * @function
- * @param secureRandom
- * {CryptoScytlRandomBytes} a secure source of random bytes.
- * @returns {symmetric/cipher.CryptoForgeSymmetricCipher} a new
- * CryptoForgeSymmetricCipher.
- */
- getCryptoForgeSymmetricCipher: function(secureRandom) {
- return new CryptoForgeSymmetricCipher(secureRandom);
- }
- };
- /**
- * @class
- * @param randomGenerator
- * {CryptoScytlRandomBytes} a secure random bytes generator.
- * @memberof symmetric/cipher
- */
- function CryptoForgeSymmetricCipher(randomGenerator) {
- this.converters = new utils.Converters();
- this.bitOperators = new utils.BitOperators();
- this.randomGenerator = randomGenerator;
- }
- CryptoForgeSymmetricCipher.prototype = {
- /**
- * Encrypts some data.
- *
- * @function
- * @param data
- * {String} Data to be encrypted, as string in Base64 encoded
- * format.
- * @param keyB64
- * {String} Key, as string in Base64 encoded format.
- * @returns Initialization vector concatenated with the encrypted data,
- * as string in Base64 encoded format.
- */
- encrypt: function(keyB64, dataB64) {
- try {
- var key = this.converters.base64Decode(keyB64);
- var data = this.converters.base64Decode(dataB64);
- if (key.length !== policies.cipher.algorithm.keyLengthBytes) {
- throw new exceptions.CryptolibException(
- 'Key length does not match the required by the algorithm.');
- }
- var initVec = this.randomGenerator.nextRandom(
- policies.cipher.initializationVectorLengthBytes);
- // Create a byte buffer for data.
- var dataBuffer = new box.forge.util.ByteBuffer(data);
- var cipher =
- box.forge.cipher.createCipher(policies.cipher.algorithm.name, key);
- // Only for the GCM mode
- var gcmAuthTagByteLength = policies.cipher.algorithm.tagLengthBytes;
- if (typeof gcmAuthTagBitLength !== 'undefined') {
- cipher.start({iv: initVec, tagLength: gcmAuthTagByteLength});
- } else {
- cipher.start({iv: initVec});
- }
- cipher.update(dataBuffer);
- cipher.finish();
- var encryptedData = cipher.output.getBytes().toString();
- if (typeof gcmAuthTagByteLength !== 'undefined') {
- var gcmAuthTag = cipher.mode.tag.getBytes();
- encryptedData = encryptedData + gcmAuthTag.toString();
- }
- var initVectorAndEncryptedData = initVec + encryptedData;
- var initVectorAndEncryptedDataBase64 =
- this.converters.base64Encode(initVectorAndEncryptedData);
- return initVectorAndEncryptedDataBase64;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Data could not be symmetrically encrypted.', error);
- }
- },
- /**
- * Decrypts some encrypted data, using the initialization vector that is
- * provided
- *
- * @function
- * @param keyB64
- * {String} the key as a string in Base64 encoded format.
- * @param initVectorAndEncryptedDataBase64
- * {String} Initialization vector concatenated with the
- * encrypted data, as string in Base64 encoded format.
- * @returns Decrypted data, as string in Base64 encoded format.
- */
- decrypt: function(keyB64, initVectorAndEncryptedDataBase64) {
- try {
- var key = this.converters.base64Decode(keyB64);
- if (key.length !== policies.cipher.algorithm.keyLengthBytes) {
- throw new exceptions.CryptolibException(
- 'Key length does not match the required by the algorithm.');
- }
- var cipher = box.forge.cipher.createDecipher(
- policies.cipher.algorithm.name, key);
- var initVectorAndEncryptedData =
- this.converters.base64Decode(initVectorAndEncryptedDataBase64);
- var initVector = this.bitOperators.extract(
- initVectorAndEncryptedData, 0,
- policies.cipher.initializationVectorLengthBytes);
- var encryptedData = this.bitOperators.extract(
- initVectorAndEncryptedData,
- policies.cipher.initializationVectorLengthBytes,
- initVectorAndEncryptedData.length);
- // Only for the GCM mode
- var gcmAuthTagByteLength = policies.cipher.algorithm.tagLengthBytes;
- if (typeof gcmAuthTagByteLength !== 'undefined') {
- var offset = encryptedData.length - gcmAuthTagByteLength;
- var gcmAuthTag = this.bitOperators.extract(
- encryptedData, offset, encryptedData.length);
- encryptedData = this.bitOperators.extract(encryptedData, 0, offset);
- var gcmAuthTagBitLength =
- gcmAuthTagByteLength * box.NUMBER_OF_BITS_PER_BYTE;
- cipher.start({
- iv: initVector,
- tagLength: gcmAuthTagBitLength,
- tag: gcmAuthTag
- });
- } else {
- cipher.start({iv: initVector});
- }
- var encryptedDataBuffer = new box.forge.util.ByteBuffer(encryptedData);
- cipher.update(encryptedDataBuffer);
- cipher.finish();
- var outputBase64 =
- this.converters.base64Encode(cipher.output.getBytes().toString());
- return outputBase64;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'Data could not be symmetrically decrypted.', error);
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
- /**
- * Defines the MACs of the module.
- *
- * @namespace symmetric/mac
- */
- cryptolib.modules.symmetric.mac = function(box) {
- 'use strict';
- box.symmetric = box.symmetric || {};
- box.symmetric.mac = {};
- /**
- * Allows a symmetric MAC factory to be obtained.
- *
- * @exports symmetric/mac/factory
- */
- box.symmetric.mac.factory = {};
- var policies = {
- mac: {
- hash: box.policies.symmetric.mac.hash,
- provider: box.policies.symmetric.mac.provider
- }
- };
- var converters;
- var exceptions;
- cryptolib('commons', function(box) {
- converters = new box.commons.utils.Converters();
- exceptions = box.commons.exceptions;
- });
- /**
- * Factory class that allows a MAC to be obtained.
- *
- * @class
- */
- box.symmetric.mac.factory.MacFactory = function() {};
- box.symmetric.mac.factory.MacFactory.prototype = {
- /**
- * Create a new MAC.
- * <p>
- * The particular MAC that is returned depends on the policies.
- *
- * @function
- * @returns a new MAC.
- */
- create: function() {
- try {
- if (policies.mac.provider === Config.symmetric.mac.provider.FORGE) {
- return this.createCryptoForgeMac();
- } else {
- throw new exceptions.CryptoLibException(
- 'No suitable provider was provided.');
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'A CryptoMac could not be obtained.', error);
- }
- },
- /**
- * Create a new CryptoForgeMac.
- *
- * @function
- * @returns {symmetric/mac.CryptoForgeMac} a new CryptoForgeMac.
- */
- createCryptoForgeMac: function() {
- return new CryptoForgeMac();
- }
- };
- /**
- * Represents a MAC.
- *
- * @class
- * @memberof symmetric/mac
- */
- function CryptoForgeMac() {
- this.hmacDigester = forge.hmac.create();
- }
- CryptoForgeMac.prototype = {
- /**
- * Generates MAC for some data.
- *
- * @function
- * @param secretKeyBase64
- * {String} Secret key, as string in Base64 encoded format
- * @param arrayDataBase64
- * {String} The input data for the MAC, as an array of string
- * in Base64 encoded format. It is assumed that the array is
- * not empty.
- * @returns The generated MAC, in Base64 encoded format.
- */
- generate: function(secretKeyBase64, arrayDataBase64) {
- var secretKey = converters.base64Decode(secretKeyBase64);
- var secretKeyBuffer = new forge.util.ByteBuffer(secretKey);
- try {
- this.hmacDigester.start(policies.mac.hash, secretKeyBuffer);
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'MAC message digester could not be initialized.', error);
- }
- try {
- if (arrayDataBase64.length < 1) {
- throw new exceptions.CryptoLibException(
- 'The array of data should have at least one element');
- }
- var dataB64;
- for (var i = 0; i < arrayDataBase64.length; i++) {
- dataB64 = arrayDataBase64[i];
- var data = converters.base64Decode(dataB64);
- this.hmacDigester.update(data);
- }
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'MAC message digester could not be updated.', error);
- }
- try {
- var hmacMessageDigest = this.hmacDigester.digest();
- return converters.base64Encode(hmacMessageDigest.getBytes());
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'MAC message digest could not be generated.', error);
- }
- },
- /**
- * Verify that a given MAC is indeed the MAC for the given data, using
- * the given secret key.
- *
- * @function
- * @param macBase64
- * {String} The MAC to be verified, as string in Base64
- * encoded format.
- * @param secretKeyBase64
- * {String} Secret key, as string in Base64 encoded format
- * @param arrayDataBase64
- * {String} The input data for the MAC, as an array of string
- * in Base64 encoded format. It is assumed that the array is
- * not empty.
- *
- * @returns True if the MAC is the MAC of the given data and SecretKey,
- * false otherwise.
- */
- verify: function(macBase64, secretKeyBase64, arrayDataBase64) {
- if (typeof macBase64 === 'undefined' || macBase64 === null) {
- return false;
- }
- var macBase64ToVerify = this.generate(secretKeyBase64, arrayDataBase64);
- if (macBase64.length !== macBase64ToVerify.length) {
- return false;
- }
- var equals = true;
- for (var i = 0; i < macBase64ToVerify.length; i++) {
- if (macBase64ToVerify.charCodeAt(i) !== macBase64.charCodeAt(i)) {
- equals = false;
- }
- }
- return equals;
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
- /**
- * Defines a symmetric secret key
- *
- * @namespace symmetric/secretkey
- */
- cryptolib.modules.symmetric.secretkey = function(box) {
- 'use strict';
- box.symmetric = box.symmetric || {};
- box.symmetric.secretkey = {};
- /**
- * Allows a symmetric secret key factory to be obtained.
- *
- * @exports symmetric/secretkey/factory
- */
- box.symmetric.secretkey.factory = {};
- var policies = {
- secretkey: {
- encryption: {
- lengthBytes: box.policies.symmetric.secretkey.encryption.lengthBytes
- },
- mac: {lengthBytes: box.policies.symmetric.secretkey.mac.lengthBytes}
- }
- };
- var utils, randomFactory, exceptions, secureRandom, lengthBytes;
- var f = function(box) {
- utils = box.commons.utils;
- exceptions = box.commons.exceptions;
- randomFactory =
- new box.primitives.securerandom.factory.SecureRandomFactory();
- };
- f.policies = {
- primitives: {
- secureRandom:
- {provider: box.policies.symmetric.secretkey.secureRandom.provider}
- }
- };
- cryptolib('commons', 'primitives.securerandom', f);
- /**
- * Validates the received length argument, in bytes.
- *
- * Confirms that:
- * <ul>
- * <li>the type of <code>lengthBytes</code> is number.</li>
- * <li><code>lengthBytes</code> is an integer with a value not less than
- * 1.</li>
- * </ul>
- *
- * @function validateParameter
- * @param lengthBytes
- * {number} the length, in bytes, to be validated.
- */
- var validateParameter = function(lengthBytes) {
- if (typeof lengthBytes !== 'number' || lengthBytes % 1 !== 0 ||
- lengthBytes < 1) {
- throw new exceptions.CryptoLibException(
- 'The given key length is not valid.');
- }
- };
- /**
- * Represents a secret key factory.
- *
- * @class
- */
- box.symmetric.secretkey.factory.SecretKeyFactory = function() {
- secureRandom = randomFactory.getCryptoRandomBytes();
- };
- box.symmetric.secretkey.factory.SecretKeyFactory.prototype = {
- /**
- * Get a CryptoSecretKeyGenerator for encryption.
- *
- * @function
- * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
- * CryptoSecretKeyGenerator for encryption.
- */
- getCryptoSecretKeyGeneratorForEncryption: function() {
- lengthBytes = policies.secretkey.encryption.lengthBytes;
- return this.getCryptoSecretKeyGenerator();
- },
- /**
- * Get a CryptoSecretKeyGenerator for MAC.
- *
- * @function
- * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
- * CryptoSecretKeyGenerator for MAC.
- */
- getCryptoSecretKeyGeneratorForMac: function() {
- lengthBytes = policies.secretkey.mac.lengthBytes;
- return this.getCryptoSecretKeyGenerator();
- },
- /**
- * Create a new CryptoSecretKeyGenerator.
- *
- * @function
- * @returns {symmetric/secretkey.CryptoSecretKeyGenerator} a
- * CryptoSecretKeyGenerator.
- */
- getCryptoSecretKeyGenerator: function() {
- return new CryptoSecretKeyGenerator(secureRandom);
- }
- };
- /**
- * Defines a Secret Key generator.
- *
- * @class
- * @memberof symmetric/secretkey
- * @param randomGenerator
- * {CryptoScytlRandomBytes} a secure random bytes generator.
- */
- function CryptoSecretKeyGenerator(randomGenerator) {
- this.converters = new utils.Converters();
- this.randomGenerator = randomGenerator;
- }
- CryptoSecretKeyGenerator.prototype = {
- /**
- * Generates a secret key.
- *
- * @function
- * @return A secret key, as string in Base64 encoded format.
- */
- generate: function() {
- try {
- validateParameter(lengthBytes);
- var key = this.randomGenerator.nextRandom(lengthBytes);
- var keyBase64 = this.converters.base64Encode(key);
- return keyBase64;
- } catch (error) {
- throw new exceptions.CryptoLibException(
- 'CryptoSecretKey could not be generated.', error);
- }
- }
- };
- };
- /*
- * Copyright 2018 Scytl Secure Electronic Voting SA
- *
- * All rights reserved
- *
- * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
- */
- cryptolib.modules.symmetric = cryptolib.modules.symmetric || {};
- /**
- * Defines the symmetric service.
- * @namespace symmetric/service
- */
- cryptolib.modules.symmetric.service = function(box) {
- 'use strict';
- box.symmetric = box.symmetric || {};
- /**
- * A module that provides symmetric cryptographic services.
- * @exports symmetric/service
- */
- box.symmetric.service = {};
- var cipherFactory, secretKeyFactory, macFactory;
- cryptolib(
- 'symmetric.cipher', 'symmetric.secretkey', 'symmetric.mac',
- 'commons.exceptions', function(box) {
- cipherFactory =
- new box.symmetric.cipher.factory.SymmetricCipherFactory();
- secretKeyFactory =
- new box.symmetric.secretkey.factory.SecretKeyFactory();
- macFactory = new box.symmetric.mac.factory.MacFactory();
- });
- /**
- * @function getSecretKeyForEncryption
- * @returns {string} a secret key as a string encoded in Base64.
- */
- box.symmetric.service.getSecretKeyForEncryption = function() {
- var secretKeyGenerator =
- secretKeyFactory.getCryptoSecretKeyGeneratorForEncryption();
- return secretKeyGenerator.generate();
- };
- /**
- * @function getSecretKeyForMac
- * @returns {string} a MAC as a string encoded in Base64.
- */
- box.symmetric.service.getSecretKeyForMac = function() {
- var secretKeyGenerator =
- secretKeyFactory.getCryptoSecretKeyGeneratorForMac();
- return secretKeyGenerator.generate();
- };
- /**
- * @function encrypt
- * @returns {string} the initialization vector concatenated with the encrypted data,
- * as string in Base64 encoded format.
- */
- box.symmetric.service.encrypt = function(secretKeyBase64, dataBase64) {
- var cipher = cipherFactory.getCryptoSymmetricCipher();
- return cipher.encrypt(secretKeyBase64, dataBase64);
- };
- /**
- * @function decrypt
- * @returns {string} the decrypted data, as a String in Base64 encoded format.
- */
- box.symmetric.service.decrypt = function(
- secretKeyBase64, initVectorAndEncryptedDataBase64) {
- var cipher = cipherFactory.getCryptoSymmetricCipher();
- return cipher.decrypt(secretKeyBase64, initVectorAndEncryptedDataBase64);
- };
- /**
- * @function getMac
- * @returns {string} a string in Base64 encoded format.
- */
- box.symmetric.service.getMac = function(secretKeyBase64, arrayDataBase64) {
- var cryptoMac = macFactory.create();
- return cryptoMac.generate(secretKeyBase64, arrayDataBase64);
- };
- /**
- * @function verifyMac
- * @returns {boolean} true if the data has been verified.
- */
- box.symmetric.service.verifyMac = function(
- macBase64, secretKeyBase64, arrayDataBase64) {
- var cryptoMac = macFactory.create();
- return cryptoMac.verify(macBase64, secretKeyBase64, arrayDataBase64);
- };
- };
- if (typeof cryptoPRNG !== 'undefined') {
- cryptolib.cryptoPRNG = cryptoPRNG;
- cryptolib.Config = Config;
- if (typeof module !== 'undefined') {
- module.exports = cryptolib;
- };
- };
|