crypt.tex 413 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598
  1. \documentclass[synpaper]{book}
  2. \usepackage{geometry}
  3. \usepackage{hyperref}
  4. \usepackage{makeidx}
  5. \usepackage{amssymb}
  6. \usepackage{color}
  7. \usepackage{alltt}
  8. \usepackage{graphicx}
  9. \usepackage{layout}
  10. \usepackage{fancyhdr}
  11. \usepackage{float}
  12. \def\union{\cup}
  13. \def\intersect{\cap}
  14. \def\getsrandom{\stackrel{\rm R}{\gets}}
  15. \def\cross{\times}
  16. \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
  17. \def\catn{$\|$}
  18. \def\divides{\hspace{0.3em} | \hspace{0.3em}}
  19. \def\nequiv{\not\equiv}
  20. \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
  21. \def\lcm{{\rm lcm}}
  22. \def\gcd{{\rm gcd}}
  23. \def\log{{\rm log}}
  24. \def\ord{{\rm ord}}
  25. \def\abs{{\mathit abs}}
  26. \def\rep{{\mathit rep}}
  27. \def\mod{{\mathit\ mod\ }}
  28. \renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
  29. \newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
  30. \newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
  31. \def\Or{{\rm\ or\ }}
  32. \def\And{{\rm\ and\ }}
  33. \def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
  34. \def\implies{\Rightarrow}
  35. \def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
  36. \let\oldphi\phi
  37. \def\phi{\varphi}
  38. \def\Pr{{\rm Pr}}
  39. \newcommand{\str}[1]{{\mathbf{#1}}}
  40. \def\F{{\mathbb F}}
  41. \def\N{{\mathbb N}}
  42. \def\Z{{\mathbb Z}}
  43. \def\R{{\mathbb R}}
  44. \def\C{{\mathbb C}}
  45. \def\Q{{\mathbb Q}}
  46. \definecolor{DGray}{gray}{0.5}
  47. \newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
  48. \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
  49. \def\gap{\vspace{0.5ex}}
  50. \makeindex
  51. \newcommand{\mysection}[1] % Re-define the chaptering command to use
  52. { % THESE headers.
  53. \section{#1}
  54. \markboth{\textsf{www.libtom.net}}{\thesection ~ {#1}}
  55. }
  56. \newcommand{\mystarsection}[1] % Re-define the chaptering command to use
  57. { % THESE headers.
  58. \section*{#1}
  59. \markboth{\textsf{www.libtom.net}}{{#1}}
  60. }
  61. \pagestyle{empty}
  62. \begin{document}
  63. \frontmatter
  64. \pagestyle{empty}
  65. ~
  66. \vspace{2in}
  67. ~
  68. \begin{center}
  69. \begin{Huge}LibTomCrypt\end{Huge}
  70. ~
  71. \begin{large}Developer Manual\end{large}
  72. ~
  73. \vspace{15mm}
  74. \begin{tabular}{c}
  75. LibTom Projects
  76. \end{tabular}
  77. \end{center}
  78. \vfil
  79. \newpage
  80. This document is part of the LibTomCrypt package and is hereby released into the public domain.
  81. ~
  82. Open Source. Open Academia. Open Minds.
  83. ~
  84. \begin{flushright}
  85. LibTom Projects
  86. ~
  87. \& originally
  88. ~
  89. Tom St Denis
  90. ~
  91. Ottawa, Ontario
  92. ~
  93. Canada
  94. ~
  95. \vfil
  96. \end{flushright}
  97. \newpage
  98. \tableofcontents
  99. \listoffigures
  100. \pagestyle{myheadings}
  101. \mainmatter
  102. \chapter{Introduction}
  103. \mysection{What is the LibTomCrypt?}
  104. LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
  105. designing cryptosystems. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
  106. public key cryptography (via PKCS \#1 RSA, DH or ECDH), and a plethora of support routines.
  107. The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
  108. (and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
  109. block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
  110. also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
  111. \mysection{Why did I write it?}
  112. You may be wondering, \textit{Tom, why did you write a crypto library. I already have one.} Well the reason falls into
  113. two categories:
  114. \begin{enumerate}
  115. \item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
  116. \item It was (still is) good coding practice.
  117. \end{enumerate}
  118. The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
  119. {\bf own} crypto library and hopefully along the way others will appreciate the work.
  120. With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
  121. and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
  122. on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
  123. know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
  124. that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time. That means your
  125. application can support all ciphers/hashes/prngs/bignum without changing the source code.
  126. Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
  127. configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
  128. without having to use configure scripts. This means that the library will work with platforms where development
  129. tools may be limited (e.g. no autoconf).
  130. On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
  131. robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
  132. arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
  133. with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
  134. Crypto++.
  135. \subsection{Modular}
  136. The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
  137. pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
  138. are essentially structures with pointers to functions. While you can still call particular functions
  139. directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
  140. usage of the library.
  141. For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
  142. that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
  143. is write a descriptor and the few support routines required for the device. After that the rest of the
  144. API can make use of it without change. Similarly imagine a few years down the road when AES2
  145. (\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
  146. with zero modifications to the end applications provided they are written properly.
  147. This flexibility within the library means it can be used with any combination of primitive algorithms and
  148. unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
  149. mode routines for every single cipher. That means every time you add or remove a cipher from the library
  150. you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
  151. are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
  152. the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
  153. can make use of the cipher right away.
  154. \mysection{License}
  155. The project is hereby released as public domain.
  156. \mysection{Patent Disclosure}
  157. The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
  158. of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
  159. They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}. The rest
  160. of the ciphers and hashes are patent free or under patents that have since expired.
  161. The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
  162. the ciphers you just can't advertise that you are doing so.
  163. \mysection{Thanks}
  164. I would like to give thanks to the following people (in no particular order) for helping me develop this project from
  165. early on:
  166. \begin{enumerate}
  167. \item Richard van de Laarschot
  168. \item Richard Heathfield
  169. \item Ajay K. Agrawal
  170. \item Brian Gladman
  171. \item Svante Seleborg
  172. \item Clay Culver
  173. \item Jason Klapste
  174. \item Dobes Vandermeer
  175. \item Daniel Richards
  176. \item Wayne Scott
  177. \item Andrew Tyler
  178. \item Sky Schulz
  179. \item Christopher Imes
  180. \end{enumerate}
  181. There have been quite a few other people as well. Please check the change log to see who else has contributed from
  182. time to time.
  183. \chapter{The Application Programming Interface (API)}
  184. \mysection{Introduction}
  185. \index{CRYPT\_ERROR} \index{CRYPT\_OK}
  186. In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
  187. that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
  188. if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
  189. commented upon. When a function does return a CRYPT error code it can be translated into a string with
  190. \index{error\_to\_string()}
  191. \begin{verbatim}
  192. const char *error_to_string(int err);
  193. \end{verbatim}
  194. An example of handling an error is:
  195. \begin{small}
  196. \begin{verbatim}
  197. void somefunc(void)
  198. {
  199. int err;
  200. /* call a cryptographic function */
  201. if ((err = some_crypto_function(...)) != CRYPT_OK) {
  202. printf("A crypto error occurred, %s\n", error_to_string(err));
  203. /* perform error handling */
  204. }
  205. /* continue on if no error occurred */
  206. }
  207. \end{verbatim}
  208. \end{small}
  209. There is no initialization routine for the library and for the most part the code is thread safe. The only thread
  210. related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
  211. that is not an issue.
  212. To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
  213. \begin{small}
  214. \begin{verbatim}
  215. #include <tomcrypt.h>
  216. int main(void) {
  217. return 0;
  218. }
  219. \end{verbatim}
  220. \end{small}
  221. The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
  222. \mysection{Macros}
  223. There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
  224. 32/64-bit words in little/big endian format. The macros are:
  225. \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
  226. \newpage
  227. \begin{figure}[hpbt]
  228. \begin{small}
  229. \begin{center}
  230. \begin{tabular}{|c|c|c|}
  231. \hline STORE32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
  232. \hline STORE64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
  233. \hline LOAD32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
  234. \hline LOAD64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
  235. \hline STORE32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
  236. \hline STORE64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
  237. \hline LOAD32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
  238. \hline LOAD64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
  239. \hline BSWAP(x) & {\bf ulong32} x & Swap bytes \\
  240. \hline
  241. \end{tabular}
  242. \caption{Load And Store Macros}
  243. \end{center}
  244. \end{small}
  245. \end{figure}
  246. There are 32 and 64-bit cyclic rotations as well:
  247. \index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
  248. \begin{figure}[hpbt]
  249. \begin{small}
  250. \begin{center}
  251. \begin{tabular}{|c|c|c|}
  252. \hline ROL(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x << y, 0 \le y \le 31$ \\
  253. \hline ROLc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x << y, 0 \le y \le 31$ \\
  254. \hline ROR(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x >> y, 0 \le y \le 31$ \\
  255. \hline RORc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x >> y, 0 \le y \le 31$ \\
  256. \hline && \\
  257. \hline ROL64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x << y, 0 \le y \le 63$ \\
  258. \hline ROL64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x << y, 0 \le y \le 63$ \\
  259. \hline ROR64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x >> y, 0 \le y \le 63$ \\
  260. \hline ROR64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x >> y, 0 \le y \le 63$ \\
  261. \hline
  262. \end{tabular}
  263. \caption{Rotate Macros}
  264. \end{center}
  265. \end{small}
  266. \end{figure}
  267. \mysection{Functions with Variable Length Output}
  268. Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length. To prevent buffer overflows you
  269. must pass it the length of the buffer where the output will be stored. For example:
  270. \index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
  271. \begin{small}
  272. \begin{verbatim}
  273. #include <tomcrypt.h>
  274. int main(void) {
  275. rsa_key key;
  276. unsigned char buffer[1024];
  277. unsigned long x;
  278. int err;
  279. /* ... Make up the RSA key somehow ... */
  280. /* lets export the key, set x to the size of the
  281. * output buffer */
  282. x = sizeof(buffer);
  283. if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
  284. printf("Export error: %s\n", error_to_string(err));
  285. return -1;
  286. }
  287. /* if rsa_export() was successful then x will have
  288. * the size of the output */
  289. printf("RSA exported key takes %d bytes\n", x);
  290. /* ... do something with the buffer */
  291. return 0;
  292. }
  293. \end{verbatim}
  294. \end{small}
  295. In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
  296. indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
  297. \textit{x} so that the calling application will know how many bytes were used.
  298. As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
  299. support this so please check the source before you rely on it doing that.
  300. \mysection{Functions that need a PRNG}
  301. \index{Pseudo Random Number Generator} \index{PRNG}
  302. Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG). These functions do not setup
  303. the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
  304. Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example). The \textit{prng\_state} argument
  305. may be passed as \textbf{NULL} in such situations.
  306. \index{register\_prng()} \index{rsa\_make\_key()}
  307. \begin{small}
  308. \begin{verbatim}
  309. #include <tomcrypt.h>
  310. int main(void) {
  311. rsa_key key;
  312. int err;
  313. /* register the system RNG */
  314. register_prng(&sprng_desc)
  315. /* make a 1024-bit RSA key with the system RNG */
  316. if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key))
  317. != CRYPT_OK) {
  318. printf("make_key error: %s\n", error_to_string(err));
  319. return -1;
  320. }
  321. /* use the key ... */
  322. return 0;
  323. }
  324. \end{verbatim}
  325. \end{small}
  326. \mysection{Functions that use Arrays of Octets}
  327. Most functions require inputs that are arrays of the data type \textit{unsigned char}. Whether it is a symmetric key, IV
  328. for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
  329. lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
  330. must pass in (a pointer to) an array of 32 \textit{unsigned char} variables. Certain routines (such as SAFER+) take
  331. special care to work properly on platforms where an \textit{unsigned char} is not eight bits.
  332. For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word. Typically an array of
  333. type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}
  334. \chapter{Symmetric Block Ciphers}
  335. \mysection{Core Functions}
  336. LibTomCrypt provides several block ciphers with an ECB block mode interface. It is important to first note that you
  337. should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
  338. or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
  339. the API to grow in a modular fashion.
  340. \subsection{Key Scheduling}
  341. All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}. This allows all ciphers to
  342. have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
  343. allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers must provide six visible
  344. functions which are (given that XXX is the name of the cipher) the following:
  345. \index{Cipher Setup}
  346. \begin{verbatim}
  347. int XXX_setup(const unsigned char *key,
  348. int keylen,
  349. int rounds,
  350. symmetric_key *skey);
  351. \end{verbatim}
  352. The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
  353. The number of rounds can be set to zero to use the default, which is generally a good idea.
  354. If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it. It's important to note
  355. that you should only used this scheduled key with the intended cipher. For example, if you call \textit{blowfish\_setup()} do not
  356. pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}. All built--in setup functions do not allocate memory off the heap so
  357. when you are done with a key you can simply discard it (e.g. they can be on the stack). However, to maintain proper coding
  358. practices you should always call the respective XXX\_done() function. This allows for quicker porting to applications with
  359. externally supplied plugins.
  360. \subsection{ECB Encryption and Decryption}
  361. To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
  362. \index{Cipher Encrypt} \index{Cipher Decrypt}
  363. \begin{verbatim}
  364. int XXX_ecb_encrypt(const unsigned char *pt,
  365. unsigned char *ct,
  366. symmetric_key *skey);
  367. int XXX_ecb_decrypt(const unsigned char *ct,
  368. unsigned char *pt,
  369. symmetric_key *skey);
  370. \end{verbatim}
  371. These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
  372. which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.). It is possible that the input and output buffer are
  373. the same buffer. For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
  374. \textit{ct}\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
  375. return \textbf{CRYPT\_OK} on success. To test a particular cipher against test vectors\footnote{As published in their design papers.}
  376. call the following self-test function.
  377. \subsection{Self--Testing}
  378. \index{Cipher Testing}
  379. \begin{verbatim}
  380. int XXX_test(void);
  381. \end{verbatim}
  382. This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
  383. based upon.
  384. \subsection{Key Sizing}
  385. For each cipher there is a function which will help find a desired key size. It is specified as follows:
  386. \index{Key Sizing}
  387. \begin{verbatim}
  388. int XXX_keysize(int *keysize);
  389. \end{verbatim}
  390. Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size. This function
  391. will return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
  392. \begin{small}
  393. \begin{verbatim}
  394. #include <tomcrypt.h>
  395. int main(void)
  396. {
  397. int keysize, err;
  398. /* now given a 20 byte key what keysize does Twofish want to use? */
  399. keysize = 20;
  400. if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
  401. printf("Error getting key size: %s\n", error_to_string(err));
  402. return -1;
  403. }
  404. printf("Twofish suggested a key size of %d\n", keysize);
  405. return 0;
  406. }
  407. \end{verbatim}
  408. \end{small}
  409. This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}
  410. \subsection{Cipher Termination}
  411. When you are finished with a cipher you can de--initialize it with the done function.
  412. \begin{verbatim}
  413. void XXX_done(symmetric_key *skey);
  414. \end{verbatim}
  415. For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
  416. cipher descriptors may require to be called for resource management purposes. To be compliant, all functions which call a cipher
  417. setup function must also call the respective cipher done function when finished.
  418. \subsection{Simple Encryption Demonstration}
  419. An example snippet that encodes a block with Blowfish in ECB mode.
  420. \index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
  421. \begin{small}
  422. \begin{verbatim}
  423. #include <tomcrypt.h>
  424. int main(void)
  425. {
  426. unsigned char pt[8], ct[8], key[8];
  427. symmetric_key skey;
  428. int err;
  429. /* ... key is loaded appropriately in key ... */
  430. /* ... load a block of plaintext in pt ... */
  431. /* schedule the key */
  432. if ((err = blowfish_setup(key, /* the key we will use */
  433. 8, /* key is 8 bytes (64-bits) long */
  434. 0, /* 0 == use default # of rounds */
  435. &skey) /* where to put the scheduled key */
  436. ) != CRYPT_OK) {
  437. printf("Setup error: %s\n", error_to_string(err));
  438. return -1;
  439. }
  440. /* encrypt the block */
  441. blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
  442. ct, /* store encrypted data here */
  443. &skey); /* our previously scheduled key */
  444. /* now ct holds the encrypted version of pt */
  445. /* decrypt the block */
  446. blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
  447. pt, /* store decrypted data here */
  448. &skey); /* our previously scheduled key */
  449. /* now we have decrypted ct to the original plaintext in pt */
  450. /* Terminate the cipher context */
  451. blowfish_done(&skey);
  452. return 0;
  453. }
  454. \end{verbatim}
  455. \end{small}
  456. \mysection{Key Sizes and Number of Rounds}
  457. \index{Symmetric Keys}
  458. As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it. Only a few of the ciphers support smaller
  459. keys (mainly for test vectors anyways). Ideally, your application should be making at least 256 bit keys. This is not
  460. because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
  461. example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
  462. total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
  463. were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
  464. only 53 bits of entropy.
  465. The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
  466. rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
  467. ciphers are configured such that the default number of rounds provide adequate security for the given block and key
  468. size.
  469. \mysection{The Cipher Descriptors}
  470. \index{Cipher Descriptor}
  471. To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}. An element
  472. of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
  473. \begin{small}
  474. \begin{verbatim}
  475. struct ltc_cipher_descriptor {
  476. /** name of cipher */
  477. char *name;
  478. /** internal ID */
  479. unsigned char ID;
  480. /** min keysize (octets) */
  481. int min_key_length,
  482. /** max keysize (octets) */
  483. max_key_length,
  484. /** block size (octets) */
  485. block_length,
  486. /** default number of rounds */
  487. default_rounds;
  488. ...<snip>...
  489. };
  490. \end{verbatim}
  491. \end{small}
  492. Where \textit{name} is the lower case ASCII version of the name. The fields \textit{min\_key\_length} and \textit{max\_key\_length}
  493. are the minimum and maximum key sizes in bytes. The \textit{block\_length} member is the block size of the cipher
  494. in bytes. As a good rule of thumb it is assumed that the cipher supports
  495. the min and max key lengths but not always everything in between. The \textit{default\_rounds} field is the default number
  496. of rounds that will be used.
  497. For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
  498. and if missing will be emulated in software.
  499. The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
  500. marked when \textit{name} equals {\bf NULL}.
  501. As of this release the current cipher\_descriptors elements are the following:
  502. \vfil
  503. \index{Cipher descriptor table}
  504. \index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
  505. \index{des\_desc} \index{des3\_desc} \index{noekeon\_desc} \index{skipjack\_desc} \index{anubis\_desc} \index{khazad\_desc} \index{kseed\_desc} \index{kasumi\_desc} \index{camellia\_desc} \index{aes\_enc\_desc}
  506. \index{idea\_desc} \index{serpent\_desc} \index{tea\_desc}
  507. \begin{figure}[hpbt]
  508. \begin{small}
  509. \begin{center}
  510. \begin{tabular}{|c|c|c|c|c|c|c|}
  511. \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} & \textbf{Id} \\
  512. \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 & 0 \\
  513. \hline X-Tea & xtea\_desc & 8 & 16 & 32 & 1 \\
  514. \hline RC2 & rc2\_desc & 8 & 5 $\ldots$ 128 & 16 & 12 \\
  515. \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 & 2 \\
  516. \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 & 3 \\
  517. \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 & 4 \\
  518. \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 & 6 \\
  519. & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 & 6 \\
  520. & rijndael\_desc & 16 & 16, 24, 32 & 10, 12, 14 & 6 \\
  521. & rijndael\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 & 6 \\
  522. \hline AES & aesni\_desc & 16 & 16, 24, 32 & 10, 12, 14 & 6 \\
  523. (only on x86 with SSE4.1) &&&&& \\
  524. \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 & 7 \\
  525. \hline DES & des\_desc & 8 & 8 & 16 & 13 \\
  526. \hline 3DES (EDE mode) & des3\_desc & 8 & 16, 24 & 16 & 14 \\
  527. \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 & 15 \\
  528. \hline Noekeon & noekeon\_desc & 16 & 16 & 16 & 16 \\
  529. \hline Skipjack & skipjack\_desc & 8 & 10 & 32 & 17 \\
  530. \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 & 19 \\
  531. \hline Khazad & khazad\_desc & 8 & 16 & 8 & 18 \\
  532. \hline SEED & kseed\_desc & 16 & 16 & 16 & 20 \\
  533. \hline KASUMI & kasumi\_desc & 8 & 16 & 8 & 21 \\
  534. \hline Camellia & camellia\_desc & 16 & 16, 24, 32 & 18, 24 & 23 \\
  535. \hline IDEA & idea\_desc & 8 & 16 & 8 & 24 \\
  536. \hline Serpent & serpent\_desc & 16 & 16, 24, 32 & 32 & 25 \\
  537. \hline TEA & tea\_desc & 8 & 16 & 32 & 26 \\
  538. \hline
  539. \end{tabular}
  540. \end{center}
  541. \end{small}
  542. \caption{Built--In Software Ciphers}
  543. \end{figure}
  544. \subsection{Notes}
  545. \begin{small}
  546. \begin{enumerate}
  547. \item
  548. For AES, (also known as Rijndael) there are multiple descriptors which complicate issues a little. As of FIXME-version-next
  549. the library also integrates hardware-accelerated AES operations (e.g. AES-NI on amd64 with SSE4.1). Therefor the functionality of
  550. the descriptors for the AES algorithm has changed. The rijndael\_desc and rijndael\_enc\_desc descriptors provide the cipher
  551. named \textit{rijndael} which contains the software implementation of the algorithm. The descriptors aes\_desc and aes\_enc\_desc
  552. provide the cipher named \textit{aes} and implement an auto-detection mechanism that chooses between the software-only \textit{rijndael}
  553. and the hardware-accelerated implementation.
  554. Functionally both \textit{rijndael} and \textit{aes} are the same cipher. The
  555. only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with \textit{enc}
  556. in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
  557. and tables. The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
  558. should not be called.
  559. The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
  560. as EAX, PMAC and OMAC or the CTR mode only require the encryption function. So far this \textit{encrypt only} functionality has only
  561. been implemented for Rijndael as it makes the most sense for this cipher.
  562. \item
  563. Note that for \textit{DES} and \textit{3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
  564. fact used for the purposes of encryption. My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
  565. byte string from the real 7/21 byte key.
  566. For \textit{3DES} exists a two-key mode, that can be initialized by calling the setup function with a \textit{keylen} of 16.
  567. This results in the re-usage of key \textit{K1} as key \textit{K3}. This mode has been specified as \textit{Keying Option 2} in FIPS 46-3.
  568. \item
  569. Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time. These options are found in
  570. the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
  571. to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
  572. key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
  573. defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
  574. by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
  575. speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
  576. Twofish round function.
  577. \begin{figure}[hpbt]
  578. \index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
  579. \begin{small}
  580. \begin{center}
  581. \begin{tabular}{|l|l|l|}
  582. \hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
  583. \hline undefined & undefined & Very fast, 4.2KB of ram. \\
  584. \hline undefined & defined & Faster key setup, larger code. \\
  585. \hline defined & undefined & Very slow, 0.2KB of ram. \\
  586. \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
  587. \hline
  588. \end{tabular}
  589. \end{center}
  590. \end{small}
  591. \caption{Twofish Build Options}
  592. \label{fig:twofishopts}
  593. \end{figure}
  594. \item
  595. As of v1.18.0 of the library RC2 got an extended setup function (which didn't fit in the regular API):
  596. \index{rc2\_setup\_ex()}
  597. \begin{verbatim}
  598. int rc2_setup_ex(const unsigned char *key,
  599. int keylen,
  600. int bits,
  601. int num_rounds,
  602. symmetric_key *skey);
  603. \end{verbatim}
  604. This setup function also allows to configure the effective key length in bits of the RC2 cipher as in its original specification.
  605. \end{enumerate}
  606. \end{small}
  607. To work with the cipher\_descriptor array there is a function:
  608. \index{find\_cipher()}
  609. \begin{verbatim}
  610. int find_cipher(char *name)
  611. \end{verbatim}
  612. Which will search for a given name in the array. It returns $-1$ if the cipher is not found, otherwise it returns
  613. the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
  614. \begin{small}
  615. \index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
  616. \begin{verbatim}
  617. #include <tomcrypt.h>
  618. int main(void)
  619. {
  620. unsigned char key[8];
  621. symmetric_key skey;
  622. int err;
  623. /* you must register a cipher before you use it */
  624. if (register_cipher(&blowfish_desc)) == -1) {
  625. printf("Unable to register Blowfish cipher.");
  626. return -1;
  627. }
  628. /* generic call to function (assuming the key
  629. * in key[] was already setup) */
  630. if ((err =
  631. cipher_descriptor[find_cipher("blowfish")].
  632. setup(key, 8, 0, &skey)) != CRYPT_OK) {
  633. printf("Error setting up Blowfish: %s\n", error_to_string(err));
  634. return -1;
  635. }
  636. /* ... use cipher ... */
  637. }
  638. \end{verbatim}
  639. \end{small}
  640. A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function. In order
  641. to use a cipher with the descriptor table you must register it first using:
  642. \index{register\_cipher()}
  643. \begin{verbatim}
  644. int register_cipher(const struct ltc_cipher_descriptor *cipher);
  645. \end{verbatim}
  646. Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
  647. as there is no more room (it can have 32 ciphers at most) it will return {\bf{-1}}. If you try to add the same cipher more
  648. than once it will just return the index of the first copy. To remove a cipher call:
  649. \index{unregister\_cipher()}
  650. \begin{verbatim}
  651. int unregister_cipher(const struct ltc_cipher_descriptor *cipher);
  652. \end{verbatim}
  653. Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
  654. \begin{small}
  655. \begin{verbatim}
  656. #include <tomcrypt.h>
  657. int main(void)
  658. {
  659. int err;
  660. /* register the cipher */
  661. if (register_cipher(&rijndael_desc) == -1) {
  662. printf("Error registering Rijndael\n");
  663. return -1;
  664. }
  665. /* use Rijndael */
  666. /* remove it */
  667. if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
  668. printf("Error removing Rijndael: %s\n", error_to_string(err));
  669. return -1;
  670. }
  671. return 0;
  672. }
  673. \end{verbatim}
  674. \end{small}
  675. This snippet is a small program that registers Rijndael.
  676. \mysection{Symmetric Modes of Operations}
  677. \subsection{Background}
  678. A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
  679. size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
  680. $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initialization vector denoted as $C_{-1}$.
  681. \subsubsection{ECB Mode}
  682. \index{ECB mode}
  683. ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
  684. \begin{equation}
  685. C_i = E_k(P_i)
  686. \end{equation}
  687. This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
  688. than once.
  689. \subsubsection{CBC Mode}
  690. \index{CBC mode}
  691. CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
  692. It is given as:
  693. \begin{equation}
  694. C_i = E_k(P_i \oplus C_{i - 1})
  695. \end{equation}
  696. It is important that the initialization vector be unique and preferably random for each message encrypted under the same key.
  697. \subsubsection{CTR Mode}
  698. \index{CTR mode}
  699. CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initialization vector which is
  700. treated as a large binary counter the CTR mode is given as:
  701. \begin{eqnarray}
  702. C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
  703. C_i = P_i \oplus E_k(C_{-1})
  704. \end{eqnarray}
  705. Where $W$ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initialization vector is random for each message
  706. encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
  707. as the block cipher is under a chosen plaintext attack (provided the initialization vector is unique).
  708. \subsubsection{CFB Mode}
  709. \index{CFB mode}
  710. CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
  711. \begin{eqnarray}
  712. C_i = P_i \oplus C_{-1} \nonumber \\
  713. C_{-1} = E_k(C_i)
  714. \end{eqnarray}
  715. Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
  716. to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
  717. blocks without a delay. When this mode is first setup it will initially encrypt the initialization vector as required.
  718. \subsubsection{OFB Mode}
  719. \index{OFB mode}
  720. OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
  721. \begin{eqnarray}
  722. C_{-1} = E_k(C_{-1}) \nonumber \\
  723. C_i = P_i \oplus C_{-1}
  724. \end{eqnarray}
  725. Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
  726. buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
  727. \subsection{Choice of Mode}
  728. My personal preference is for the CTR mode since it has several key benefits:
  729. \begin{enumerate}
  730. \item No short cycles which is possible in the OFB and CFB modes.
  731. \item Provably as secure as the block cipher being used under a chosen plaintext attack.
  732. \item Technically does not require the decryption routine of the cipher.
  733. \item Allows random access to the plaintext.
  734. \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
  735. \end{enumerate}
  736. The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
  737. accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
  738. block of memory with either of the three modes.
  739. The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
  740. other modes.
  741. \subsection{Ciphertext Stealing}
  742. \index{Ciphertext stealing}
  743. Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
  744. by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
  745. support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.
  746. The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
  747. \subsection{Initialization}
  748. \index{CBC Mode} \index{CTR Mode}
  749. \index{OFB Mode} \index{CFB Mode}
  750. The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
  751. you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
  752. use that mode. They have identical setup routines (except CTR and ECB mode):
  753. \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
  754. \begin{verbatim}
  755. int XXX_start( int cipher,
  756. const unsigned char *IV,
  757. const unsigned char *key,
  758. int keylen,
  759. int num_rounds,
  760. symmetric_XXX *XXX);
  761. int ctr_start( int cipher,
  762. const unsigned char *IV,
  763. const unsigned char *key,
  764. int keylen,
  765. int num_rounds,
  766. int ctr_mode,
  767. symmetric_CTR *ctr);
  768. int ecb_start( int cipher,
  769. const unsigned char *key,
  770. int keylen,
  771. int num_rounds,
  772. symmetric_ECB *ecb);
  773. \end{verbatim}
  774. In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use. The \textit{IV} value is
  775. the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
  776. length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
  777. of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
  778. parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call. The final parameter
  779. is a pointer to the structure you want to hold the information for the mode of operation.
  780. The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.
  781. \subsubsection{CTR Mode}
  782. In the case of CTR mode there is an additional parameter \textit{ctr\_mode} which specifies the mode that the counter is to be used in.
  783. If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
  784. \textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value. As of v1.15 the RFC 3686 style of
  785. increment then encrypt is also supported. By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
  786. the counter before encrypting it for the first time.
  787. As of V1.17, the library supports variable length counters for CTR mode. The (optional) counter length is specified by OR'ing the octet
  788. length of the counter against the \textit{ctr\_mode} parameter. The default, zero, indicates that a full block length counter will be used. This also
  789. ensures backwards compatibility with software that uses older versions of the library.
  790. \begin{small}
  791. \begin{verbatim}
  792. symmetric_CTR ctr;
  793. int err;
  794. unsigned char IV[16], key[16];
  795. /* use a 32-bit little endian counter */
  796. if ((err = ctr_start(find_cipher("aes"),
  797. IV, key, 16, 0,
  798. CTR_COUNTER_LITTLE_ENDIAN | 4,
  799. &ctr)) != CRYPT_OK) {
  800. handle_error(err);
  801. }
  802. \end{verbatim}
  803. \end{small}
  804. Changing the counter size has little (really no) effect on the performance of the CTR chaining mode. It is provided for compatibility
  805. with other software (and hardware) which have smaller fixed sized counters.
  806. \subsection{Encryption and Decryption}
  807. To actually encrypt or decrypt the following routines are provided:
  808. \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
  809. \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
  810. \begin{verbatim}
  811. int XXX_encrypt(const unsigned char *pt,
  812. unsigned char *ct,
  813. unsigned long len,
  814. symmetric_YYY *YYY);
  815. int XXX_decrypt(const unsigned char *ct,
  816. unsigned char *pt,
  817. unsigned long len,
  818. symmetric_YYY *YYY);
  819. \end{verbatim}
  820. Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.
  821. In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
  822. chunk sensitive. That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
  823. and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
  824. five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
  825. In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size. In the CBC case, you must manually pad the end of your message (either with
  826. zeroes or with whatever your protocol requires).
  827. To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
  828. \subsection{IV Manipulation}
  829. To change or read the IV of a previously initialized chaining mode use the following two functions.
  830. \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
  831. \index{ctr\_setiv()} \index{ctr\_getiv()}
  832. \begin{verbatim}
  833. int XXX_getiv(unsigned char *IV,
  834. unsigned long *len,
  835. symmetric_XXX *XXX);
  836. int XXX_setiv(const unsigned char *IV,
  837. unsigned long len,
  838. symmetric_XXX *XXX);
  839. \end{verbatim}
  840. The XXX\_getiv() functions will read the IV out of the chaining mode and store it into \textit{IV} along with the length of the IV
  841. stored in \textit{len}. The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
  842. of the IV passed in must be the size of the ciphers block size.
  843. The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
  844. What the \textit{setiv} function will do depends on the mode being changed. In CBC mode, the new IV replaces the existing IV as if it
  845. were the last ciphertext block. In CFB mode, the IV is encrypted as if it were the prior encrypted pad. In CTR mode, the IV is encrypted without
  846. first incrementing it (regardless of the LTC\_RFC\_3686 flag presence). In F8 mode, the IV is encrypted and becomes the new pad. It does not change
  847. the salted IV, and is only meant to allow seeking within a session. In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
  848. seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
  849. \subsection{Stream Termination}
  850. To terminate an open stream call the done function.
  851. \index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
  852. \begin{verbatim}
  853. int XXX_done(symmetric_XXX *XXX);
  854. \end{verbatim}
  855. This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
  856. \newpage
  857. \subsection{Examples}
  858. \begin{small}
  859. \begin{verbatim}
  860. #include <tomcrypt.h>
  861. int main(void)
  862. {
  863. unsigned char key[16], IV[16], buffer[512];
  864. symmetric_CTR ctr;
  865. int x, err;
  866. /* register twofish first */
  867. if (register_cipher(&twofish_desc) == -1) {
  868. printf("Error registering cipher.\n");
  869. return -1;
  870. }
  871. /* somehow fill out key and IV */
  872. /* start up CTR mode */
  873. if ((err = ctr_start(
  874. find_cipher("twofish"), /* index of desired cipher */
  875. IV, /* the initialization vector */
  876. key, /* the secret key */
  877. 16, /* length of secret key (16 bytes) */
  878. 0, /* 0 == default # of rounds */
  879. CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
  880. &ctr) /* where to store the CTR state */
  881. ) != CRYPT_OK) {
  882. printf("ctr_start error: %s\n", error_to_string(err));
  883. return -1;
  884. }
  885. /* somehow fill buffer than encrypt it */
  886. if ((err = ctr_encrypt( buffer, /* plaintext */
  887. buffer, /* ciphertext */
  888. sizeof(buffer), /* length of plaintext pt */
  889. &ctr) /* CTR state */
  890. ) != CRYPT_OK) {
  891. printf("ctr_encrypt error: %s\n", error_to_string(err));
  892. return -1;
  893. }
  894. /* make use of ciphertext... */
  895. /* now we want to decrypt so let's use ctr_setiv */
  896. if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
  897. 16, /* the IV is 16 bytes long */
  898. &ctr) /* the ctr state we wish to modify */
  899. ) != CRYPT_OK) {
  900. printf("ctr_setiv error: %s\n", error_to_string(err));
  901. return -1;
  902. }
  903. if ((err = ctr_decrypt( buffer, /* ciphertext */
  904. buffer, /* plaintext */
  905. sizeof(buffer), /* length of plaintext */
  906. &ctr) /* CTR state */
  907. ) != CRYPT_OK) {
  908. printf("ctr_decrypt error: %s\n", error_to_string(err));
  909. return -1;
  910. }
  911. /* terminate the stream */
  912. if ((err = ctr_done(&ctr)) != CRYPT_OK) {
  913. printf("ctr_done error: %s\n", error_to_string(err));
  914. return -1;
  915. }
  916. /* clear up and return */
  917. zeromem(key, sizeof(key));
  918. zeromem(&ctr, sizeof(ctr));
  919. return 0;
  920. }
  921. \end{verbatim}
  922. \end{small}
  923. \subsection{LRW Mode}
  924. LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media. It is meant to have efficient seeking and overcome the
  925. security problems of ECB mode while not increasing the storage requirements. It is used much like any other chaining mode except with two key differences.
  926. The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long). The second key
  927. $K_2$ is the \textit{tweak} key and is always 16 octets long. The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.
  928. To initialize LRW mode use:
  929. \index{lrw\_start()}
  930. \begin{verbatim}
  931. int lrw_start( int cipher,
  932. const unsigned char *IV,
  933. const unsigned char *key,
  934. int keylen,
  935. const unsigned char *tweak,
  936. int num_rounds,
  937. symmetric_LRW *lrw);
  938. \end{verbatim}
  939. This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$ \textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$ \textit{tweak}.
  940. While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit{cipher}. The
  941. number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.
  942. To process data use the following functions:
  943. \index{lrw\_encrypt()} \index{lrw\_decrypt()}
  944. \begin{verbatim}
  945. int lrw_encrypt(const unsigned char *pt,
  946. unsigned char *ct,
  947. unsigned long len,
  948. symmetric_LRW *lrw);
  949. int lrw_decrypt(const unsigned char *ct,
  950. unsigned char *pt,
  951. unsigned long len,
  952. symmetric_LRW *lrw);
  953. \end{verbatim}
  954. These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa). The length is specified by \textit{len} in octets but must be a multiple
  955. of 16. The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.
  956. To manipulate the IV use the following functions:
  957. \index{lrw\_getiv()} \index{lrw\_setiv()}
  958. \begin{verbatim}
  959. int lrw_getiv(unsigned char *IV,
  960. unsigned long *len,
  961. symmetric_LRW *lrw);
  962. int lrw_setiv(const unsigned char *IV,
  963. unsigned long len,
  964. symmetric_LRW *lrw);
  965. \end{verbatim}
  966. These will get or set the 16--octet IV. Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation. It requires
  967. updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
  968. To terminate the LRW state use the following:
  969. \index{lrw\_done()}
  970. \begin{verbatim}
  971. int lrw_done(symmetric_LRW *lrw);
  972. \end{verbatim}
  973. \subsection{XTS Mode}
  974. As of v1.17, LibTomCrypt supports XTS mode with code donated by Elliptic Semiconductor Inc.\footnote{www.ellipticsemi.com}.
  975. XTS is a chaining mode for 128--bit block ciphers, recommended by IEEE (P1619)
  976. for disk encryption. It is meant to be an encryption mode with random access to the message data without compromising privacy. It requires two private keys (of equal
  977. length) to perform the encryption process. Each encryption invocation includes a sector number or unique identifier specified as a 128--bit string.
  978. To initialize XTS mode use the following function call:
  979. \index{xts\_start()}
  980. \begin{verbatim}
  981. int xts_start( int cipher,
  982. const unsigned char *key1,
  983. const unsigned char *key2,
  984. unsigned long keylen,
  985. int num_rounds,
  986. symmetric_xts *xts)
  987. \end{verbatim}
  988. This will start the XTS mode with the two keys pointed to by \textit{key1} and \textit{key2} of length \textit{keylen} octets each.
  989. To encrypt or decrypt a sector use the following calls:
  990. \index{xts\_encrypt()} \index{xts\_decrypt()}
  991. \begin{verbatim}
  992. int xts_encrypt(
  993. const unsigned char *pt, unsigned long ptlen,
  994. unsigned char *ct,
  995. const unsigned char *tweak,
  996. symmetric_xts *xts);
  997. int xts_decrypt(
  998. const unsigned char *ct, unsigned long ptlen,
  999. unsigned char *pt,
  1000. const unsigned char *tweak,
  1001. symmetric_xts *xts);
  1002. \end{verbatim}
  1003. The first will encrypt the plaintext pointed to by \textit{pt} of length \textit{ptlen} octets, and store the ciphertext in the array pointed to by
  1004. \textit{ct}. It uses the 128--bit tweak pointed to by \textit{tweak} to encrypt the block. The decrypt function performs the opposite operation. Both
  1005. functions support ciphertext stealing (blocks that are not multiples of 16 bytes).
  1006. The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.
  1007. To terminate the XTS state call the following function:
  1008. \index{xts\_done()}
  1009. \begin{verbatim}
  1010. void xts_done(symmetric_xts *xts);
  1011. \end{verbatim}
  1012. \subsection{F8 Mode}
  1013. \index{F8 Mode}
  1014. The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers. It behaves much like CTR mode in that it XORs a keystream
  1015. against the plaintext to encrypt. F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}. We
  1016. initialize F8 mode with the following function call:
  1017. \index{f8\_start()}
  1018. \begin{verbatim}
  1019. int f8_start( int cipher,
  1020. const unsigned char *IV,
  1021. const unsigned char *key,
  1022. int keylen,
  1023. const unsigned char *salt_key,
  1024. int skeylen,
  1025. int num_rounds,
  1026. symmetric_F8 *f8);
  1027. \end{verbatim}
  1028. This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter. It uses the \textit{salt\_key} as IV encryption key
  1029. (\textit{m} in the RFC 3711). The salt\_key can be shorter than the secret key but it should not be longer.
  1030. To encrypt or decrypt data we use the following two functions:
  1031. \index{f8\_encrypt()} \index{f8\_decrypt()}
  1032. \begin{verbatim}
  1033. int f8_encrypt(const unsigned char *pt,
  1034. unsigned char *ct,
  1035. unsigned long len,
  1036. symmetric_F8 *f8);
  1037. int f8_decrypt(const unsigned char *ct,
  1038. unsigned char *pt,
  1039. unsigned long len,
  1040. symmetric_F8 *f8);
  1041. \end{verbatim}
  1042. These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified. The length is specified in bytes and does not have to be a multiple
  1043. of the ciphers block size.
  1044. To change or retrieve the current counter IV value use the following functions:
  1045. \index{f8\_getiv()} \index{f8\_setiv()}
  1046. \begin{verbatim}
  1047. int f8_getiv(unsigned char *IV,
  1048. unsigned long *len,
  1049. symmetric_F8 *f8);
  1050. int f8_setiv(const unsigned char *IV,
  1051. unsigned long len,
  1052. symmetric_F8 *f8);
  1053. \end{verbatim}
  1054. These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start(). The purpose of these two functions is to be
  1055. able to seek within a current session only. If you want to change the session IV you will have to call f8\_done() and then start a new state with
  1056. f8\_start().
  1057. To terminate an F8 state call the following function:
  1058. \index{f8\_done()}
  1059. \begin{verbatim}
  1060. int f8_done(symmetric_F8 *f8);
  1061. \end{verbatim}
  1062. \chapter{Stream Ciphers}
  1063. Stream ciphers are symmetric key ciphers which operate on a stream of bytes (in theory on a stream of bits
  1064. however LibTomCrypt's implementation works with bytes).
  1065. The API for all stream ciphers operates in mode: \textit{setup} -- \textit{crypt} -- \textit{crypt} -- ... -- \textit{done}.
  1066. Please note that both encryption and decryption are implemented via \textit{crypt}.
  1067. Another useful feature of the stream ciphers API is generation of a random stream of bytes which works like:
  1068. \textit{setup} -- \textit{keystream} -- \textit{keystream} -- ... -- \textit{done}. The random stream generation is
  1069. implemented like encryption of a stream of \textit{0x00} bytes.
  1070. Note: You shouldn't use the keystream interface as a PRNG, as it doesn't allow to re-seed the internal state.
  1071. \mysection{ChaCha}
  1072. \textit{ChaCha} is currently the most modern stream cipher included in LibTomCrypt, so use this one unless you
  1073. have a reason for using some of the older algorithms.
  1074. For more information about ChaCha see \url{https://en.wikipedia.org/wiki/ChaCha_(cipher)}.
  1075. Supported key size: 16 or 32 bytes (128 or 256 bits).
  1076. You can initialize ChaCha with 96bit \textit{nonce} + 32bit \textit{counter}:
  1077. \begin{verbatim}
  1078. chacha_state st;
  1079. err = chacha_setup(&st, key, key_len, rounds);
  1080. err = chacha_ivctr32(&st, nonce, 12, initial_32bit_ctr);
  1081. \end{verbatim}
  1082. Or with 64bit \textit{nonce} + 64bit \textit{counter}:
  1083. \begin{verbatim}
  1084. chacha_state st;
  1085. err = chacha_setup(&st, key, key_len, rounds);
  1086. err = chacha_ivctr64(&st, nonce, 8, initial_64bit_ctr);
  1087. \end{verbatim}
  1088. The \textit{chacha\_setup} takes the number of rounds as a parameter -- choose 20 if you are not sure.
  1089. As always never ever use the same key + nonce pair more than once.
  1090. For the actual encryption or decryption you have to call:
  1091. \begin{verbatim}
  1092. err = chacha_crypt(&st, in_buffer, in_len, out_buffer);
  1093. \end{verbatim}
  1094. If you just want a random stream of bytes initialize the cipher with a truly random \textit{key} (32 bytes),
  1095. a truly random \textit{nonce} (8 bytes) and zero initial counter. After that you can get a stream of pseudo--random
  1096. bytes via:
  1097. \begin{verbatim}
  1098. err = chacha_keystream(&st, out_buffer, out_len);
  1099. \end{verbatim}
  1100. At the end you have to terminate the state:
  1101. \begin{verbatim}
  1102. err = chacha_done(&st);
  1103. \end{verbatim}
  1104. To encrypt plaintext (or decrypt ciphertext) using ChaCha for data already in
  1105. memory with a single function call, the following function may be used.
  1106. \begin{verbatim}
  1107. err = chacha_memory(key, keylen, iv, ivlen, datain, datalen, rounds, dataout);
  1108. \end{verbatim}
  1109. \mysection{Salsa20 and XSalsa20}
  1110. \textit{Salsa20} was Daniel Bernstein's submission to the EU eSTREAM
  1111. competition where a reduced-round version, \textit{Salsa20/12}, was named
  1112. one of the winners. A third version, \textit{Salsa20/8}, was also evaluated.
  1113. \vspace{1mm}
  1114. While 20 rounds is the conservative default number of rounds, eSTREAM deemed
  1115. 12 rounds to be a decent balance between strength and better performance.
  1116. The 8-round version, while still secure as of this writing, is faster but
  1117. does not enjoy the same margin of safety. Regardless of the number of rounds,
  1118. \textit{Salsa20} accepts either a 128- or a 256-bit key, a 64-bit IV, and a
  1119. 64-bit counter.
  1120. \vspace{1mm}
  1121. \textit{XSalsa20} is yet another variant of \textit{Salsa20} designed to accept
  1122. only a 256-bit key and a longer 192-bit nonce, initialization being the only
  1123. difference between \textit{XSalsa20} and \textit{Salsa20}. Even the
  1124. \textit{salsa20\_state} is the same. Thereafter, salsa20\_crypt(),
  1125. salsa20\_keystream(), and salsa20\_done() are used unaltered.
  1126. salsa20\_ivctr64() is NOT used with xsalsa20\_setup().
  1127. \vspace{1mm}
  1128. To initialize \textit{Salsa20} for 8, 12, or 20 rounds with a 128- or a
  1129. 256-bit key (16 or 32 bytes), a 64-bit IV (8 bytes), and counter (typically
  1130. zero), use:
  1131. \begin{verbatim}
  1132. salsa20_state st;
  1133. ulong64 counter = 0;
  1134. err = salsa20_setup(&st, key, key_len, rounds);
  1135. err = salsa20_ivctr64(&st, nonce, 8, counter);
  1136. \end{verbatim}
  1137. To initialize \textit{XSalsa20} for the recommended 20 rounds with a 256-bit
  1138. key (32 bytes) and a 192-bit nonce (24 bytes), use:
  1139. \begin{verbatim}
  1140. salsa20_state st;
  1141. err = xsalsa20_setup(&st, key, key_len, nonce, nonce_len, rounds);
  1142. \end{verbatim}
  1143. Both \textit{Salsa20} and \textit{XSalsa20} use the following functions. To
  1144. encrypt or decrypt call:
  1145. \begin{verbatim}
  1146. err = salsa20_crypt(&st, in_buffer, in_len, out_buffer);
  1147. \end{verbatim}
  1148. For a random keystream initialize the cipher with a truly random \textit{key}
  1149. and random \textit{nonce} after which you can get a stream of
  1150. pseudo--random bytes via:
  1151. \begin{verbatim}
  1152. err = salsa20_keystream(&st, out_buffer, out_len);
  1153. \end{verbatim}
  1154. Finally, when finished you should wipe the state.
  1155. \begin{verbatim}
  1156. err = salsa20_done(&st);
  1157. \end{verbatim}
  1158. To encrypt plaintext (or decrypt ciphertext) using Salsa20 for data already in
  1159. memory with a single function call, the following function may be used.
  1160. \begin{verbatim}
  1161. err = salsa20_memory(key, keylen, iv, ivlen, datain, datalen, rounds, dataout);
  1162. \end{verbatim}
  1163. To encrypt plaintext (or decrypt ciphertext) using XSalsa20 for data already in
  1164. memory with a single function call, the following function may be used.
  1165. \begin{verbatim}
  1166. err = xsalsa20_memory(key, keylen, nonce, nonce_len, datain, datalen, rounds, dataout);
  1167. \end{verbatim}
  1168. For both \textit{Salsa20} and \textit{XSalsa20} rounds must be an even number
  1169. and if set to 0 the default number of rounds, 20, will be used.
  1170. \vspace{1mm}
  1171. If you define \textit{LTC\_XSALSA20} to include \textit{XSalsa20} in a minimal
  1172. \textit{libtomcrypt} library build, you must also define \textit{LTC\_SALSA20}.
  1173. \vspace{1mm}
  1174. As always, never ever use the same key + nonce/IV pair more than once.
  1175. \vspace{1mm}
  1176. For more information about Salsa20 see
  1177. \url{https://en.wikipedia.org/wiki/Salsa20}.
  1178. \vspace{1mm}
  1179. For more information about XSalsa20 see
  1180. \url{https://cr.yp.to/snuffle/xsalsa-20081128.pdf}.
  1181. \vspace{1mm}
  1182. \mysection{Sosemanuk}
  1183. \textit{Sosemanuk}, along with Salsa20, HC-128, and Rabbit, was named one of the winners in
  1184. the EU eSTREAM competition. Sosemanuk is a stream cipher that borrows heavily from SNOW,
  1185. another stream cipher, and the block cipher Serpent. (Sosemanuk means "snow snake" in the
  1186. Cree Indian language.)
  1187. Sosemanuk will accept a key between 1 and 256 bits, but Sosemanuk's security level of 128
  1188. bits is achieved only if the key is between 128 and 256 bits. Keys longer than 128 bits
  1189. are not guaranteed to provided higher security. The initialization vector is 128 bits.
  1190. (All length arguments are expressed in bytes.)
  1191. See \url{http://www.ecrypt.eu.org/stream/p3ciphers/sosemanuk/sosemanuk_p3.pdf} for more
  1192. information.
  1193. Initialize by creating a Sosemanuk state and provide a 128- to 256-bit key to \textit{sosemanuk\_setup()}.
  1194. \begin{verbatim}
  1195. sosemanuk_state st;
  1196. err = sosemanuk_setup(&st, key, keylen);
  1197. \end{verbatim}
  1198. Finish initializing with an iv of up to 128 bits.
  1199. \begin{verbatim}
  1200. err = sosemanuk_setiv(&st, iv, ivlen);
  1201. \end{verbatim}
  1202. For the actual encryption or decryption, call:
  1203. \begin{verbatim}
  1204. err = sosemanuk_crypt(&st, in, inlen, out);
  1205. \end{verbatim}
  1206. If you just want a random stream of bytes initialize the cipher with a truly random
  1207. \textit{key} (256 bits) and a truly random \textit{iv} (128 bits). After that you can
  1208. get a stream of pseudo--random bytes via:
  1209. \begin{verbatim}
  1210. err = sosemanuk_keystream(&st, out, outlen);
  1211. \end{verbatim}
  1212. When finished you should wipe the key by running \textit{sosemanuk\_done()}.
  1213. \begin{verbatim}
  1214. err = sosemanuk_done(&st);
  1215. \end{verbatim}
  1216. To do multiple encryptions and decryptions with the same key, you will want to set the iv but
  1217. you do not need to re-run \textit{sosemanuk\_setup()} again, unless of course, you called
  1218. \textit{sosemanuk\_done()}.
  1219. To encrypt plaintext (or decrypt ciphertext) using Sosemanuk for data already in
  1220. memory with a single function call, the following function may be used.
  1221. \begin{verbatim}
  1222. err = sosemanuk_memory(key, keylen, iv, ivlen, datain, datalen, dataout);
  1223. \end{verbatim}
  1224. \mysection{Rabbit}
  1225. \textit{Rabbit}, along with Salsa20, Sosemanuk, and HC-128, was named one of the winners
  1226. in the EU eSTREAM competition. Rabbit is a simple and fast cipher suitable for resource
  1227. constrained platforms.
  1228. This implementation of Rabbit will accept a key of up to 16 bytes (128 bits), and an
  1229. initialization vector of up to 8 bytes (64 bits). If the provided key or IV is shorter,
  1230. they will be null padded to that length. There is no rounds option.
  1231. The calls to \textit{rabbit\_crypt()} or \textit{rabbit\_keystream()} may be for any
  1232. number bytes although their generation will be more efficient if the requests are for
  1233. multiples of 16 bytes.
  1234. You begin initializing Rabbit by creating a state and calling \textit{rabbit\_setup()}
  1235. with a 128-bit key.
  1236. \begin{verbatim}
  1237. rabbit_state st;
  1238. err = rabbit_setup(&st, key, keylen);
  1239. \end{verbatim}
  1240. Set the IV using \textit{rabbit\_setiv()} with a 64-bit IV.
  1241. \begin{verbatim}
  1242. err = rabbit_setiv(&st, iv, iv_len);
  1243. \end{verbatim}
  1244. For the actual encryption or decryption, call:
  1245. \begin{verbatim}
  1246. err = rabbit_crypt(&st, in_buffer, inlen, out_buffer);
  1247. \end{verbatim}
  1248. If you just want a random stream of bytes initialize the cipher with a truly random \textit{key}
  1249. (16 bytes), a truly random \textit{iv} (8 bytes). After that you can
  1250. get a stream of pseudo--random bytes via:
  1251. \begin{verbatim}
  1252. err = rabbit_keystream(&st, out_buffer, length);
  1253. \end{verbatim}
  1254. When finished you should wipe the key and the state:
  1255. \begin{verbatim}
  1256. err = rabbit_done(&st);
  1257. \end{verbatim}
  1258. Technically, it is possible to initialize Rabbit with only a call to \textit{rabbit\_setup()},
  1259. skipping the call to \textit{rabbit\_setiv()}. This is not recommended for interoperability reasons,
  1260. but there may be special cases like closed systems or custom protocols where doing so might be
  1261. appropriate. Please note that skipping \textit{rabbit\_setiv()} will give results different than
  1262. calling \textit{rabbit\_setiv()} passing a zero-valued IV. You should call \textit{rabbit\_setiv()} unless
  1263. you have a special reason for not doing so.
  1264. To do multiple encryptions and decryptions with the same key, you can reset the algorithm
  1265. using \textit{rabbit\_setiv()} if you saved the state and did not wipe it with \textit{rabbit\_done()}.
  1266. You will want to use a different IV but you do not need to call \textit{rabbit\_setup()} a 2nd time,
  1267. unless of course, you skipped calling \textit{rabbit\_setiv()}.
  1268. To encrypt plaintext (or decrypt ciphertext) using Rabbit for data already in
  1269. memory with a single function call, the following function may be used.
  1270. \begin{verbatim}
  1271. err = rabbit_memory(key, keylen, iv, ivlen, datain, datalen, dataout);
  1272. \end{verbatim}
  1273. For more information, see: \newline
  1274. \hspace{4em}- \url{http://www.ecrypt.eu.org/stream/p3ciphers/rabbit/rabbit_p3.pdf} \newline
  1275. \hspace{4em}- \url{https://tools.ietf.org/html/rfc4503}
  1276. \mysection{RC4}
  1277. For more information about RC4 see \url{https://en.wikipedia.org/wiki/RC4}.
  1278. Supported key size: 5--256 bytes
  1279. You need to initialize RC4 only with a \textit{key}.
  1280. \begin{verbatim}
  1281. rc4_state st;
  1282. err = rc4_stream_setup(&st, key, key_len);
  1283. \end{verbatim}
  1284. For the actual encryption or decryption you have to call:
  1285. \begin{verbatim}
  1286. err = rc4_stream_crypt(&st, in_buffer, in_len, out_buffer);
  1287. \end{verbatim}
  1288. If you just want a random stream of bytes initialize the cipher with truly random \textit{key}.
  1289. After that you can get a stream of pseudo--random bytes via:
  1290. \begin{verbatim}
  1291. err = rc4_stream_keystream(&st, out_buffer, out_len);
  1292. \end{verbatim}
  1293. At the end you have to terminate the state:
  1294. \begin{verbatim}
  1295. err = rc4_stream_done(&st);
  1296. \end{verbatim}
  1297. To encrypt plaintext (or decrypt ciphertext) using RC4 for data already in
  1298. memory with a single function call, the following function may be used.
  1299. \begin{verbatim}
  1300. err = rc4_stream_memory(key, keylen, datain, datalen, dataout);
  1301. \end{verbatim}
  1302. \mysection{Sober128}
  1303. Supported key size: must be multiple of 4 bytes
  1304. You need to initialize Sober128 with a \textit{key} and a \textit{nonce} (must be multiple of 4 bytes).
  1305. \begin{verbatim}
  1306. sober128_state st;
  1307. err = sober128_stream_setup(&st, key, 16);
  1308. err = sober128_stream_setiv(&st, nonce, 12);
  1309. \end{verbatim}
  1310. For the actual encryption or decryption you to call:
  1311. \begin{verbatim}
  1312. err = sober128_stream_crypt(&st, in_buffer, in_len, out_buffer);
  1313. \end{verbatim}
  1314. If you just want a random stream of bytes initialize the cipher with a truly random \textit{key}
  1315. and a truly random \textit{nonce}. After that you can get a stream of pseudo--random bytes via:
  1316. \begin{verbatim}
  1317. err = sober128_stream_keystream(&st, out_buffer, out_len);
  1318. \end{verbatim}
  1319. At the end you have to terminate the state:
  1320. \begin{verbatim}
  1321. err = sober128_stream_done(&st);
  1322. \end{verbatim}
  1323. To encrypt plaintext (or decrypt ciphertext) using Sober128 for data already in
  1324. memory with a single function call, the following function may be used.
  1325. \begin{verbatim}
  1326. err = sober128_stream_memory(key, keylen, iv, ivlen, datain, datalen, dataout);
  1327. \end{verbatim}
  1328. \chapter{Authenticated Encryption}
  1329. Authenticated Encryption - sometimes also called Authenticated Encryption with Associated Data (AEAD) - is a variant of encryption
  1330. that provides not only confidentiality (as other symmetric or stream ciphers) but also integrity.
  1331. The inputs of Authenticated Encryption are: \textit{key}, \textit{nonce} (sometimes called initialization vector), \textit{plaintext},
  1332. optional \textit{header} (sometimes called additional authenticated data - AAD). The outputs are: \textit{ciphertext} and \textit{tag}.
  1333. \mysection{EAX Mode}
  1334. LibTomCrypt provides support for a mode called EAX\footnote{See
  1335. M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
  1336. by the designers. First, a short description of what EAX mode is before we explain how to use it. EAX is a mode that requires a cipher,
  1337. CTR and OMAC support and provides encryption and
  1338. authentication\footnote{Note that since EAX only requires OMAC and CTR you may use \textit{encrypt only} cipher descriptors with this mode.}.
  1339. It is initialized with a random \textit{nonce} that can be shared publicly, a \textit{header} which can be fixed and public, and a random secret symmetric key.
  1340. The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages). It can
  1341. be added at anytime during an EAX stream, and is part of the authentication tag. That is, changes in the meta-data can be detected by changes in the output tag.
  1342. The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
  1343. called a \textit{tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
  1344. sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
  1345. of operation.
  1346. The mode is initialized with the following function.
  1347. \index{eax\_init()}
  1348. \begin{verbatim}
  1349. int eax_init( eax_state *eax,
  1350. int cipher,
  1351. const unsigned char *key,
  1352. unsigned long keylen,
  1353. const unsigned char *nonce,
  1354. unsigned long noncelen,
  1355. const unsigned char *header,
  1356. unsigned long headerlen);
  1357. \end{verbatim}
  1358. Where \textit{eax} is the EAX state. The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.
  1359. The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets. The \textit{nonce} parameter is the
  1360. random public string of length \textit{noncelen} octets. The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the
  1361. message of length \textit{headerlen} octets.
  1362. When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or
  1363. encrypted in EAX mode. Note: if \textit{headerlen} is zero you may pass \textit{header} as \textbf{NULL} to indicate there is no initial header data.
  1364. To encrypt or decrypt data in a streaming mode use the following.
  1365. \index{eax\_encrypt()} \index{eax\_decrypt()}
  1366. \begin{verbatim}
  1367. int eax_encrypt( eax_state *eax,
  1368. const unsigned char *pt,
  1369. unsigned char *ct,
  1370. unsigned long length);
  1371. int eax_decrypt( eax_state *eax,
  1372. const unsigned char *ct,
  1373. unsigned char *pt,
  1374. unsigned long length);
  1375. \end{verbatim}
  1376. The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
  1377. \textit{ct}. Note: \textit{ct} and \textit{pt} may be the same region in memory. This function will also send the ciphertext
  1378. through the OMAC function. The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}. This also allows
  1379. \textit{pt} and \textit{ct} to be the same region in memory.
  1380. You cannot both encrypt or decrypt with the same \textit{eax} context. For bi--directional communication you will need to initialize
  1381. two EAX contexts (preferably with different headers and nonces).
  1382. Note: both of these functions allow you to send the data in any granularity but the order is important. While
  1383. the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
  1384. EAX stream with the following.
  1385. \index{eax\_addheader()}
  1386. \begin{verbatim}
  1387. int eax_addheader( eax_state *eax,
  1388. const unsigned char *header,
  1389. unsigned long length);
  1390. \end{verbatim}
  1391. This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header. Once the message is finished, the
  1392. \textit{tag} (checksum) may be computed with the following function:
  1393. \index{eax\_done()}
  1394. \begin{verbatim}
  1395. int eax_done( eax_state *eax,
  1396. unsigned char *tag,
  1397. unsigned long *taglen);
  1398. \end{verbatim}
  1399. This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}. The function
  1400. then stores how many bytes of the tag were written out back in to \textit{taglen}.
  1401. The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
  1402. \index{eax\_test()}
  1403. \begin{verbatim}
  1404. int eax_test(void);
  1405. \end{verbatim}
  1406. This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
  1407. \begin{verbatim}
  1408. #include <tomcrypt.h>
  1409. int main(void)
  1410. {
  1411. int err;
  1412. eax_state eax;
  1413. unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
  1414. unsigned long taglen;
  1415. if (register_cipher(&rijndael_desc) == -1) {
  1416. printf("Error registering Rijndael");
  1417. return EXIT_FAILURE;
  1418. }
  1419. /* ... make up random nonce and key ... */
  1420. /* initialize context */
  1421. if ((err = eax_init( &eax, /* context */
  1422. find_cipher("rijndael"), /* cipher id */
  1423. nonce, /* the nonce */
  1424. 16, /* nonce is 16 bytes */
  1425. "TestApp", /* example header */
  1426. 7) /* header length */
  1427. ) != CRYPT_OK) {
  1428. printf("Error eax_init: %s", error_to_string(err));
  1429. return EXIT_FAILURE;
  1430. }
  1431. /* now encrypt data, say in a loop or whatever */
  1432. if ((err = eax_encrypt( &eax, /* eax context */
  1433. pt, /* plaintext (source) */
  1434. ct, /* ciphertext (destination) */
  1435. sizeof(pt) /* size of plaintext */
  1436. ) != CRYPT_OK) {
  1437. printf("Error eax_encrypt: %s", error_to_string(err));
  1438. return EXIT_FAILURE;
  1439. }
  1440. /* finish message and get authentication tag */
  1441. taglen = sizeof(tag);
  1442. if ((err = eax_done( &eax, /* eax context */
  1443. tag, /* where to put tag */
  1444. &taglen /* length of tag space */
  1445. ) != CRYPT_OK) {
  1446. printf("Error eax_done: %s", error_to_string(err));
  1447. return EXIT_FAILURE;
  1448. }
  1449. /* now we have the authentication tag in "tag" and
  1450. * it's taglen bytes long */
  1451. }
  1452. \end{verbatim}
  1453. You can also perform an entire EAX state on a block of memory in a single function call with the
  1454. following functions.
  1455. \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
  1456. \begin{verbatim}
  1457. int eax_encrypt_authenticate_memory(
  1458. int cipher,
  1459. const unsigned char *key, unsigned long keylen,
  1460. const unsigned char *nonce, unsigned long noncelen,
  1461. const unsigned char *header, unsigned long headerlen,
  1462. const unsigned char *pt, unsigned long ptlen,
  1463. unsigned char *ct,
  1464. unsigned char *tag, unsigned long *taglen);
  1465. int eax_decrypt_verify_memory(
  1466. int cipher,
  1467. const unsigned char *key, unsigned long keylen,
  1468. const unsigned char *nonce, unsigned long noncelen,
  1469. const unsigned char *header, unsigned long headerlen,
  1470. const unsigned char *ct, unsigned long ctlen,
  1471. unsigned char *pt,
  1472. unsigned char *tag, unsigned long taglen,
  1473. int *res);
  1474. \end{verbatim}
  1475. Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
  1476. have the same meaning as with those respective functions.
  1477. The only difference is eax\_decrypt\_verify\_memory() does not emit a tag. Instead you pass it a tag as input and it compares it against
  1478. the tag it computed while decrypting the message. If the tags match then it stores a $1$ in \textit{res}, otherwise it stores a $0$.
  1479. \mysection{OCB Modes}
  1480. \subsection{Preface}
  1481. LibTomCrypt provides support for a mode called OCB in version 1 ''OCB''\footnote{See
  1482. P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit{OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption}.}
  1483. and version 3 ''OCB3''\footnote{See RFC7253, T. Krovetz, P. Rogaway, \textit{The OCB Authenticated-Encryption Algorithm}.}.
  1484. OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
  1485. but is less flexible.
  1486. Please be aware that all versions of OCB are patented and there are several licensing models provided by P. Rogaway, the patent holder
  1487. -- see \url{http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm}.
  1488. \subsection{OCB}
  1489. \subsubsection{Initialization and processing}
  1490. Let's review how to initialize an OCB context.
  1491. \index{ocb\_init()}
  1492. \begin{verbatim}
  1493. int ocb_init( ocb_state *ocb,
  1494. int cipher,
  1495. const unsigned char *key,
  1496. unsigned long keylen,
  1497. const unsigned char *nonce);
  1498. \end{verbatim}
  1499. This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
  1500. and the random \textit{nonce}. Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
  1501. block size (e.g. 16 bytes for AES).
  1502. This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
  1503. To encrypt or decrypt data use the following.
  1504. \index{ocb\_encrypt()} \index{ocb\_decrypt()}
  1505. \begin{verbatim}
  1506. int ocb_encrypt( ocb_state *ocb,
  1507. const unsigned char *pt,
  1508. unsigned char *ct);
  1509. int ocb_decrypt( ocb_state *ocb,
  1510. const unsigned char *ct,
  1511. unsigned char *pt);
  1512. \end{verbatim}
  1513. This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
  1514. They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
  1515. both functions given a single \textit{ocb} state. For bi-directional communication you will have to initialize two \textit{ocb}
  1516. states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
  1517. \subsubsection{State Termination}
  1518. When you are finished encrypting the message you call the following function to compute the tag.
  1519. \index{ocb\_done\_encrypt()}
  1520. \begin{verbatim}
  1521. int ocb_done_encrypt( ocb_state *ocb,
  1522. const unsigned char *pt,
  1523. unsigned long ptlen,
  1524. unsigned char *ct,
  1525. unsigned char *tag,
  1526. unsigned long *taglen);
  1527. \end{verbatim}
  1528. This will terminate an encrypt stream \textit{ocb}. If you have trailing bytes of plaintext that will not complete a block
  1529. you can pass them here. This will also encrypt the \textit{ptlen} bytes in \textit{pt} and store them in \textit{ct}. It will also
  1530. store up to \textit{taglen} bytes of the tag into \textit{tag}.
  1531. Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen. Also note that if you have
  1532. an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
  1533. To terminate a decrypt stream and compared the tag you call the following.
  1534. \index{ocb\_done\_decrypt()}
  1535. \begin{verbatim}
  1536. int ocb_done_decrypt( ocb_state *ocb,
  1537. const unsigned char *ct,
  1538. unsigned long ctlen,
  1539. unsigned char *pt,
  1540. const unsigned char *tag,
  1541. unsigned long taglen,
  1542. int *res);
  1543. \end{verbatim}
  1544. Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
  1545. tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided. By default
  1546. \textit{res} is set to zero. If all \textit{taglen} bytes of \textit{tag} can be verified then \textit{res} is set to one (authenticated
  1547. message).
  1548. \subsubsection{Packet Functions}
  1549. To make life simpler the following two functions are provided for memory bound OCB.
  1550. %\index{ocb\_encrypt\_authenticate\_memory()}
  1551. \begin{verbatim}
  1552. int ocb_encrypt_authenticate_memory(
  1553. int cipher,
  1554. const unsigned char *key, unsigned long keylen,
  1555. const unsigned char *nonce,
  1556. const unsigned char *pt, unsigned long ptlen,
  1557. unsigned char *ct,
  1558. unsigned char *tag, unsigned long *taglen);
  1559. \end{verbatim}
  1560. This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
  1561. can be any arbitrary length.
  1562. \index{ocb\_decrypt\_verify\_memory()}
  1563. \begin{verbatim}
  1564. int ocb_decrypt_verify_memory(
  1565. int cipher,
  1566. const unsigned char *key, unsigned long keylen,
  1567. const unsigned char *nonce,
  1568. const unsigned char *ct, unsigned long ctlen,
  1569. unsigned char *pt,
  1570. const unsigned char *tag, unsigned long taglen,
  1571. int *res);
  1572. \end{verbatim}
  1573. Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
  1574. appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.
  1575. \subsection{OCB3}
  1576. \subsubsection{Initialization and processing}
  1577. \index{ocb3\_init()}
  1578. \begin{verbatim}
  1579. int ocb3_init(ocb3_state *ocb, int cipher,
  1580. const unsigned char *key, unsigned long keylen,
  1581. const unsigned char *nonce, unsigned long noncelen,
  1582. unsigned long taglen);
  1583. \end{verbatim}
  1584. This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
  1585. and the random \textit{nonce} of length \textit{noncelen}. The \textit{nonce} must be a random (public) string of an arbitrary length
  1586. between 1 and 15 octets. The desired length of the TAG that should be created when terminating the state has to be passed in \textit{taglen}
  1587. and has to be between 0 and 16 octets.
  1588. Note that you can only use ciphers with a block length of 16.
  1589. \subsubsection{Additional Authenticated Data}
  1590. OCB3 has, in contrary to OCB, the possibility to add "Additional Authenticated Data" (AAD) when performing cryptographic operations.
  1591. \index{ocb3\_add\_aad()}
  1592. \begin{verbatim}
  1593. int ocb3_add_aad(ocb3_state *ocb, const unsigned char *aad, unsigned long aadlen);
  1594. \end{verbatim}
  1595. This will add the AAD at \textit{aad} of the arbitrary length \textit{aadlen} to be authenticated within the context \textit{ocb}.
  1596. \index{ocb3\_encrypt()} \index{ocb3\_decrypt()}
  1597. \begin{verbatim}
  1598. int ocb3_encrypt( ocb3_state *ocb,
  1599. const unsigned char *pt,
  1600. unsigned long ptlen,
  1601. unsigned char *ct);
  1602. int ocb3_decrypt( ocb3_state *ocb,
  1603. const unsigned char *ct,
  1604. unsigned long ctlen,
  1605. unsigned char *pt);
  1606. \end{verbatim}
  1607. This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
  1608. They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
  1609. both functions given a single \textit{ocb} state. For bi-directional communication you will have to initialize two \textit{ocb}
  1610. states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
  1611. \subsubsection{State Termination}
  1612. \index{ocb3\_encrypt\_last()} \index{ocb3\_decrypt\_last()}
  1613. \begin{verbatim}
  1614. int ocb3_encrypt_last( ocb3_state *ocb,
  1615. const unsigned char *pt,
  1616. unsigned long ptlen,
  1617. unsigned char *ct);
  1618. int ocb3_decrypt_last( ocb3_state *ocb,
  1619. const unsigned char *ct,
  1620. unsigned long ctlen,
  1621. unsigned char *pt);
  1622. \end{verbatim}
  1623. This has to be called for the last encrypt (or decrypt) operation. Note that if you have to invoke only a single operation you can
  1624. directly use these functions instead of \textit{ocb3\_encrypt()} or \textit{ocb3\_decrypt()}.
  1625. When you are finished encrypting the message you call the following function to compute the tag.
  1626. \index{ocb3\_done()}
  1627. \begin{verbatim}
  1628. int ocb3_done(ocb3_state *ocb, unsigned char *tag, unsigned long *taglen);
  1629. \end{verbatim}
  1630. This stores the tag of the \textit{ocb} state in \textit{tag}.
  1631. The \textit{taglen} parameter defines on input the length of the tag to output and will be set to the actual length written, which
  1632. is at most 16 octets.
  1633. \subsubsection{Packet Functions}
  1634. To make life simpler the following two functions are provided for memory bound OCB3.
  1635. \index{ocb3\_encrypt\_authenticate\_memory()}
  1636. \begin{verbatim}
  1637. int ocb3_encrypt_authenticate_memory(int cipher,
  1638. const unsigned char *key, unsigned long keylen,
  1639. const unsigned char *nonce, unsigned long noncelen,
  1640. const unsigned char *adata, unsigned long adatalen,
  1641. const unsigned char *pt, unsigned long ptlen,
  1642. unsigned char *ct,
  1643. unsigned char *tag, unsigned long *taglen);
  1644. \end{verbatim}
  1645. This will OCB3 encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
  1646. can be any arbitrary length. The additional authenticated data \textit{adata} of length \textit{adatalen} is optional and can be left out
  1647. by passing \textit{NULL} as \textit{adata}. The length of the authentication TAG will be stored in \textit{tag}, which is also optional.
  1648. The length of the TAG passed in \textit{taglen} has to be between 0 and 16.
  1649. \index{ocb3\_decrypt\_verify\_memory()}
  1650. \begin{verbatim}
  1651. int ocb3_decrypt_verify_memory(int cipher,
  1652. const unsigned char *key, unsigned long keylen,
  1653. const unsigned char *nonce, unsigned long noncelen,
  1654. const unsigned char *adata, unsigned long adatalen,
  1655. const unsigned char *ct, unsigned long ctlen,
  1656. unsigned char *pt,
  1657. const unsigned char *tag, unsigned long taglen,
  1658. int *stat);
  1659. \end{verbatim}
  1660. Similarly, this will OCB3 decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
  1661. appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.
  1662. \mysection{CCM Mode}
  1663. CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.
  1664. \subsection{Initialization}
  1665. To initialize the CCM context with a secret key call the following function.
  1666. \index{ccm\_init()}
  1667. \begin{verbatim}
  1668. int ccm_init( ccm_state *ccm,
  1669. int cipher,
  1670. const unsigned char *key,
  1671. int keylen,
  1672. int ptlen,
  1673. int taglen,
  1674. int aadlen);
  1675. \end{verbatim}
  1676. This initializes the CCM state \textit{ccm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
  1677. chosen must have a 16--byte block size (e.g., AES).
  1678. Unlike EAX and OCB mode, CCM is only meant for \textit{packet} mode where the length of the input is known in advance. This is why the length of the stream
  1679. to authenticate is given as \textit{ptlen}.
  1680. With CCM, a header is meta--data you want to send with the message but not have encrypted. The header len is given in the init
  1681. as \textit{aadlen}.
  1682. \subsection{Nonce Vector}
  1683. After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector. It should be unique per packet encrypted.
  1684. \index{ccm\_add\_nonce()}
  1685. \begin{verbatim}
  1686. int ccm_add_nonce( ccm_state *ccm,
  1687. const unsigned char *nonce,
  1688. unsigned long noncelen);
  1689. \end{verbatim}
  1690. This adds the nonce (a.k.a. salt) \textit{nonce} of length \textit{noncelen} octets to the CCM state \textit{ccm}. Note that this function must be called
  1691. once and only once.
  1692. \subsection{Additional Authentication Data}
  1693. The header is meta--data you want to send with the message but not have encrypted, it must be stored in \textit{adata} of length \textit{adatalen} octets.
  1694. \index{ccm\_add\_aad()}
  1695. \begin{verbatim}
  1696. int ccm_add_aad( ccm_state *ccm,
  1697. const unsigned char *adata,
  1698. unsigned long adatalen);
  1699. \end{verbatim}
  1700. This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the CCM state \textit{ccm}.
  1701. \subsection{Plaintext Processing}
  1702. After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
  1703. \index{ccm\_process()}
  1704. \begin{verbatim}
  1705. int ccm_process(ccm_state *ccm,
  1706. unsigned char *pt,
  1707. unsigned long ptlen,
  1708. unsigned char *ct,
  1709. int direction);
  1710. \end{verbatim}
  1711. This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
  1712. the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{CCM\_ENCRYPT} the plaintext is read,
  1713. encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{CCM\_DECRYPT} the opposite occurs.
  1714. \subsection{State Termination}
  1715. To terminate a CCM state and retrieve the message authentication tag call the following function.
  1716. \index{ccm\_done()}
  1717. \begin{verbatim}
  1718. int ccm_done( ccm_state *ccm,
  1719. unsigned char *tag,
  1720. unsigned long *taglen);
  1721. \end{verbatim}
  1722. This terminates the CCM state \textit{ccm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
  1723. \subsection{State Reset}
  1724. The call to ccm\_init() will perform considerable pre--computation and if you're going to be dealing with a lot of packets
  1725. it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function is provided.
  1726. \index{ccm\_reset()}
  1727. \begin{verbatim}
  1728. int ccm_reset(ccm_state *ccm);
  1729. \end{verbatim}
  1730. This will reset the CCM state \textit{ccm} to the state that ccm\_init() left it. The user would then call ccm\_add\_nonce(), ccm\_add\_aad(), etc.
  1731. \subsection{One--Shot Packet}
  1732. To process a single packet under any given key the following helper function can be used.
  1733. \index{ccm\_memory()}
  1734. \begin{verbatim}
  1735. int ccm_memory(
  1736. int cipher,
  1737. const unsigned char *key, unsigned long keylen,
  1738. symmetric_key *uskey,
  1739. const unsigned char *nonce, unsigned long noncelen,
  1740. const unsigned char *header, unsigned long headerlen,
  1741. unsigned char *pt, unsigned long ptlen,
  1742. unsigned char *ct,
  1743. unsigned char *tag, unsigned long *taglen,
  1744. int direction);
  1745. \end{verbatim}
  1746. This will initialize the CCM state with the given key, nonce and AAD value then proceed to encrypt or decrypt the message text and store the final
  1747. message tag. The definition of the variables is the same as it is for all the manual functions.
  1748. If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
  1749. \subsection{Example Usage}
  1750. The following is an example usage of how to use CCM over multiple packets with a shared secret key.
  1751. \begin{small}
  1752. \begin{verbatim}
  1753. #include <tomcrypt.h>
  1754. int send_packet(const unsigned char *pt, unsigned long ptlen,
  1755. const unsigned char *nonce, unsigned long noncelen,
  1756. const unsigned char *aad, unsigned long aadlen,
  1757. ccm_state *ccm)
  1758. {
  1759. int err;
  1760. unsigned long taglen;
  1761. unsigned char tag[16];
  1762. /* reset the state */
  1763. if ((err = ccm_reset(ccm)) != CRYPT_OK) {
  1764. return err;
  1765. }
  1766. /* Add the nonce */
  1767. if ((err = ccm_add_nonce(ccm, nonce, noncelen)) != CRYPT_OK) {
  1768. return err;
  1769. }
  1770. /* Add the AAD (note: aad can be NULL if aadlen == 0) */
  1771. if ((err = ccm_add_aad(ccm, aad, aadlen)) != CRYPT_OK) {
  1772. return err;
  1773. }
  1774. /* process the plaintext */
  1775. if ((err =
  1776. ccm_process(ccm, pt, ptlen, pt, CCM_ENCRYPT)) != CRYPT_OK) {
  1777. return err;
  1778. }
  1779. /* Finish up and get the MAC tag */
  1780. taglen = sizeof(tag);
  1781. if ((err = ccm_done(ccm, tag, &taglen)) != CRYPT_OK) {
  1782. return err;
  1783. }
  1784. /* ... send a header describing the lengths ... */
  1785. /* depending on the protocol and how nonce is
  1786. * generated you may have to send it too... */
  1787. send(socket, nonce, noncelen, 0);
  1788. /* send the aad */
  1789. send(socket, aad, aadlen, 0);
  1790. /* send the ciphertext */
  1791. send(socket, pt, ptlen, 0);
  1792. /* send the tag */
  1793. send(socket, tag, taglen, 0);
  1794. return CRYPT_OK;
  1795. }
  1796. int main(void)
  1797. {
  1798. ccm_state ccm;
  1799. unsigned char key[16], NONCE[12], pt[PACKET_SIZE];
  1800. int err, x;
  1801. unsigned long ptlen;
  1802. /* somehow fill key/NONCE with random values */
  1803. /* register AES */
  1804. register_cipher(&aes_desc);
  1805. /* init the CCM state */
  1806. if ((err =
  1807. ccm_init(&ccm, find_cipher("aes"), key, 16, PACKET_SIZE, 16, size(NONCE))) != CRYPT_OK) {
  1808. whine_and_pout(err);
  1809. }
  1810. /* handle us some packets */
  1811. for (;;) {
  1812. ptlen = make_packet_we_want_to_send(pt);
  1813. /* use NONCE as counter (12 byte counter) */
  1814. for (x = 11; x >= 0; x--) {
  1815. if (++NONCE[x]) {
  1816. break;
  1817. }
  1818. }
  1819. if ((err = send_packet(pt, ptlen, NONCE, 12, NULL, 0, &ccm))
  1820. != CRYPT_OK) {
  1821. whine_and_pout(err);
  1822. }
  1823. }
  1824. return EXIT_SUCCESS;
  1825. }
  1826. \end{verbatim}
  1827. \end{small}
  1828. \mysection{GCM Mode}
  1829. Galois counter mode is an IEEE proposal for authenticated encryption (also it is a planned NIST standard). Like EAX and OCB mode, it can be used in a streaming capacity
  1830. however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed. This mode also only works with
  1831. block ciphers with a 16--byte block.
  1832. A GCM stream is meant to be processed in three modes, one after another. First, the initialization vector (per session) data is processed. This should be
  1833. unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
  1834. \subsection{Initialization}
  1835. To initialize the GCM context with a secret key call the following function.
  1836. \index{gcm\_init()}
  1837. \begin{verbatim}
  1838. int gcm_init( gcm_state *gcm,
  1839. int cipher,
  1840. const unsigned char *key,
  1841. int keylen);
  1842. \end{verbatim}
  1843. This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
  1844. chosen must have a 16--byte block size (e.g., AES).
  1845. \subsection{Initialization Vector}
  1846. After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector. It should be unique per packet encrypted.
  1847. \index{gcm\_add\_iv()}
  1848. \begin{verbatim}
  1849. int gcm_add_iv( gcm_state *gcm,
  1850. const unsigned char *IV,
  1851. unsigned long IVlen);
  1852. \end{verbatim}
  1853. This adds the initialization vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}. You can call this function as many times as required
  1854. to process the entire IV.
  1855. Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done. If you want to minimize per packet latency it is ideal
  1856. to only use 12--byte IVs. You can just increment it like a counter for each packet.
  1857. \subsection{Additional Authentication Data}
  1858. After the entire IV has been processed, the additional authentication data can be processed. Unlike the IV, a packet/session does not require additional
  1859. authentication data (AAD) for security. The AAD is meant to be used as side--channel data you want to be authenticated with the packet. Note: once
  1860. you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
  1861. \index{gcm\_add\_aad()}
  1862. \begin{verbatim}
  1863. int gcm_add_aad( gcm_state *gcm,
  1864. const unsigned char *adata,
  1865. unsigned long adatalen);
  1866. \end{verbatim}
  1867. This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
  1868. \subsection{Plaintext Processing}
  1869. After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
  1870. \index{gcm\_process()}
  1871. \begin{verbatim}
  1872. int gcm_process( gcm_state *gcm,
  1873. unsigned char *pt,
  1874. unsigned long ptlen,
  1875. unsigned char *ct,
  1876. int direction);
  1877. \end{verbatim}
  1878. This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
  1879. the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read,
  1880. encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
  1881. \subsection{State Termination}
  1882. To terminate a GCM state and retrieve the message authentication tag call the following function.
  1883. \index{gcm\_done()}
  1884. \begin{verbatim}
  1885. int gcm_done( gcm_state *gcm,
  1886. unsigned char *tag,
  1887. unsigned long *taglen);
  1888. \end{verbatim}
  1889. This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
  1890. \subsection{State Reset}
  1891. The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
  1892. it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
  1893. \index{gcm\_reset()}
  1894. \begin{verbatim}
  1895. int gcm_reset(gcm_state *gcm);
  1896. \end{verbatim}
  1897. This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it. The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
  1898. \subsection{One--Shot Packet}
  1899. To process a single packet under any given key the following helper function can be used.
  1900. \index{gcm\_memory()}
  1901. \begin{verbatim}
  1902. int gcm_memory(
  1903. int cipher,
  1904. const unsigned char *key,
  1905. unsigned long keylen,
  1906. const unsigned char *IV, unsigned long IVlen,
  1907. const unsigned char *adata, unsigned long adatalen,
  1908. unsigned char *pt, unsigned long ptlen,
  1909. unsigned char *ct,
  1910. unsigned char *tag, unsigned long *taglen,
  1911. int direction);
  1912. \end{verbatim}
  1913. This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
  1914. message tag. The definition of the variables is the same as it is for all the manual functions.
  1915. IMPORTANT NOTICE: for \textit{direction == GCM\_DECRYPT} the caller has to fill \textit{tag} and \textit{taglen} with expected
  1916. tag value. The \textit{gcm\_memory} in decrypt mode validates the \textit{tag} value and returns \textit{CRYPT\_ERROR} on mismatch.
  1917. If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
  1918. \subsection{Example Usage}
  1919. The following is an example usage of how to use GCM over multiple packets with a shared secret key.
  1920. \begin{small}
  1921. \begin{verbatim}
  1922. #include <tomcrypt.h>
  1923. int send_packet(const unsigned char *pt, unsigned long ptlen,
  1924. const unsigned char *iv, unsigned long ivlen,
  1925. const unsigned char *aad, unsigned long aadlen,
  1926. gcm_state *gcm)
  1927. {
  1928. int err;
  1929. unsigned long taglen;
  1930. unsigned char tag[16];
  1931. /* reset the state */
  1932. if ((err = gcm_reset(gcm)) != CRYPT_OK) {
  1933. return err;
  1934. }
  1935. /* Add the IV */
  1936. if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
  1937. return err;
  1938. }
  1939. /* Add the AAD (note: aad can be NULL if aadlen == 0) */
  1940. if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
  1941. return err;
  1942. }
  1943. /* process the plaintext */
  1944. if ((err =
  1945. gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
  1946. return err;
  1947. }
  1948. /* Finish up and get the MAC tag */
  1949. taglen = sizeof(tag);
  1950. if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
  1951. return err;
  1952. }
  1953. /* ... send a header describing the lengths ... */
  1954. /* depending on the protocol and how IV is
  1955. * generated you may have to send it too... */
  1956. send(socket, iv, ivlen, 0);
  1957. /* send the aad */
  1958. send(socket, aad, aadlen, 0);
  1959. /* send the ciphertext */
  1960. send(socket, pt, ptlen, 0);
  1961. /* send the tag */
  1962. send(socket, tag, taglen, 0);
  1963. return CRYPT_OK;
  1964. }
  1965. int main(void)
  1966. {
  1967. gcm_state gcm;
  1968. unsigned char key[16], IV[12], pt[PACKET_SIZE];
  1969. int err, x;
  1970. unsigned long ptlen;
  1971. /* somehow fill key/IV with random values */
  1972. /* register AES */
  1973. register_cipher(&aes_desc);
  1974. /* init the GCM state */
  1975. if ((err =
  1976. gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
  1977. whine_and_pout(err);
  1978. }
  1979. /* handle us some packets */
  1980. for (;;) {
  1981. ptlen = make_packet_we_want_to_send(pt);
  1982. /* use IV as counter (12 byte counter) */
  1983. for (x = 11; x >= 0; x--) {
  1984. if (++IV[x]) {
  1985. break;
  1986. }
  1987. }
  1988. if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm))
  1989. != CRYPT_OK) {
  1990. whine_and_pout(err);
  1991. }
  1992. }
  1993. return EXIT_SUCCESS;
  1994. }
  1995. \end{verbatim}
  1996. \end{small}
  1997. \mysection{ChaCha20--Poly1305}
  1998. This authenticated encryption is based on ChaCha20 stream cipher and Poly1305 authenticator.
  1999. It is defined by \url{https://tools.ietf.org/html/rfc7539}.
  2000. \subsection{Initialization}
  2001. To initialize the ChaCha20--Poly1305 context with a secret key call the following function.
  2002. \index{chacha20poly1305\_init()}
  2003. \begin{verbatim}
  2004. int chacha20poly1305_init(chacha20poly1305_state *st,
  2005. const unsigned char *key,
  2006. unsigned long keylen);
  2007. \end{verbatim}
  2008. This initializes the ChaCha20--Poly1305 state \textit{st} with a secret key \textit{key} of length \textit{keylen}
  2009. octets (valid lengths: 32 or 16).
  2010. \subsection{Initialization Vector}
  2011. After the state has been initialized the next step is to add the initialization vector.
  2012. \index{chacha20poly1305\_setiv()}
  2013. \begin{verbatim}
  2014. int chacha20poly1305_setiv(chacha20poly1305_state *st,
  2015. const unsigned char *iv,
  2016. unsigned long ivlen);
  2017. \end{verbatim}
  2018. This adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
  2019. the ChaCha20--Poly1305 state \textit{st}.
  2020. \index{chacha20poly1305\_setiv\_rfc7905()}
  2021. \begin{verbatim}
  2022. int chacha20poly1305_setiv_rfc7905(chacha20poly1305_state *st,
  2023. const unsigned char *iv,
  2024. unsigned long ivlen,
  2025. ulong64 sequence_number);
  2026. \end{verbatim}
  2027. This also adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
  2028. the state \textit{st} but it also incorporates 64bit \textit{sequence\_number} into IV as described in RFC7905.
  2029. You can call only one of \textit{chacha20poly1305\_setiv} or \textit{chacha20poly1305\_setiv\_rfc7905}.
  2030. \subsection{Additional Authentication Data}
  2031. After the IV has been set, the additional authentication data can be processed.
  2032. \index{chacha20poly1305\_add\_aad()}
  2033. \begin{verbatim}
  2034. int chacha20poly1305_add_aad(chacha20poly1305_state *st,
  2035. const unsigned char *adata,
  2036. unsigned long adatalen);
  2037. \end{verbatim}
  2038. This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the ChaCha20--Poly1305 state \textit{st}.
  2039. \subsection{Encryption / Decryption}
  2040. After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
  2041. \index{chacha20poly1305\_encrypt()}
  2042. \begin{verbatim}
  2043. int chacha20poly1305_encrypt(chacha20poly1305_state *st,
  2044. const unsigned char *in,
  2045. unsigned long inlen,
  2046. unsigned char *out);
  2047. \end{verbatim}
  2048. This encrypts the data where \textit{in} is the plaintext and \textit{out} is the ciphertext. The length of both are equal and stored in \textit{inlen}.
  2049. \index{chacha20poly1305\_decrypt()}
  2050. \begin{verbatim}
  2051. int chacha20poly1305_decrypt(chacha20poly1305_state *st,
  2052. const unsigned char *in,
  2053. unsigned long inlen,
  2054. unsigned char *out);
  2055. \end{verbatim}
  2056. This decrypts the data where \textit{in} is the ciphertext and \textit{out} is the plaintext. The length of both are equal and stored in \textit{inlen}.
  2057. \subsection{State Termination}
  2058. To terminate a ChaCha20--Poly1305 state and retrieve the message authentication tag call the following function.
  2059. \index{chacha20poly1305\_done()}
  2060. \begin{verbatim}
  2061. int chacha20poly1305_done(chacha20poly1305_state *st,
  2062. unsigned char *tag,
  2063. unsigned long *taglen);
  2064. \end{verbatim}
  2065. This terminates the ChaCha20--Poly1305 state \textit{st} and stores the tag in \textit{tag} of length \textit{taglen} octets (always 16).
  2066. \subsection{One--Shot Packet}
  2067. To process a single packet under any given key the following helper function can be used.
  2068. \index{chacha20poly1305\_memory()}
  2069. \begin{verbatim}
  2070. int chacha20poly1305_memory(const unsigned char *key,
  2071. unsigned long keylen,
  2072. const unsigned char *iv,
  2073. unsigned long ivlen,
  2074. const unsigned char *aad,
  2075. unsigned long aadlen,
  2076. const unsigned char *in,
  2077. unsigned long inlen,
  2078. unsigned char *out,
  2079. unsigned char *tag,
  2080. unsigned long *taglen,
  2081. int direction);
  2082. \end{verbatim}
  2083. This will initialize the ChaCha20--Poly1305 state with the given key, IV and AAD value then proceed to
  2084. encrypt (\textit{direction} equals \textbf{CHACHA20POLY1305\_ENCRYPT}) or decrypt (\textit{direction} equals
  2085. \textbf{CHACHA20POLY1305\_DECRYPT}) the message text and store the final message tag. The definition of the
  2086. variables is the same as it is for all the manual functions.
  2087. IMPORTANT NOTICE: for \textit{direction == CHACHA20POLY1305\_DECRYPT} the caller has to fill \textit{tag} and \textit{taglen} with expected
  2088. tag value. The \textit{chacha20poly1305\_memory} in decrypt mode validates the \textit{tag} value and returns \textit{CRYPT\_ERROR} on mismatch.
  2089. \chapter{One-Way Cryptographic Hash Functions}
  2090. \mysection{Core Functions}
  2091. Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}. To initialize hash
  2092. XXX (where XXX is the name) call:
  2093. \index{Hash Functions}
  2094. \begin{verbatim}
  2095. void XXX_init(hash_state *md);
  2096. \end{verbatim}
  2097. This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the message being hashed call:
  2098. \begin{verbatim}
  2099. int XXX_process( hash_state *md,
  2100. const unsigned char *in,
  2101. unsigned long inlen);
  2102. \end{verbatim}
  2103. Essentially all hash messages are virtually infinitely\footnote{Most hashes are limited to $2^{64}$ bits or 2,305,843,009,213,693,952 bytes.} long message which
  2104. are buffered. In the case where this limit is reached the \textit{XXX\_process()} function returns \textit{CRYPT\_HASH\_OVERFLOW}.
  2105. \index{CRYPT\_HASH\_OVERFLOW}
  2106. The data can be passed in any sized chunks as long as the order of the bytes are the same, the message digest (hash output) will be the same. For example, this means that:
  2107. \begin{verbatim}
  2108. md5_process(&md, "hello ", 6);
  2109. md5_process(&md, "world", 5);
  2110. \end{verbatim}
  2111. Will produce the same message digest as the single call:
  2112. \index{Message Digest}
  2113. \begin{verbatim}
  2114. md5_process(&md, "hello world", 11);
  2115. \end{verbatim}
  2116. To finally get the message digest (the hash) call:
  2117. \begin{verbatim}
  2118. int XXX_done( hash_state *md,
  2119. unsigned char *out);
  2120. \end{verbatim}
  2121. This function will finish up the hash and store the result in the \textit{out} array. You must ensure that \textit{out} is long
  2122. enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
  2123. will wipe the \textit{md} variable before returning automatically.
  2124. To test a hash function call:
  2125. \begin{verbatim}
  2126. int XXX_test(void);
  2127. \end{verbatim}
  2128. This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
  2129. example snippet that hashes a message with md5 is given below.
  2130. \begin{small}
  2131. \begin{verbatim}
  2132. #include <tomcrypt.h>
  2133. int main(void)
  2134. {
  2135. hash_state md;
  2136. unsigned char *in = "hello world", out[16];
  2137. /* setup the hash */
  2138. md5_init(&md);
  2139. /* add the message */
  2140. md5_process(&md, in, strlen(in));
  2141. /* get the hash in out[0..15] */
  2142. md5_done(&md, out);
  2143. return 0;
  2144. }
  2145. \end{verbatim}
  2146. \end{small}
  2147. \mysection{Hash Descriptors}
  2148. Like the set of ciphers, the set of hashes have descriptors as well. They are stored in an array called \textit{hash\_descriptor} and
  2149. are defined by:
  2150. \begin{verbatim}
  2151. struct ltc_hash_descriptor {
  2152. char *name;
  2153. unsigned long hashsize; /* digest output size in bytes */
  2154. unsigned long blocksize; /* the block size the hash uses */
  2155. void (*init) (hash_state *hash);
  2156. int (*process)( hash_state *hash,
  2157. const unsigned char *in,
  2158. unsigned long inlen);
  2159. int (*done) (hash_state *hash, unsigned char *out);
  2160. int (*test) (void);
  2161. };
  2162. \end{verbatim}
  2163. \index{find\_hash()}
  2164. The \textit{name} member is the name of the hash function (all lowercase). The \textit{hashsize} member is the size of the digest output
  2165. in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function. Technically, this detail is not important
  2166. for high level developers but is useful to know for performance reasons.
  2167. The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the
  2168. digest. The \textit{test} member tests the hash against the specified test vectors.
  2169. There is a function to search the array as well called \textit{int find\_hash(char *name)}. It returns -1 if the hash is not found, otherwise, the
  2170. position in the descriptor table of the hash.
  2171. In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
  2172. \index{find\_hash\_oid()}
  2173. \begin{verbatim}
  2174. int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
  2175. \end{verbatim}
  2176. You can use the table to indirectly call a hash function that is chosen at run-time. For example:
  2177. \begin{small}
  2178. \begin{verbatim}
  2179. #include <tomcrypt.h>
  2180. int main(void)
  2181. {
  2182. unsigned char buffer[100], hash[MAXBLOCKSIZE];
  2183. int idx, x;
  2184. hash_state md;
  2185. /* register hashes .... */
  2186. if (register_hash(&md5_desc) == -1) {
  2187. printf("Error registering MD5.\n");
  2188. return -1;
  2189. }
  2190. /* register other hashes ... */
  2191. /* prompt for name and strip newline */
  2192. printf("Enter hash name: \n");
  2193. fgets(buffer, sizeof(buffer), stdin);
  2194. buffer[strlen(buffer) - 1] = 0;
  2195. /* get hash index */
  2196. idx = find_hash(buffer);
  2197. if (idx == -1) {
  2198. printf("Invalid hash name!\n");
  2199. return -1;
  2200. }
  2201. /* hash input until blank line */
  2202. hash_descriptor[idx].init(&md);
  2203. while (fgets(buffer, sizeof(buffer), stdin) != NULL)
  2204. hash_descriptor[idx].process(&md, buffer, strlen(buffer));
  2205. hash_descriptor[idx].done(&md, hash);
  2206. /* dump to screen */
  2207. for (x = 0; x < hash_descriptor[idx].hashsize; x++)
  2208. printf("%02x ", hash[x]);
  2209. printf("\n");
  2210. return 0;
  2211. }
  2212. \end{verbatim}
  2213. \end{small}
  2214. Note the usage of \textbf{MAXBLOCKSIZE}. In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
  2215. length. This provides a simple size you can set your automatic arrays to that will not get overrun.
  2216. There are three helper functions to make working with hashes easier. The first is a function to hash a buffer, and produce the digest in a single
  2217. function call.
  2218. \index{hash\_memory()}
  2219. \begin{verbatim}
  2220. int hash_memory( int hash,
  2221. const unsigned char *in,
  2222. unsigned long inlen,
  2223. unsigned char *out,
  2224. unsigned long *outlen);
  2225. \end{verbatim}
  2226. This will hash the data pointed to by \textit{in} of length \textit{inlen}. The hash used is indexed by the \textit{hash} parameter. The message
  2227. digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  2228. The next helper function allows for the hashing of a file based on a file name.
  2229. \index{hash\_file()}
  2230. \begin{verbatim}
  2231. int hash_file( int hash,
  2232. const char *fname,
  2233. unsigned char *out,
  2234. unsigned long *outlen);
  2235. \end{verbatim}
  2236. This will hash the file named by \textit{fname} using the hash indexed by \textit{hash}. The file named in this function call must be readable by the
  2237. user owning the process performing the request. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
  2238. when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  2239. \index{hash\_filehandle()}
  2240. \begin{verbatim}
  2241. int hash_filehandle( int hash,
  2242. FILE *in,
  2243. unsigned char *out,
  2244. unsigned long *outlen);
  2245. \end{verbatim}
  2246. This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}. This will begin hashing from the current file pointer position, and
  2247. will not rewind the file pointer when finished. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
  2248. when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  2249. To perform the above hash with md5 the following code could be used:
  2250. \begin{small}
  2251. \begin{verbatim}
  2252. #include <tomcrypt.h>
  2253. int main(void)
  2254. {
  2255. int idx, err;
  2256. unsigned long len;
  2257. unsigned char out[MAXBLOCKSIZE];
  2258. /* register the hash */
  2259. if (register_hash(&md5_desc) == -1) {
  2260. printf("Error registering MD5.\n");
  2261. return -1;
  2262. }
  2263. /* get the index of the hash */
  2264. idx = find_hash("md5");
  2265. /* call the hash */
  2266. len = sizeof(out);
  2267. if ((err =
  2268. hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
  2269. printf("Error hashing data: %s\n", error_to_string(err));
  2270. return -1;
  2271. }
  2272. return 0;
  2273. }
  2274. \end{verbatim}
  2275. \end{small}
  2276. \subsection{Hash Registration}
  2277. Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
  2278. work exactly like those of the cipher registration code. The functions are:
  2279. \index{register\_hash()} \index{unregister\_hash()}
  2280. \begin{verbatim}
  2281. int register_hash(const struct ltc_hash_descriptor *hash);
  2282. int unregister_hash(const struct ltc_hash_descriptor *hash);
  2283. \end{verbatim}
  2284. The following hashes are provided as of this release within the LibTomCrypt library:
  2285. \index{Hash descriptor table}
  2286. \begin{figure}[H]
  2287. \begin{center}
  2288. \begin{tabular}{|c|c|c|c|}
  2289. \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Size of Message Digest (bytes)} & \textbf{Id} \\
  2290. \hline WHIRLPOOL & whirlpool\_desc & 64 & 11 \\
  2291. \hline Keccak512 & keccak\_512\_desc & 64 & 32 \\
  2292. \hline SHA3-512 & sha3\_512\_desc & 64 & 20 \\
  2293. \hline SHA-512 & sha512\_desc & 64 & 5 \\
  2294. \hline BLAKE2B-512 & blake2b\_512\_desc & 64 & 28 \\
  2295. \hline Keccak384 & keccak\_384\_desc & 48 & 31 \\
  2296. \hline SHA3-384 & sha3\_384\_desc & 48 & 19 \\
  2297. \hline SHA-384 & sha384\_desc & 48 & 4 \\
  2298. \hline BLAKE2B-384 & blake2b\_384\_desc & 48 & 27 \\
  2299. \hline RIPEMD-320 & rmd160\_desc & 40 & 14 \\
  2300. \hline SHA-512/256 & sha512\_256\_desc & 32 & 16 \\
  2301. \hline Keccak256 & keccak\_256\_desc & 32 & 30 \\
  2302. \hline SHA3-256 & sha3\_256\_desc & 32 & 18 \\
  2303. \hline SHA-256 & sha256\_desc & 32 & 0 \\
  2304. \hline RIPEMD-256 & rmd160\_desc & 32 & 13 \\
  2305. \hline BLAKE2S-256 & blake2s\_256\_desc & 32 & 24 \\
  2306. \hline BLAKE2B-256 & blake2b\_256\_desc & 32 & 26 \\
  2307. \hline SHA-512/224 & sha512\_224\_desc & 28 & 15 \\
  2308. \hline Keccak224 & keccak\_224\_desc & 28 & 29 \\
  2309. \hline SHA3-224 & sha3\_224\_desc & 28 & 17 \\
  2310. \hline SHA-224 & sha224\_desc & 28 & 10 \\
  2311. \hline BLAKE2S-224 & blake2s\_224\_desc & 28 & 23 \\
  2312. \hline TIGER-192 & tiger\_desc & 24 & 1 \\
  2313. \hline TIGER2-192 & tiger2\_desc & 24 & 33 \\
  2314. \hline SHA-1 & sha1\_desc & 20 & 2 \\
  2315. \hline RIPEMD-160 & rmd160\_desc & 20 & 9 \\
  2316. \hline BLAKE2S-160 & blake2s\_160\_desc & 20 & 22 \\
  2317. \hline BLAKE2B-160 & blake2b\_160\_desc & 20 & 25 \\
  2318. \hline RIPEMD-128 & rmd128\_desc & 16 & 8 \\
  2319. \hline MD5 & md5\_desc & 16 & 3 \\
  2320. \hline MD4 & md4\_desc & 16 & 6 \\
  2321. \hline MD2 & md2\_desc & 16 & 7 \\
  2322. \hline BLAKE2S-128 & blake2s\_128\_desc & 16 & 21 \\
  2323. \hline
  2324. \end{tabular}
  2325. \end{center}
  2326. \caption{Built--In Software Hashes}
  2327. \end{figure}
  2328. \vfil
  2329. \mysection{Cipher Hash Construction}
  2330. \index{Cipher Hash Construction}
  2331. An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode. In this mode
  2332. applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
  2333. particular this allows a cryptosystem to be designed using very few moving parts.
  2334. In order to use the CHC system the developer will have to take a few extra steps. First the \textit{chc\_desc} hash
  2335. descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
  2336. data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
  2337. via the chc\_register() function.
  2338. \index{chc\_register()}
  2339. \begin{verbatim}
  2340. int chc_register(int cipher);
  2341. \end{verbatim}
  2342. A cipher has to be registered with CHC (and also in the cipher descriptor tables with
  2343. register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
  2344. be bound to the CHC hash at a time. There are additional requirements for the system to work.
  2345. \begin{enumerate}
  2346. \item The cipher must have a block size greater than 64--bits.
  2347. \item The cipher must allow an input key the size of the block size.
  2348. \end{enumerate}
  2349. Example of using CHC with the AES block cipher.
  2350. \begin{verbatim}
  2351. #include <tomcrypt.h>
  2352. int main(void)
  2353. {
  2354. int err;
  2355. /* register cipher and hash */
  2356. if (register_cipher(&aes_enc_desc) == -1) {
  2357. printf("Could not register cipher\n");
  2358. return EXIT_FAILURE;
  2359. }
  2360. if (register_hash(&chc_desc) == -1) {
  2361. printf("Could not register hash\n");
  2362. return EXIT_FAILURE;
  2363. }
  2364. /* start chc with AES */
  2365. if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
  2366. printf("Error binding AES to CHC: %s\n",
  2367. error_to_string(err));
  2368. }
  2369. /* now you can use chc_hash in any LTC function
  2370. * [aside from pkcs...] */
  2371. }
  2372. \end{verbatim}
  2373. \mysection{SHA3 SHAKE}
  2374. The SHA3 class of algorithms provides a special XOF (Extendable Output Functions) mode, called SHAKE.
  2375. SHAKE operates in 2 security configurations, 128bit or 256bit, and allows to generate message digests of an arbitrary length.
  2376. For further information see \url{https://en.wikipedia.org/wiki/SHA-3}
  2377. Example of using SHAKE256 with an arbitrary length output.
  2378. \begin{small}
  2379. \begin{verbatim}
  2380. #include <tomcrypt.h>
  2381. int main(void)
  2382. {
  2383. int err;
  2384. hash_state state;
  2385. const void* msg = "The quick brown fox jumps over the lazy dog";
  2386. unsigned char output[345];
  2387. if ((err = sha3_shake_init(&state, 256)) != CRYPT_OK) {
  2388. printf("Could not init SHAKE256 (%s)\n", error_to_string(err));
  2389. return EXIT_FAILURE;
  2390. }
  2391. if ((err = sha3_shake_process(&state, msg, strlen(msg))) != CRYPT_OK) {
  2392. printf("Could not process SHAKE256 (%s)\n", error_to_string(err));
  2393. return EXIT_FAILURE;
  2394. }
  2395. if ((err = sha3_shake_done(&state, output, sizeof(output))) != CRYPT_OK) {
  2396. printf("Could not finish SHAKE256 (%s)\n", error_to_string(err));
  2397. return EXIT_FAILURE;
  2398. }
  2399. return EXIT_SUCCESS;
  2400. }
  2401. \end{verbatim}
  2402. \end{small}
  2403. \mysection{Extended Tiger API}
  2404. The Tiger and Tiger2 hash algorithms \url{http://www.cs.technion.ac.il/~biham/Reports/Tiger/} specify the possibility to run the algorithm with
  2405. a configurable number of passes. The default and minimum is 3 passes, there is a second more or less widely used version with 4 passes,
  2406. which has been introduced by PHP. Its utilization is mostly limited to PHP, so we don't provide descriptors by default.
  2407. An example of how to use the 4-pass version of Tiger in a libtomcrypt-style way is shown below.
  2408. \index{tiger\_init\_ex()}
  2409. \begin{small}
  2410. \begin{verbatim}
  2411. #include <tomcrypt.h>
  2412. static const char *tiger_4passes_name = "tiger-4passes";
  2413. static int tiger_4passes_init(hash_state *md)
  2414. {
  2415. return tiger_init_ex(md, 4);
  2416. }
  2417. static struct ltc_hash_descriptor tiger_4passes_desc;
  2418. int main(void)
  2419. {
  2420. int err = 0;
  2421. unsigned char hash[MAXBLOCKSIZE], *p;
  2422. unsigned long hashlen = sizeof(hash);
  2423. memcpy(&tiger_4passes_desc, &tiger_desc, sizeof(tiger_4passes_desc));
  2424. tiger_4passes_desc.init = tiger_4passes_init;
  2425. /* Make sure to have a different name, ID and OID than standard Tiger */
  2426. tiger_4passes_desc.name = tiger_4passes_name;
  2427. tiger_4passes_desc.ID |= 0x80u;
  2428. memset(tiger_4passes_desc.OID, 0, sizeof(tiger_4passes_desc.OID));
  2429. tiger_4passes_desc.OIDlen = 0;
  2430. if ((err = register_hash(&tiger_4passes_desc)) == CRYPT_OK) {
  2431. err = hash_memory(find_hash(tiger_4passes_name), (unsigned char*)"abc", 3, hash, &hashlen);
  2432. }
  2433. if (err != 0) {
  2434. fprintf(stderr, "Error %s (%d)", error_to_string(err), err);
  2435. } else {
  2436. p = hash;
  2437. printf("Resulting hash: ");
  2438. while(hashlen--) {
  2439. printf("%02x", *p++);
  2440. }
  2441. printf("\n");
  2442. }
  2443. return err;
  2444. }
  2445. \end{verbatim}
  2446. \end{small}
  2447. When compiling and running this, the output should be:
  2448. \begin{verbatim}
  2449. Resulting hash: 538883c8fc5f28250299018e66bdf4fdb5ef7b65f2e91753
  2450. \end{verbatim}
  2451. \mysection{Notice}
  2452. It is highly recommended that you \textbf{not} use the MD2, MD4, MD5, or SHA-1 hashes for the purposes of digital signatures or authentication codes.
  2453. These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
  2454. (e.g. Yarrow).
  2455. The other hashes such as the SHA-2 (that includes SHA-512, SHA-512/384, SHA-384, SHA-512/256, SHA-256 and SHA-224), TIGER-192 and TIGER2-192 are still
  2456. considered secure for all purposes you would normally use a hash for.
  2457. \chapter{Checksum Functions}
  2458. \mysection{Preface}
  2459. The API for all checksum functions operate in mode: \textit{init} -- \textit{update} -- \textit{update} -- ... -- \textit{finish}.
  2460. The \textit{finish} functions allow to output a partial result if necessary.
  2461. \mysection{CRC-32 -- Cyclic redundancy check}
  2462. A Cyclic Redundancy Check is an error-detecting code, where LibTomCrypt implements CRC-32 with the polynomial \textit{0x04C11DB7}.
  2463. For further information see \url{https://en.wikipedia.org/wiki/Cyclic_redundancy_check}
  2464. \begin{verbatim}
  2465. void crc32_init(crc32_state *ctx);
  2466. void crc32_update(crc32_state *ctx, const unsigned char *input, unsigned long length);
  2467. void crc32_finish(crc32_state *ctx, void *hash, unsigned long size);
  2468. \end{verbatim}
  2469. \mysection{Adler-32}
  2470. Adler-32 is a checksum algorithm.
  2471. For further information see \url{https://en.wikipedia.org/wiki/Adler-32}.
  2472. \begin{verbatim}
  2473. void adler32_init(adler32_state *ctx);
  2474. void adler32_update(adler32_state *ctx, const unsigned char *input, unsigned long length);
  2475. void adler32_finish(adler32_state *ctx, void *hash, unsigned long size);
  2476. \end{verbatim}
  2477. \chapter{Message Authentication Codes}
  2478. \mysection{HMAC Protocol}
  2479. Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short. An HMAC
  2480. of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify. The purpose is
  2481. to allow an owner of a private symmetric key to produce an HMAC on a message then later verify if it is correct. Any impostor or
  2482. eavesdropper will not be able to verify the authenticity of a message.
  2483. The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
  2484. and its length. The key is much like a key you would pass to a cipher. That is, it is simply an array of octets stored in
  2485. unsigned characters. The initialization routine is:
  2486. \index{hmac\_init()}
  2487. \begin{verbatim}
  2488. int hmac_init( hmac_state *hmac,
  2489. int hash,
  2490. const unsigned char *key,
  2491. unsigned long keylen);
  2492. \end{verbatim}
  2493. The \textit{hmac} parameter is the state for the HMAC code. The \textit{hash} parameter is the index into the descriptor table of the hash you want
  2494. to use to authenticate the message. The \textit{key} parameter is the pointer to the array of chars that make up the key. The \textit{keylen} parameter is the
  2495. length (in octets) of the key you want to use to authenticate the message. To send octets of a message through the HMAC system you must use the following function:
  2496. \index{hmac\_process()}
  2497. \begin{verbatim}
  2498. int hmac_process( hmac_state *hmac,
  2499. const unsigned char *in,
  2500. unsigned long inlen);
  2501. \end{verbatim}
  2502. \textit{hmac} is the HMAC state you are working with. \textit{in} is the array of octets to send into the HMAC process. \textit{inlen} is the
  2503. number of octets to process. Like the hash process routines, you can send the data in arbitrarily sized chunks. When you
  2504. are finished with the HMAC process you must call the following function to get the HMAC code:
  2505. \index{hmac\_done()}
  2506. \begin{verbatim}
  2507. int hmac_done( hmac_state *hmac,
  2508. unsigned char *out,
  2509. unsigned long *outlen);
  2510. \end{verbatim}
  2511. The \textit{hmac} parameter is the HMAC state you are working with. The \textit{out} parameter is the array of octets where the HMAC code should be stored.
  2512. You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
  2513. produced (depending on which hash was picked). If \textit{outlen} is less than the size of the message digest (and ultimately
  2514. the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).
  2515. There are two utility functions provided to make using HMACs easier to do. They accept the key and information about the
  2516. message (file pointer, address in memory), and produce the HMAC result in one shot. These are useful if you want to avoid
  2517. calling the three step process yourself.
  2518. \index{hmac\_memory()}
  2519. \begin{verbatim}
  2520. int hmac_memory(
  2521. int hash,
  2522. const unsigned char *key, unsigned long keylen,
  2523. const unsigned char *in, unsigned long inlen,
  2524. unsigned char *out, unsigned long *outlen);
  2525. \end{verbatim}
  2526. This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}. The index into the hash descriptor
  2527. table must be provided in \textit{hash}. It uses the key from \textit{key} with a key length of \textit{keylen}.
  2528. The result is stored in the array of octets \textit{out} and the length in \textit{outlen}. The value of \textit{outlen} must be set
  2529. to the size of the destination buffer before calling this function. Similarly for files there is the following function:
  2530. \index{hmac\_file()}
  2531. \begin{verbatim}
  2532. int hmac_file(
  2533. int hash,
  2534. const char *fname,
  2535. const unsigned char *key, unsigned long keylen,
  2536. unsigned char *out, unsigned long *outlen);
  2537. \end{verbatim}
  2538. \textit{hash} is the index into the hash descriptor table of the hash you want to use. \textit{fname} is the filename to process.
  2539. \textit{key} is the array of octets to use as the key of length \textit{keylen}. \textit{out} is the array of octets where the
  2540. result should be stored.
  2541. To test if the HMAC code is working there is the following function:
  2542. \index{hmac\_test()}
  2543. \begin{verbatim}
  2544. int hmac_test(void);
  2545. \end{verbatim}
  2546. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  2547. HMAC system is given below.
  2548. \begin{small}
  2549. \begin{verbatim}
  2550. #include <tomcrypt.h>
  2551. int main(void)
  2552. {
  2553. int idx, err;
  2554. hmac_state hmac;
  2555. unsigned char key[16], dst[MAXBLOCKSIZE];
  2556. unsigned long dstlen;
  2557. /* register SHA-1 */
  2558. if (register_hash(&sha1_desc) == -1) {
  2559. printf("Error registering SHA1\n");
  2560. return -1;
  2561. }
  2562. /* get index of SHA1 in hash descriptor table */
  2563. idx = find_hash("sha1");
  2564. /* we would make up our symmetric key in "key[]" here */
  2565. /* start the HMAC */
  2566. if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
  2567. printf("Error setting up hmac: %s\n", error_to_string(err));
  2568. return -1;
  2569. }
  2570. /* process a few octets */
  2571. if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
  2572. printf("Error processing hmac: %s\n", error_to_string(err));
  2573. return -1;
  2574. }
  2575. /* get result (presumably to use it somehow...) */
  2576. dstlen = sizeof(dst);
  2577. if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
  2578. printf("Error finishing hmac: %s\n", error_to_string(err));
  2579. return -1;
  2580. }
  2581. printf("The hmac is %lu bytes long\n", dstlen);
  2582. /* return */
  2583. return 0;
  2584. }
  2585. \end{verbatim}
  2586. \end{small}
  2587. \mysection{OMAC Support}
  2588. \index{OMAC} \index{CMAC}
  2589. OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
  2590. algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. Note: OMAC has been standardized as
  2591. CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous. From an API standpoint, the OMAC routines work much like the
  2592. HMAC routines. Instead, in this case a cipher is used instead of a hash.
  2593. To start an OMAC state you call
  2594. \index{omac\_init()}
  2595. \begin{verbatim}
  2596. int omac_init( omac_state *omac,
  2597. int cipher,
  2598. const unsigned char *key,
  2599. unsigned long keylen);
  2600. \end{verbatim}
  2601. The \textit{omac} parameter is the state for the OMAC algorithm. The \textit{cipher} parameter is the index into the cipher\_descriptor table
  2602. of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
  2603. wish to use. The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.
  2604. To send data through the algorithm call
  2605. \index{omac\_process()}
  2606. \begin{verbatim}
  2607. int omac_process( omac_state *state,
  2608. const unsigned char *in,
  2609. unsigned long inlen);
  2610. \end{verbatim}
  2611. This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}. Returns \textbf{CRYPT\_OK} if the
  2612. function succeeds. The function is not sensitive to the granularity of the data. For example,
  2613. \begin{verbatim}
  2614. omac_process(&mystate, "hello", 5);
  2615. omac_process(&mystate, " world", 6);
  2616. \end{verbatim}
  2617. Would produce the same result as,
  2618. \begin{verbatim}
  2619. omac_process(&mystate, "hello world", 11);
  2620. \end{verbatim}
  2621. When you are done processing the message you can call the following to compute the message tag.
  2622. \index{omac\_done()}
  2623. \begin{verbatim}
  2624. int omac_done( omac_state *state,
  2625. unsigned char *out,
  2626. unsigned long *outlen);
  2627. \end{verbatim}
  2628. Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}. Note that unlike the HMAC and other code
  2629. \textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
  2630. specification states that the output may be truncated. So if you pass in $outlen = 5$ and use AES as your cipher than
  2631. the output MAC code will only be five bytes long. If \textit{outlen} is larger than the default size it is set to the default
  2632. size to show how many bytes were actually used.
  2633. Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
  2634. following function.
  2635. \index{omac\_memory()}
  2636. \begin{verbatim}
  2637. int omac_memory(
  2638. int cipher,
  2639. const unsigned char *key, unsigned long keylen,
  2640. const unsigned char *in, unsigned long inlen,
  2641. unsigned char *out, unsigned long *outlen);
  2642. \end{verbatim}
  2643. This will compute the OMAC of \textit{inlen} bytes of \textit{in} using the key \textit{key} of length \textit{keylen} bytes and the cipher
  2644. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
  2645. rules as omac\_done.
  2646. To OMAC a file use
  2647. \index{omac\_file()}
  2648. \begin{verbatim}
  2649. int omac_file(
  2650. int cipher,
  2651. const unsigned char *key, unsigned long keylen,
  2652. const char *filename,
  2653. unsigned char *out, unsigned long *outlen);
  2654. \end{verbatim}
  2655. Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
  2656. and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
  2657. the same rules as omac\_done.
  2658. To test if the OMAC code is working there is the following function:
  2659. \index{omac\_test()}
  2660. \begin{verbatim}
  2661. int omac_test(void);
  2662. \end{verbatim}
  2663. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  2664. OMAC system is given below.
  2665. \begin{small}
  2666. \begin{verbatim}
  2667. #include <tomcrypt.h>
  2668. int main(void)
  2669. {
  2670. int idx, err;
  2671. omac_state omac;
  2672. unsigned char key[16], dst[MAXBLOCKSIZE];
  2673. unsigned long dstlen;
  2674. /* register Rijndael */
  2675. if (register_cipher(&rijndael_desc) == -1) {
  2676. printf("Error registering Rijndael\n");
  2677. return -1;
  2678. }
  2679. /* get index of Rijndael in cipher descriptor table */
  2680. idx = find_cipher("rijndael");
  2681. /* we would make up our symmetric key in "key[]" here */
  2682. /* start the OMAC */
  2683. if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
  2684. printf("Error setting up omac: %s\n", error_to_string(err));
  2685. return -1;
  2686. }
  2687. /* process a few octets */
  2688. if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
  2689. printf("Error processing omac: %s\n", error_to_string(err));
  2690. return -1;
  2691. }
  2692. /* get result (presumably to use it somehow...) */
  2693. dstlen = sizeof(dst);
  2694. if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
  2695. printf("Error finishing omac: %s\n", error_to_string(err));
  2696. return -1;
  2697. }
  2698. printf("The omac is %lu bytes long\n", dstlen);
  2699. /* return */
  2700. return 0;
  2701. }
  2702. \end{verbatim}
  2703. \end{small}
  2704. \mysection{PMAC Support}
  2705. The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}}
  2706. protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
  2707. API as the provided OMAC code.
  2708. A PMAC state is initialized with the following.
  2709. \index{pmac\_init()}
  2710. \begin{verbatim}
  2711. int pmac_init( pmac_state *pmac,
  2712. int cipher,
  2713. const unsigned char *key,
  2714. unsigned long keylen);
  2715. \end{verbatim}
  2716. Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes. The chosen cipher
  2717. must have a 64 or 128 bit block size (e.x. AES).
  2718. To MAC data simply send it through the process function.
  2719. \index{pmac\_process()}
  2720. \begin{verbatim}
  2721. int pmac_process( pmac_state *state,
  2722. const unsigned char *in,
  2723. unsigned long inlen);
  2724. \end{verbatim}
  2725. This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}. The function is not sensitive to the granularity of the
  2726. data. For example,
  2727. \begin{verbatim}
  2728. pmac_process(&mystate, "hello", 5);
  2729. pmac_process(&mystate, " world", 6);
  2730. \end{verbatim}
  2731. Would produce the same result as,
  2732. \begin{verbatim}
  2733. pmac_process(&mystate, "hello world", 11);
  2734. \end{verbatim}
  2735. When a complete message has been processed the following function can be called to compute the message tag.
  2736. \index{pmac\_done()}
  2737. \begin{verbatim}
  2738. int pmac_done( pmac_state *state,
  2739. unsigned char *out,
  2740. unsigned long *outlen);
  2741. \end{verbatim}
  2742. This will store up to \textit{outlen} bytes of the tag for the given \textit{state} into \textit{out}. Note that if \textit{outlen} is larger
  2743. than the size of the tag it is set to the amount of bytes stored in \textit{out}.
  2744. Similar to the OMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
  2745. following function.
  2746. \index{pmac\_memory()}
  2747. \begin{verbatim}
  2748. int pmac_memory(
  2749. int cipher,
  2750. const unsigned char *key, unsigned long keylen,
  2751. const unsigned char *in, unsigned long inlen,
  2752. unsigned char *out, unsigned long *outlen);
  2753. \end{verbatim}
  2754. This will compute the PMAC of \textit{msglen} bytes of \textit{msg} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2755. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
  2756. rules as pmac\_done().
  2757. To PMAC a file use
  2758. \index{pmac\_file()}
  2759. \begin{verbatim}
  2760. int pmac_file(
  2761. int cipher,
  2762. const unsigned char *key, unsigned long keylen,
  2763. const char *filename,
  2764. unsigned char *out, unsigned long *outlen);
  2765. \end{verbatim}
  2766. Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes,
  2767. and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
  2768. the same rules as pmac\_done().
  2769. To test if the PMAC code is working there is the following function:
  2770. \index{pmac\_test()}
  2771. \begin{verbatim}
  2772. int pmac_test(void);
  2773. \end{verbatim}
  2774. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
  2775. \mysection{Pelican MAC}
  2776. Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit{mixing function}. It achieves a very high
  2777. rate of processing and is potentially very secure. It requires AES to be enabled to function. You do not have to register\_cipher() AES first though
  2778. as it calls AES directly.
  2779. \index{pelican\_init()}
  2780. \begin{verbatim}
  2781. int pelican_init( pelican_state *pelmac,
  2782. const unsigned char *key,
  2783. unsigned long keylen);
  2784. \end{verbatim}
  2785. This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
  2786. \index{pelican\_process()}
  2787. \begin{verbatim}
  2788. int pelican_process( pelican_state *pelmac,
  2789. const unsigned char *in,
  2790. unsigned long inlen);
  2791. \end{verbatim}
  2792. This will process \textit{inlen} bytes of \textit{in} through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
  2793. routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
  2794. an entire message.
  2795. \index{pelican\_done()}
  2796. \begin{verbatim}
  2797. int pelican_done(pelican_state *pelmac, unsigned char *out);
  2798. \end{verbatim}
  2799. This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.
  2800. \subsection{Example}
  2801. \begin{verbatim}
  2802. #include <tomcrypt.h>
  2803. int main(void)
  2804. {
  2805. pelican_state pelstate;
  2806. unsigned char key[32], tag[16];
  2807. int err;
  2808. /* somehow initialize a key */
  2809. /* initialize pelican mac */
  2810. if ((err = pelican_init(&pelstate, /* the state */
  2811. key, /* user key */
  2812. 32 /* key length in octets */
  2813. )) != CRYPT_OK) {
  2814. printf("Error initializing Pelican: %s",
  2815. error_to_string(err));
  2816. return EXIT_FAILURE;
  2817. }
  2818. /* MAC some data */
  2819. if ((err = pelican_process(&pelstate, /* the state */
  2820. "hello world", /* data to mac */
  2821. 11 /* length of data */
  2822. )) != CRYPT_OK) {
  2823. printf("Error processing Pelican: %s",
  2824. error_to_string(err));
  2825. return EXIT_FAILURE;
  2826. }
  2827. /* Terminate the MAC */
  2828. if ((err = pelican_done(&pelstate,/* the state */
  2829. tag /* where to store the tag */
  2830. )) != CRYPT_OK) {
  2831. printf("Error terminating Pelican: %s",
  2832. error_to_string(err));
  2833. return EXIT_FAILURE;
  2834. }
  2835. /* tag[0..15] has the MAC output now */
  2836. return EXIT_SUCCESS;
  2837. }
  2838. \end{verbatim}
  2839. \mysection{XCBC-MAC}
  2840. As of LibTomCrypt v1.15, XCBC-MAC (RFC 3566) has been provided to support TLS encryption suites. Like OMAC, it computes a message authentication code
  2841. by using a cipher in CBC mode. It also uses a single key which it expands into the requisite three keys for the MAC function. A XCBC--MAC state is
  2842. initialized with the following function:
  2843. \index{xcbc\_init()}
  2844. \begin{verbatim}
  2845. int xcbc_init( xcbc_state *xcbc,
  2846. int cipher,
  2847. const unsigned char *key,
  2848. unsigned long keylen);
  2849. \end{verbatim}
  2850. This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
  2851. by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
  2852. \index{LTC\_XCBC\_PURE}
  2853. It is possible to use XCBC in a three key mode by OR'ing the value \textbf{LTC\_XCBC\_PURE} against the \textit{keylen} parameter. In this mode, the key is
  2854. interpretted as three keys. If the cipher has a block size of $n$ octets, the first key is then $keylen - 2n$ octets and is the encryption key. The next
  2855. $2n$ octets are the $K_1$ and $K_2$ padding keys (used on the last block). For example, to use AES--192 \textit{keylen} should be $24 + 2 \cdot 16 = 56$ octets.
  2856. The three keys are interpretted as if they were concatenated in the \textit{key} buffer.
  2857. To process data through XCBC--MAC use the following function:
  2858. \index{xcbc\_process()}
  2859. \begin{verbatim}
  2860. int xcbc_process( xcbc_state *state,
  2861. const unsigned char *in,
  2862. unsigned long inlen);
  2863. \end{verbatim}
  2864. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}. Like the other MAC functions,
  2865. the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
  2866. To compute the MAC tag value use the following function:
  2867. \index{xcbc\_done()}
  2868. \begin{verbatim}
  2869. int xcbc_done( xcbc_state *state,
  2870. unsigned char *out,
  2871. unsigned long *outlen);
  2872. \end{verbatim}
  2873. This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
  2874. specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return \textbf{CRYPT\_OK} on success.
  2875. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  2876. \index{xcbc\_memory()}
  2877. \begin{verbatim}
  2878. int xcbc_memory(
  2879. int cipher,
  2880. const unsigned char *key, unsigned long keylen,
  2881. const unsigned char *in, unsigned long inlen,
  2882. unsigned char *out, unsigned long *outlen);
  2883. \end{verbatim}
  2884. This will compute the XCBC--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2885. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
  2886. To xcbc a file use
  2887. \index{xcbc\_file()}
  2888. \begin{verbatim}
  2889. int xcbc_file(
  2890. int cipher,
  2891. const unsigned char *key, unsigned long keylen,
  2892. const char *filename,
  2893. unsigned char *out, unsigned long *outlen);
  2894. \end{verbatim}
  2895. Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2896. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
  2897. To test XCBC--MAC for RFC 3566 compliance use the following function:
  2898. \index{xcbc\_test()}
  2899. \begin{verbatim}
  2900. int xcbc_test(void);
  2901. \end{verbatim}
  2902. This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
  2903. \textbf{CRYPT\_NOP}.
  2904. \mysection{F9--MAC}
  2905. The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard. Originally specified to be used with the KASUMI block cipher, it can also be used
  2906. with other ciphers. For LibTomCrypt, the F9--MAC code can use any cipher.
  2907. \subsection{Usage Notice}
  2908. F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding. The padding quite simply is a direction
  2909. bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size. If the message is byte aligned, the padding takes on the form of
  2910. a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.
  2911. If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
  2912. with F9--MAC.
  2913. \subsection{F9--MAC Functions}
  2914. A F9--MAC state is initialized with the following function:
  2915. \index{f9\_init()}
  2916. \begin{verbatim}
  2917. int f9_init( f9_state *f9,
  2918. int cipher,
  2919. const unsigned char *key,
  2920. unsigned long keylen);
  2921. \end{verbatim}
  2922. This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
  2923. by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
  2924. To process data through F9--MAC use the following function:
  2925. \index{f9\_process()}
  2926. \begin{verbatim}
  2927. int f9_process( f9_state *state,
  2928. const unsigned char *in,
  2929. unsigned long inlen);
  2930. \end{verbatim}
  2931. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}. Like the other MAC functions,
  2932. the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
  2933. To compute the MAC tag value use the following function:
  2934. \index{f9\_done()}
  2935. \begin{verbatim}
  2936. int f9_done( f9_state *state,
  2937. unsigned char *out,
  2938. unsigned long *outlen);
  2939. \end{verbatim}
  2940. This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
  2941. specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return
  2942. \textbf{CRYPT\_OK} on success.
  2943. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  2944. \index{f9\_memory()}
  2945. \begin{verbatim}
  2946. int f9_memory(
  2947. int cipher,
  2948. const unsigned char *key, unsigned long keylen,
  2949. const unsigned char *in, unsigned long inlen,
  2950. unsigned char *out, unsigned long *outlen);
  2951. \end{verbatim}
  2952. This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2953. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
  2954. To F9--MAC a file use
  2955. \index{f9\_file()}
  2956. \begin{verbatim}
  2957. int f9_file(
  2958. int cipher,
  2959. const unsigned char *key, unsigned long keylen,
  2960. const char *filename,
  2961. unsigned char *out, unsigned long *outlen);
  2962. \end{verbatim}
  2963. Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2964. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
  2965. To test f9--MAC for RFC 3566 compliance use the following function:
  2966. \index{f9\_test()}
  2967. \begin{verbatim}
  2968. int f9_test(void);
  2969. \end{verbatim}
  2970. This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
  2971. \textbf{CRYPT\_NOP}.
  2972. \mysection{Poly1305--MAC}
  2973. The Poly1305--MAC is a cryptographic message authentication code created by Daniel J. Bernstein.
  2974. More info at \url{https://en.wikipedia.org/wiki/Poly1305}.
  2975. A Poly1305--MAC state is initialized with the following function:
  2976. \index{poly1305\_init()}
  2977. \begin{verbatim}
  2978. int poly1305_init( poly1305_state *st,
  2979. const unsigned char *key,
  2980. unsigned long keylen);
  2981. \end{verbatim}
  2982. This will initialize the Poly1305--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (always 32).
  2983. To process data through Poly1305--MAC use the following function:
  2984. \index{poly1305\_process()}
  2985. \begin{verbatim}
  2986. int poly1305_process( poly1305_state *st,
  2987. const unsigned char *in,
  2988. unsigned long inlen);
  2989. \end{verbatim}
  2990. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the Poly1305--MAC state pointed to by \textit{st}.
  2991. To compute the MAC tag value use the following function:
  2992. \index{poly1305\_done()}
  2993. \begin{verbatim}
  2994. int poly1305_done(poly1305_state *st,
  2995. unsigned char *mac,
  2996. unsigned long *maclen);
  2997. \end{verbatim}
  2998. This will retrieve the Poly1305--MAC tag from the state pointed to by \textit{st}, and store it in the array pointed to by \textit{mac}.
  2999. The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
  3000. the function returns.
  3001. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  3002. \index{poly1305\_memory()}
  3003. \begin{verbatim}
  3004. int poly1305_memory(const unsigned char *key,
  3005. unsigned long keylen,
  3006. const unsigned char *in,
  3007. unsigned long inlen,
  3008. unsigned char *mac,
  3009. unsigned long *maclen);
  3010. \end{verbatim}
  3011. This will compute the Poly1305--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
  3012. It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
  3013. To Poly1305--MAC a file use
  3014. \index{poly1305\_file()}
  3015. \begin{verbatim}
  3016. int poly1305_file( const char *fname,
  3017. const unsigned char *key,
  3018. unsigned long keylen,
  3019. unsigned char *mac,
  3020. unsigned long *maclen);
  3021. \end{verbatim}
  3022. Which will Poly1305--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
  3023. length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
  3024. \mysection{BLAKE2s + BLAKE2b MAC}
  3025. The BLAKE2s and BLAKE2b are cryptographic message authentication code designed by Jean--Philippe Aumasson,
  3026. Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. More info at \url{https://tools.ietf.org/html/rfc7693}.
  3027. A BLAKE2s/b--MAC state is initialized with the following function:
  3028. \index{blake2smac\_init()}
  3029. \begin{verbatim}
  3030. int blake2smac_init(blake2smac_state *st,
  3031. unsigned long outlen,
  3032. const unsigned char *key,
  3033. unsigned long keylen);
  3034. \end{verbatim}
  3035. \index{blake2bmac\_init()}
  3036. \begin{verbatim}
  3037. int blake2bmac_init(blake2smac_state *st,
  3038. unsigned long outlen,
  3039. const unsigned char *key,
  3040. unsigned long keylen);
  3041. \end{verbatim}
  3042. This will initialize the BLAKE2s/b--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (up to 64).
  3043. The \textit{outlen} specifies the size of the final tag (up to 64 octets).
  3044. To process data through BLAKE2s/b--MAC use the following function:
  3045. \index{blake2smac\_process()}
  3046. \begin{verbatim}
  3047. int blake2smac_process( blake2smac_state *st,
  3048. const unsigned char *in,
  3049. unsigned long inlen);
  3050. \end{verbatim}
  3051. \index{blake2bmac\_process()}
  3052. \begin{verbatim}
  3053. int blake2bmac_process( blake2bmac_state *st,
  3054. const unsigned char *in,
  3055. unsigned long inlen);
  3056. \end{verbatim}
  3057. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the BLAKE2s/b--MAC state pointed to by \textit{st}.
  3058. To compute the MAC tag value use the following function:
  3059. \index{blake2smac\_done()}
  3060. \begin{verbatim}
  3061. int blake2smac_done(blake2smac_state *st,
  3062. unsigned char *mac,
  3063. unsigned long *maclen);
  3064. \end{verbatim}
  3065. \index{blake2bmac\_done()}
  3066. \begin{verbatim}
  3067. int blake2bmac_done(blake2bmac_state *st,
  3068. unsigned char *mac,
  3069. unsigned long *maclen);
  3070. \end{verbatim}
  3071. This will retrieve the BLAKE2s/b--MAC tag from the state pointed to by \textit{st}, and store it in the array pointed to by \textit{mac}.
  3072. The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
  3073. the function returns.
  3074. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  3075. \index{blake2smac\_memory()}
  3076. \begin{verbatim}
  3077. int blake2smac_memory(const unsigned char *key,
  3078. unsigned long keylen,
  3079. const unsigned char *in,
  3080. unsigned long inlen,
  3081. unsigned char *mac,
  3082. unsigned long *maclen);
  3083. \end{verbatim}
  3084. \index{blake2bmac\_memory()}
  3085. \begin{verbatim}
  3086. int blake2bmac_memory(const unsigned char *key,
  3087. unsigned long keylen,
  3088. const unsigned char *in,
  3089. unsigned long inlen,
  3090. unsigned char *mac,
  3091. unsigned long *maclen);
  3092. \end{verbatim}
  3093. This will compute the BLAKE2s/b--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
  3094. It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().
  3095. To BLAKE2s/b--MAC a file use
  3096. \index{blake2smac\_file()}
  3097. \begin{verbatim}
  3098. int blake2smac_file( const char *fname,
  3099. const unsigned char *key,
  3100. unsigned long keylen,
  3101. unsigned char *mac,
  3102. unsigned long *maclen);
  3103. \end{verbatim}
  3104. \index{blake2bmac\_file()}
  3105. \begin{verbatim}
  3106. int blake2bmac_file( const char *fname,
  3107. const unsigned char *key,
  3108. unsigned long keylen,
  3109. unsigned char *mac,
  3110. unsigned long *maclen);
  3111. \end{verbatim}
  3112. Which will BLAKE2s/b--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
  3113. length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().
  3114. \chapter{Pseudo-Random Number Generators}
  3115. \mysection{Core Functions}
  3116. The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
  3117. used to expand a shorter bit string into a longer bit string. PRNGs are used wherever random data is required such as Public Key (PK)
  3118. key generation. There is a universal structure called \textit{prng\_state}. To initialize a PRNG call:
  3119. \index{PRNG start}
  3120. \begin{verbatim}
  3121. int XXX_start(prng_state *prng);
  3122. \end{verbatim}
  3123. This will setup the PRNG for future use and not seed it. In order for the PRNG to be cryptographically useful you must give it
  3124. entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
  3125. \index{PRNG add\_entropy}
  3126. \begin{verbatim}
  3127. int XXX_add_entropy(const unsigned char *in,
  3128. unsigned long inlen,
  3129. prng_state *prng);
  3130. \end{verbatim}
  3131. Which returns {\bf CRYPT\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
  3132. function to put the entropy into action.
  3133. \index{PRNG ready}
  3134. \begin{verbatim}
  3135. int XXX_ready(prng_state *prng);
  3136. \end{verbatim}
  3137. Which returns {\bf CRYPT\_OK} if it is ready. Finally to actually read bytes call:
  3138. \index{PRNG read}
  3139. \begin{verbatim}
  3140. unsigned long XXX_read(unsigned char *out,
  3141. unsigned long outlen,
  3142. prng_state *prng);
  3143. \end{verbatim}
  3144. Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
  3145. the following.
  3146. \index{PRNG done}
  3147. \begin{verbatim}
  3148. void XXX_done(prng_state *prng);
  3149. \end{verbatim}
  3150. This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
  3151. so that you can later resume the PRNG call the following.
  3152. \index{PRNG export}
  3153. \begin{verbatim}
  3154. int XXX_export(unsigned char *out,
  3155. unsigned long *outlen,
  3156. prng_state *prng);
  3157. \end{verbatim}
  3158. This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes. The idea of
  3159. the export is meant to be used as a \textit{seed file}. That is, when the program starts up there will not likely
  3160. be that much entropy available. To import a state to seed a PRNG call the following function.
  3161. \index{PRNG import}
  3162. \begin{verbatim}
  3163. int XXX_import(const unsigned char *in,
  3164. unsigned long inlen,
  3165. prng_state *prng);
  3166. \end{verbatim}
  3167. This will call the start and add\_entropy functions of the given PRNG. It will use the state in
  3168. \textit{in} of length \textit{inlen} as the initial seed. You must pass the same seed length as was exported
  3169. by the corresponding export function.
  3170. Note that importing a state will not \textit{resume} the PRNG from where it left off. That is, if you export
  3171. a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
  3172. specifically equal the 8 bytes you generated previously.
  3173. When a program is first executed the normal course of operation is:
  3174. \begin{enumerate}
  3175. \item Gather entropy from your sources for a given period of time or number of events.
  3176. \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
  3177. \end{enumerate}
  3178. When your program is finished you simply call the export function and save the state to a medium (disk,
  3179. flash memory, etc). The next time your application starts up you can detect the state, feed it to the
  3180. import function and go on your way. It is ideal that (as soon as possible) after start up you export a
  3181. fresh state. This helps in the case that the program aborts or the machine is powered down without
  3182. being given a chance to exit properly.
  3183. Note that even if you have a state to import it is important to add new entropy to the state. However,
  3184. there is less pressure to do so.
  3185. To test a PRNG for operational conformity call the following functions.
  3186. \index{PRNG test}
  3187. \begin{verbatim}
  3188. int XXX_test(void);
  3189. \end{verbatim}
  3190. This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
  3191. \subsection{Remarks}
  3192. It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
  3193. and call ready() you can now read from it. You can also keep adding new entropy to it. The new entropy will not be used
  3194. in the PRNG until ready() is called again. This allows the PRNG to be used and re-seeded at the same time. No real error
  3195. checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
  3196. \subsection{Example}
  3197. Below is a simple snippet to read 10 bytes from Yarrow. It is important to note that this snippet is {\bf NOT} secure since
  3198. the entropy added is not random.
  3199. \begin{verbatim}
  3200. #include <tomcrypt.h>
  3201. int main(void)
  3202. {
  3203. prng_state prng;
  3204. unsigned char buf[10];
  3205. int err;
  3206. /* start it */
  3207. if ((err = yarrow_start(&prng)) != CRYPT_OK) {
  3208. printf("Start error: %s\n", error_to_string(err));
  3209. }
  3210. /* add entropy */
  3211. if ((err = yarrow_add_entropy("hello world", 11, &prng))
  3212. != CRYPT_OK) {
  3213. printf("Add_entropy error: %s\n", error_to_string(err));
  3214. }
  3215. /* ready and read */
  3216. if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
  3217. printf("Ready error: %s\n", error_to_string(err));
  3218. }
  3219. printf("Read %lu bytes from yarrow\n",
  3220. yarrow_read(buf, sizeof(buf), &prng));
  3221. return 0;
  3222. }
  3223. \end{verbatim}
  3224. \mysection{PRNG Descriptors}
  3225. \index{PRNG Descriptor}
  3226. PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}. The
  3227. format of an element is:
  3228. \begin{verbatim}
  3229. struct ltc_prng_descriptor {
  3230. char *name;
  3231. int export_size; /* size in bytes of exported state */
  3232. int (*start) (prng_state *);
  3233. int (*add_entropy)(const unsigned char *, unsigned long,
  3234. prng_state *);
  3235. int (*ready) (prng_state *);
  3236. unsigned long (*read)(unsigned char *, unsigned long len,
  3237. prng_state *);
  3238. void (*done)(prng_state *);
  3239. int (*pexport)(unsigned char *, unsigned long *, prng_state *);
  3240. int (*pimport)(const unsigned char *, unsigned long, prng_state *);
  3241. int (*test)(void);
  3242. };
  3243. \end{verbatim}
  3244. To find a PRNG in the descriptor table the following function can be used:
  3245. \index{find\_prng()}
  3246. \begin{verbatim}
  3247. int find_prng(const char *name);
  3248. \end{verbatim}
  3249. This will search the PRNG descriptor table for the PRNG named \textit{name}. It will return -1 if the PRNG is not found, otherwise, it returns
  3250. the index into the descriptor table.
  3251. Just like the ciphers and hashes, you must register your prng before you can use it. The two functions provided work exactly as those for the cipher registry functions.
  3252. They are the following:
  3253. \index{register\_prng()} \index{unregister\_prng()}
  3254. \begin{verbatim}
  3255. int register_prng(const struct ltc_prng_descriptor *prng);
  3256. int unregister_prng(const struct ltc_prng_descriptor *prng);
  3257. \end{verbatim}
  3258. The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error). It will avoid registering the same
  3259. descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once. The unregister function
  3260. will return \textbf{CRYPT\_OK} if the PRNG was found and removed. Otherwise, it returns \textbf{CRYPT\_ERROR}.
  3261. \subsection{PRNGs Provided}
  3262. \begin{figure}[H]
  3263. \begin{center}
  3264. \begin{small}
  3265. \begin{tabular}{|c|c|l|}
  3266. \hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
  3267. \hline ChaCha20 & chacha20\_prng\_desc & Stream Cipher PRNG (recommended, fast) \\
  3268. \hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended, secure) \\
  3269. \hline RC4 & rc4\_desc & Stream Cipher PRNG \\
  3270. \hline SOBER-128 & sober128\_desc & Stream Cipher PRNG \\
  3271. \hline sprng & sprng\_desc & Secure PRNG using the System RNG \\
  3272. \hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
  3273. \hline
  3274. \end{tabular}
  3275. \end{small}
  3276. \end{center}
  3277. \caption{List of Provided PRNGs}
  3278. \end{figure}
  3279. \subsubsection{Yarrow}
  3280. Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
  3281. (keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.
  3282. \textit{Note:} This PRNG is still secure for most tasks but is no longer recommended. Users
  3283. should use Fortuna or ChaCha20 instead.
  3284. \subsubsection{Fortuna}
  3285. Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
  3286. usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
  3287. to work with most cipher and hash combos based on which you have chosen to build into the library.} while
  3288. providing more security.
  3289. Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
  3290. and SHA--256 hash function. Technically, Fortuna will work with any block cipher that accepts a 256--bit
  3291. key, and any hash that produces at least a 256--bit output. However, to make the implementation simpler
  3292. it has been fixed to those choices.
  3293. Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
  3294. added to the PRNG learn far less about the state than that of Yarrow. Without getting into too many
  3295. details Fortuna has the ability to recover from state determination attacks where the attacker starts
  3296. to learn information from the PRNGs output about the internal state. Yarrow on the other hand, cannot
  3297. recover from that problem until new entropy is added to the pool and put to use through the ready() function.
  3298. For detailed information on how the algorithm works and what you have to do to maintain the secure state
  3299. get a copy of the book\footnote{Niels Ferguson and Bruce Schneier, Practical Cryptography. ISBN 0-471-22357-3.} or
  3300. read the paper online\footnote{\url{https://www.schneier.com/academic/paperfiles/fortuna.pdf} [Accessed on 7th Dec. 2017]}.
  3301. Fortuna provides additional API functions to be able to implement some of the important steps proposed in the original algorithm specification.
  3302. \index{fortuna\_add\_random\_event()}
  3303. \begin{verbatim}
  3304. int fortuna_add_random_event( unsigned long source, unsigned long pool,
  3305. const unsigned char *in, unsigned long inlen,
  3306. prng_state *prng);
  3307. \end{verbatim}
  3308. \textit{fortuna\_add\_random\_event()} can be used as a powerful alternative to the more general \textit{add\_entropy()}.
  3309. \index{fortuna\_update\_seed()}
  3310. \begin{verbatim}
  3311. int fortuna_update_seed(const unsigned char *in, unsigned long inlen,
  3312. prng_state *prng);
  3313. \end{verbatim}
  3314. \textit{fortuna\_update\_seed()} can be used to implement the \textit{UpdateSeedFile} function from the original specification.
  3315. \subsubsection{RC4}
  3316. RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You key RC4 by
  3317. calling add\_entropy(), and setup the key by calling ready().
  3318. You really should not use RC4 for cryptographical purposes, it's broken.
  3319. \subsubsection{SOBER-128}
  3320. SOBER--128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4, you key it by
  3321. calling add\_entropy(). There is no need to call ready() for this PRNG as it does not do anything.
  3322. Note: this cipher has several oddities about how it operates. The first call to add\_entropy() sets the cipher's key.
  3323. Every other time call to the add\_entropy() function sets the cipher's IV variable. The IV mechanism allows you to
  3324. encrypt several messages with the same key, and not re--use the same key material.
  3325. Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
  3326. you pass it on the \textbf{first} call to add\_entropy(). All buffers sent to add\_entropy() must have a length
  3327. that is a multiple of four bytes.
  3328. Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner, you can use
  3329. sober128\_read() as an encrypt (and decrypt) function.
  3330. Since SOBER--128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
  3331. key it from the output of Fortuna (or Yarrow), and use it to encrypt messages. It is also ideal for
  3332. simulations which need a high quality (and fast) stream of bytes.
  3333. \subsubsection{ChaCha20}
  3334. ChaCha20 is a fast stream cipher built on a pseudorandom function designed by Daniel J. Bernstein.
  3335. It can also double duty as a PRNG.
  3336. It is recommended to use 40 bytes of truly random bytes for initialization.
  3337. The implementation supports adding entropy via the add\_entropy() function while already being operational.
  3338. \subsubsection{Example Usage}
  3339. \begin{small}
  3340. \begin{verbatim}
  3341. #include <tomcrypt.h>
  3342. int main(void)
  3343. {
  3344. prng_state prng;
  3345. unsigned char buf[32];
  3346. int err;
  3347. if ((err = rc4_start(&prng)) != CRYPT_OK) {
  3348. printf("RC4 init error: %s\n", error_to_string(err));
  3349. exit(-1);
  3350. }
  3351. /* use "key" as the key */
  3352. if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
  3353. printf("RC4 add entropy error: %s\n", error_to_string(err));
  3354. exit(-1);
  3355. }
  3356. /* setup RC4 for use */
  3357. if ((err = rc4_ready(&prng)) != CRYPT_OK) {
  3358. printf("RC4 ready error: %s\n", error_to_string(err));
  3359. exit(-1);
  3360. }
  3361. /* encrypt buffer */
  3362. strcpy(buf,"hello world");
  3363. if (rc4_read(buf, 11, &prng) != 11) {
  3364. printf("RC4 read error\n");
  3365. exit(-1);
  3366. }
  3367. return 0;
  3368. }
  3369. \end{verbatim}
  3370. \end{small}
  3371. To decrypt you have to do the exact same steps.
  3372. \mysection{The Secure RNG}
  3373. \index{Secure RNG}
  3374. An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data. They generate their random bits
  3375. by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
  3376. PRNG. Computers are deterministic that try hard not to stray from pre--determined paths. This makes gathering entropy needed to seed a PRNG
  3377. a hard task.
  3378. There is one small function that may help on certain platforms:
  3379. \index{rng\_get\_bytes()}
  3380. \begin{verbatim}
  3381. unsigned long rng_get_bytes(
  3382. unsigned char *buf,
  3383. unsigned long len,
  3384. void (*callback)(void));
  3385. \end{verbatim}
  3386. Which will try one of three methods of getting random data. The first is to open the popular \textit{/dev/random} device which
  3387. on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite. It emulates \textit{/dev/random} via the Microsoft CSP.}.
  3388. The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG. The third method is an ANSI C
  3389. clock drift method that is also somewhat popular but gives bits of lower entropy. The \textit{callback} parameter is a pointer to a function that returns void. It is
  3390. used when the slower ANSI C RNG must be used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of roughly three
  3391. bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to. The function returns the number of bytes actually read from
  3392. any RNG source. There is a function to help setup a PRNG as well:
  3393. \index{rng\_make\_prng()}
  3394. \begin{verbatim}
  3395. int rng_make_prng( int bits,
  3396. int wprng,
  3397. prng_state *prng,
  3398. void (*callback)(void));
  3399. \end{verbatim}
  3400. This will try to initialize the prng with a state of at least \textit{bits} of entropy. The \textit{callback} parameter works much like
  3401. the callback in \textit{rng\_get\_bytes()}. It is highly recommended that you use this function to setup your PRNGs unless you have a
  3402. platform where the RNG does not work well. Example usage of this function is given below:
  3403. \begin{small}
  3404. \begin{verbatim}
  3405. #include <tomcrypt.h>
  3406. int main(void)
  3407. {
  3408. ecc_key mykey;
  3409. prng_state prng;
  3410. int err;
  3411. /* register yarrow */
  3412. if (register_prng(&yarrow_desc) == -1) {
  3413. printf("Error registering Yarrow\n");
  3414. return -1;
  3415. }
  3416. /* setup the PRNG */
  3417. if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL))
  3418. != CRYPT_OK) {
  3419. printf("Error setting up PRNG, %s\n", error_to_string(err));
  3420. return -1;
  3421. }
  3422. /* make a 192-bit ECC key */
  3423. if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey))
  3424. != CRYPT_OK) {
  3425. printf("Error making key: %s\n", error_to_string(err));
  3426. return -1;
  3427. }
  3428. return 0;
  3429. }
  3430. \end{verbatim}
  3431. \end{small}
  3432. \subsection{The Secure PRNG Interface}
  3433. \index{sprng\_desc}
  3434. It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
  3435. as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
  3436. requires to be started, that is you need not call the start, add\_entropy, or ready functions. For example, consider
  3437. the previous example using this PRNG.
  3438. \begin{small}
  3439. \begin{verbatim}
  3440. #include <tomcrypt.h>
  3441. int main(void)
  3442. {
  3443. ecc_key mykey;
  3444. int err;
  3445. /* register SPRNG */
  3446. if (register_prng(&sprng_desc) == -1) {
  3447. printf("Error registering SPRNG\n");
  3448. return -1;
  3449. }
  3450. /* make a 192-bit ECC key */
  3451. if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey))
  3452. != CRYPT_OK) {
  3453. printf("Error making key: %s\n", error_to_string(err));
  3454. return -1;
  3455. }
  3456. return 0;
  3457. }
  3458. \end{verbatim}
  3459. \end{small}
  3460. \chapter{RSA Public Key Cryptography}
  3461. \mysection{Introduction}
  3462. RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
  3463. padding algorithms for encryption and signatures. The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
  3464. To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.
  3465. \mysection{PKCS \#1 Padding}
  3466. PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function. Note: the
  3467. signature padding does \textbf{not} include the ASN.1 padding required. That is performed by the rsa\_sign\_hash\_ex() function
  3468. documented later on in this chapter.
  3469. \subsection{PKCS \#1 v1.5 Encoding}
  3470. The following function performs PKCS \#1 v1.5 padding:
  3471. \index{pkcs\_1\_v1\_5\_encode()}
  3472. \begin{verbatim}
  3473. int pkcs_1_v1_5_encode(
  3474. const unsigned char *msg,
  3475. unsigned long msglen,
  3476. int block_type,
  3477. unsigned long modulus_bitlen,
  3478. prng_state *prng,
  3479. int prng_idx,
  3480. unsigned char *out,
  3481. unsigned long *outlen);
  3482. \end{verbatim}
  3483. This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets. The \textit{block\_type} parameter must be set to
  3484. \textbf{LTC\_PKCS\_1\_EME} to perform encryption padding. It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding. The \textit{modulus\_bitlen}
  3485. parameter indicates the length of the modulus in bits. The padded data is stored in \textit{out} with a length of \textit{outlen} octets. The output will not be
  3486. longer than the modulus which helps allocate the correct output buffer size.
  3487. Only encryption padding requires a PRNG. When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.
  3488. \subsection{PKCS \#1 v1.5 Decoding}
  3489. The following function performs PKCS \#1 v1.5 de--padding:
  3490. \index{pkcs\_1\_v1\_5\_decode()}
  3491. \begin{verbatim}
  3492. int pkcs_1_v1_5_decode(
  3493. const unsigned char *msg,
  3494. unsigned long msglen,
  3495. int block_type,
  3496. unsigned long modulus_bitlen,
  3497. unsigned char *out,
  3498. unsigned long *outlen,
  3499. int *is_valid);
  3500. \end{verbatim}
  3501. \index{LTC\_PKCS\_1\_EME} \index{LTC\_PKCS\_1\_EMSA}
  3502. This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}. The decoded data is stored in \textit{out} of length
  3503. \textit{outlen}. If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored. The \textit{block\_type} parameter must be set to either
  3504. \textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.
  3505. \mysection{PKCS \#1 v2.1 Encryption}
  3506. PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
  3507. the library is concerned we are only dealing with th OAEP padding of the message.
  3508. \subsection{OAEP Encoding}
  3509. The following function performs PKCS \#1 v2.1 encryption padding:
  3510. \index{pkcs\_1\_oaep\_encode()}
  3511. \begin{alltt}
  3512. int pkcs_1_oaep_encode(
  3513. const unsigned char *msg,
  3514. unsigned long msglen,
  3515. const unsigned char *lparam,
  3516. unsigned long lparamlen,
  3517. unsigned long modulus_bitlen,
  3518. prng_state *prng,
  3519. int prng_idx,
  3520. int mgf_hash,
  3521. int lparam_hash,
  3522. unsigned char *out,
  3523. unsigned long *outlen);
  3524. \end{alltt}
  3525. This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded. The \textit{lparam} variable is an additional system specific
  3526. tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
  3527. \textit{lparam} can be set to \textbf{NULL}.
  3528. OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output. This is passed as the parameter
  3529. \textit{modulus\_bitlen}. \textit{mgf\_hash} is the index into the hash descriptor table of the hash desired for the mask generation function (MGF).
  3530. \textit{lparam\_hash} is the index into the hash descriptor table of the hash desired for the \textit{lparam}. This value can also be set to $-1$
  3531. to indicate usage of the same algorithm than for the MGF. PKCS \#1 allows any hash to be
  3532. used but both the encoder and decoder must use the same hash in order for this to succeed. The size of hash output affects the maximum
  3533. sized input message. \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.
  3534. The padded message is stored in \textit{out} along with the length in \textit{outlen}.
  3535. If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for \textit{msg} is
  3536. $m - 2h - 2$. For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.
  3537. Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
  3538. rsa\_exptmod() to encrypt it.
  3539. \subsection{OAEP Decoding}
  3540. \index{pkcs\_1\_oaep\_decode()}
  3541. \begin{alltt}
  3542. int pkcs_1_oaep_decode(
  3543. const unsigned char *msg,
  3544. unsigned long msglen,
  3545. const unsigned char *lparam,
  3546. unsigned long lparamlen,
  3547. unsigned long modulus_bitlen,
  3548. int mgf_hash,
  3549. int lparam_hash,
  3550. unsigned char *out,
  3551. unsigned long *outlen,
  3552. int *res);
  3553. \end{alltt}
  3554. This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. \textit{msg} is the
  3555. output of pkcs\_1\_oaep\_encode() of length \textit{msglen}. \textit{lparam} is the same system variable passed to the OAEP encoder. If it does not
  3556. match what was used during encoding this function will not decode the packet. \textit{modulus\_bitlen} is the size of the RSA modulus in bits
  3557. and must match what was used during encoding. Similarly the \textit{mgf\_hash} and \textit{lparam\_hash} indexes into the hash descriptor table must
  3558. match what was used during encoding.
  3559. If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a
  3560. $1$ in \textit{res}. If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
  3561. it returns an error code.
  3562. \mysection{PKCS \#1 Digital Signatures}
  3563. \subsection{PSS Encoding}
  3564. PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
  3565. \index{pkcs\_1\_pss\_encode()}
  3566. \begin{alltt}
  3567. int pkcs_1_pss_encode(
  3568. const unsigned char *msghash,
  3569. unsigned long msghashlen,
  3570. unsigned long saltlen,
  3571. prng_state *prng,
  3572. int prng_idx,
  3573. int hash_idx,
  3574. unsigned long modulus_bitlen,
  3575. unsigned char *out,
  3576. unsigned long *outlen);
  3577. \end{alltt}
  3578. This function assumes the message to be PSS encoded has previously been hashed. The input hash \textit{msghash} is of length
  3579. \textit{msghashlen}. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
  3580. \textit{hash\_idx} is the index into the hash descriptor table of the hash to use. \textit{prng\_idx} and \textit{prng} are the random
  3581. number generator information required for the salt.
  3582. Similar to OAEP encoding \textit{modulus\_bitlen} is the size of the RSA modulus (in bits). It limits the size of the salt. If $m$ is the length
  3583. of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
  3584. This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_exptmod().
  3585. \subsection{PSS Decoding}
  3586. To decode a PSS encoded signature block you have to use the following.
  3587. \index{pkcs\_1\_pss\_decode()}
  3588. \begin{alltt}
  3589. int pkcs_1_pss_decode(
  3590. const unsigned char *msghash,
  3591. unsigned long msghashlen,
  3592. const unsigned char *sig,
  3593. unsigned long siglen,
  3594. unsigned long saltlen,
  3595. int hash_idx,
  3596. unsigned long modulus_bitlen,
  3597. int *res);
  3598. \end{alltt}
  3599. This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
  3600. \textit{msghashlen}. If the block is a valid PSS block and the decoded hash equals the hash supplied \textit{res} is set to non--zero. Otherwise,
  3601. it is set to zero. The rest of the parameters are as in the PSS encode call.
  3602. It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
  3603. \mysection{RSA Key Operations}
  3604. \subsection{Background}
  3605. RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown
  3606. factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
  3607. not strictly equivalent.
  3608. The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or \textit{Euler totient} of the
  3609. multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
  3610. $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
  3611. $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
  3612. often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
  3613. A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
  3614. $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
  3615. given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
  3616. $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
  3617. can sign a message by \textit{decrypting} it. Others can verify it by \textit{encrypting} it.
  3618. Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
  3619. Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
  3620. the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
  3621. The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
  3622. designed for fast exponentiation (requires 16 squarings and one multiplication).
  3623. It is important to pad the input to RSA since it has particular mathematical structure. For instance
  3624. $M_1^dM_2^d = (M_1M_2)^d$ which can be used to forge a signature. Suppose $M_3 = M_1M_2$ is a message you want
  3625. to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
  3626. together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
  3627. the hash of documents only but also to pad the inputs with data to remove such structure.
  3628. \subsection{RSA Key Generation}
  3629. For RSA routines a single \textit{rsa\_key} structure is used. To make a new RSA key call:
  3630. \index{rsa\_make\_key()}
  3631. \begin{verbatim}
  3632. int rsa_make_key(prng_state *prng,
  3633. int wprng,
  3634. int size,
  3635. long e,
  3636. rsa_key *key);
  3637. \end{verbatim}
  3638. Where \textit{wprng} is the index into the PRNG descriptor array. The \textit{size} parameter is the size in bytes of the RSA modulus desired.
  3639. The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537. Stick with 65537 since it is big enough to prevent
  3640. trivial math attacks, and not super slow. The \textit{key} parameter is where the constructed key is placed. All keys must be at
  3641. least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
  3642. \index{rsa\_make\_key\_ubin\_e()}
  3643. \begin{verbatim}
  3644. int rsa_make_key_ubin_e(
  3645. prng_state *prng,
  3646. int wprng,
  3647. int size,
  3648. const unsigned char *e,
  3649. unsigned long elen,
  3650. rsa_key *key);
  3651. \end{verbatim}
  3652. Where \textit{wprng} is the index into the PRNG descriptor array. The \textit{size} parameter is the size in bytes of the RSA modulus desired.
  3653. The \textit{e} parameter is the hexadecimal buffer of the encryption exponent desired, from 3 upto 255 bits value. Stick with 65537 since it is big enough
  3654. to prevent trivial math attacks, and not super slow. The \textit{elen} parameter is the size in bytes of the encryption exponent \textit{e}.
  3655. The \textit{key} parameter is where the constructed key is placed. All keys must be at
  3656. least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
  3657. \index{rsa\_free()}
  3658. Note: the \textit{rsa\_make\_key()} and \textit{rsa\_make\_key\_ubin\_e()} functions allocates memory at run--time when you make the key.
  3659. Make sure to call \textit{rsa\_free()} (see below) when you are finished with the key. If \textit{rsa\_make\_key()} or \textit{rsa\_make\_key\_ubin\_e()}
  3660. fails it will automatically free the memory allocated.
  3661. \index{PK\_PRIVATE} \index{PK\_PUBLIC}
  3662. There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
  3663. RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the
  3664. PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant). The second type, is a public RSA key which only includes the modulus and public exponent.
  3665. It takes the form of a RSAPublicKey (PKCS \#1 compliant).
  3666. \subsection{RSA Exponentiation}
  3667. To do raw work with the RSA function, that is without padding, use the following function:
  3668. \index{rsa\_exptmod()}
  3669. \begin{verbatim}
  3670. int rsa_exptmod(const unsigned char *in,
  3671. unsigned long inlen,
  3672. unsigned char *out,
  3673. unsigned long *outlen,
  3674. int which,
  3675. rsa_key *key);
  3676. \end{verbatim}
  3677. This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
  3678. in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e}
  3679. (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
  3680. Note: the output of this function is zero--padded as per PKCS \#1 specification. This allows this routine to work with PKCS \#1 padding functions properly.
  3681. \subsection{RSA Key Size}
  3682. To fetch the key size of an RSA key, use the following function:
  3683. \index{rsa\_get\_size()}
  3684. \begin{verbatim}
  3685. int rsa_get_size(rsa_key *key);
  3686. \end{verbatim}
  3687. This can be used to determine the modulus size of an RSA key.
  3688. \mysection{RSA Key Encryption}
  3689. Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
  3690. To facilitate encrypting short keys the following functions have been provided.
  3691. \index{rsa\_encrypt\_key()}
  3692. \begin{verbatim}
  3693. int rsa_encrypt_key(
  3694. const unsigned char *in,
  3695. unsigned long inlen,
  3696. unsigned char *out,
  3697. unsigned long *outlen,
  3698. const unsigned char *lparam,
  3699. unsigned long lparamlen,
  3700. prng_state *prng,
  3701. int prng_idx,
  3702. int hash_idx,
  3703. rsa_key *key);
  3704. \end{verbatim}
  3705. This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
  3706. in \textit{out} of length \textit{outlen} octets. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
  3707. to \index{pkcs\_1\_oaep\_encode()} pkcs\_1\_oaep\_encode().
  3708. \subsection{Extended Encryption}
  3709. As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
  3710. encryption function:
  3711. \index{rsa\_encrypt\_key\_ex()}
  3712. \begin{verbatim}
  3713. int rsa_encrypt_key_ex(
  3714. const unsigned char *in,
  3715. unsigned long inlen,
  3716. unsigned char *out,
  3717. unsigned long *outlen,
  3718. const unsigned char *lparam,
  3719. unsigned long lparamlen,
  3720. prng_state *prng,
  3721. int prng_idx,
  3722. int mgf_hash,
  3723. int lparam_hash,
  3724. int padding,
  3725. rsa_key *key);
  3726. \end{verbatim}
  3727. \index{LTC\_PKCS\_1\_OAEP} \index{LTC\_PKCS\_1\_V1\_5}
  3728. The parameters are all the same as for rsa\_encrypt\_key() except for the addition of the \textit{padding} parameter. It must be set to
  3729. \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 encryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 encryption.
  3730. When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
  3731. \mysection{RSA Key Decryption}
  3732. \index{rsa\_decrypt\_key()}
  3733. \begin{verbatim}
  3734. int rsa_decrypt_key(
  3735. const unsigned char *in,
  3736. unsigned long inlen,
  3737. unsigned char *out,
  3738. unsigned long *outlen,
  3739. const unsigned char *lparam,
  3740. unsigned long lparamlen,
  3741. int mgf_hash,
  3742. int lparam_hash,
  3743. int *stat,
  3744. rsa_key *key);
  3745. \end{verbatim}
  3746. This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
  3747. \textit{out} of length \textit{outlen}. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
  3748. to pkcs\_1\_oaep\_decode().
  3749. If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$. Otherwise, it is set to $1$.
  3750. \subsection{Extended Decryption}
  3751. As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
  3752. decryption function:
  3753. \index{rsa\_decrypt\_key\_ex()}
  3754. \begin{verbatim}
  3755. int rsa_decrypt_key_ex(
  3756. const unsigned char *in,
  3757. unsigned long inlen,
  3758. unsigned char *out,
  3759. unsigned long *outlen,
  3760. const unsigned char *lparam,
  3761. unsigned long lparamlen,
  3762. int hash_idx,
  3763. int padding,
  3764. int *stat,
  3765. rsa_key *key);
  3766. \end{verbatim}
  3767. Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.
  3768. It must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 decryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 decryption.
  3769. When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
  3770. \mysection{RSA Signature Generation}
  3771. Similar to RSA key encryption RSA is also used to \textit{digitally sign} message digests (hashes). To facilitate this
  3772. process the following functions have been provided.
  3773. \index{rsa\_sign\_hash()}
  3774. \begin{verbatim}
  3775. int rsa_sign_hash(const unsigned char *in,
  3776. unsigned long inlen,
  3777. unsigned char *out,
  3778. unsigned long *outlen,
  3779. prng_state *prng,
  3780. int prng_idx,
  3781. int hash_idx,
  3782. unsigned long saltlen,
  3783. rsa_key *key);
  3784. \end{verbatim}
  3785. This will PSS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PSS encoded hash will be RSA
  3786. \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.
  3787. The \textit{hash\_idx} parameter indicates which hash will be used to create the PSS encoding. It should be the same as the hash used to
  3788. hash the message being signed. The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small. A good
  3789. default value is between 8 and 16 octets. Strictly, it must be small than $modulus\_len - hLen - 2$ where \textit{modulus\_len} is the size of
  3790. the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.
  3791. \subsection{Extended Signatures}
  3792. As of v1.15, the library supports both v1.5 and v2.1 signatures. The extended signature generation function has the following prototype:
  3793. \index{rsa\_sign\_hash\_ex()}
  3794. \begin{verbatim}
  3795. int rsa_sign_hash_ex(
  3796. const unsigned char *in,
  3797. unsigned long inlen,
  3798. unsigned char *out,
  3799. unsigned long *outlen,
  3800. int padding,
  3801. prng_state *prng,
  3802. int prng_idx,
  3803. int hash_idx,
  3804. unsigned long saltlen,
  3805. rsa_key *key);
  3806. \end{verbatim}
  3807. This will PKCS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PKCS encoded hash will be RSA
  3808. \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets. The \textit{padding} parameter
  3809. must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to produce a v1.5 signature, otherwise, it must be set to \textbf{LTC\_PKCS\_1\_PSS} to produce a
  3810. v2.1 signature.
  3811. \index{LTC\_PKCS\_1\_V1\_5\_NA1}
  3812. As of v1.18.0, the library also supports v1.5 signature generation without ASN.1 encoding the signature which can be indicated by passing
  3813. \textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter. This option has been introduced to provide compatibilty to SSL3.0 implementations
  3814. which implemented this.
  3815. When generating a standard v1.5 signature the \textit{prng}, and \textit{prng\_idx} parameters are ignored.
  3816. When generating a v1.5 signature without ASN.1 decoding additionally the textit{hash\_idx} parameter is ignored.
  3817. \mysection{RSA Signature Verification}
  3818. \index{rsa\_verify\_hash()}
  3819. \begin{verbatim}
  3820. int rsa_verify_hash(const unsigned char *sig,
  3821. unsigned long siglen,
  3822. const unsigned char *msghash,
  3823. unsigned long msghashlen,
  3824. int hash_idx,
  3825. unsigned long saltlen,
  3826. int *stat,
  3827. rsa_key *key);
  3828. \end{verbatim}
  3829. This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PSS decoded
  3830. and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
  3831. If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash}
  3832. value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
  3833. \subsection{RSA Signature Salt Length}
  3834. The v2.1 signature algorithm requires a salt length to be able to properly
  3835. encode resp. decode. To fetch the maximum possible salt length this function
  3836. is provided:
  3837. \index{rsa\_sign\_saltlen\_get\_max()}
  3838. \begin{verbatim}
  3839. int rsa_sign_saltlen_get_max(int hash_idx, rsa_key *key);
  3840. \end{verbatim}
  3841. As stated in the PKCS\#1 RFC3447 "Typical salt lengths in octets are hLen
  3842. (the length of the output of the hash function Hash) and 0".
  3843. This function is provided to be able to use other lengths as well and to make
  3844. sure at runtime that the RSA key can handle the desired salt length.
  3845. \subsection{Extended Verification}
  3846. As of v1.15, the library supports both v1.5 and v2.1 signature verification. The extended signature verification function has the following prototype:
  3847. \index{rsa\_verify\_hash\_ex()}
  3848. \begin{verbatim}
  3849. int rsa_verify_hash_ex(
  3850. const unsigned char *sig,
  3851. unsigned long siglen,
  3852. const unsigned char *hash,
  3853. unsigned long hashlen,
  3854. int padding,
  3855. int hash_idx,
  3856. unsigned long saltlen,
  3857. int *stat,
  3858. rsa_key *key);
  3859. \end{verbatim}
  3860. This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PKCS decoded
  3861. and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
  3862. If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash}
  3863. value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
  3864. The \textit{padding} parameter must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform a v1.5 verification. Otherwise, it must be set to
  3865. \textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification.
  3866. As of v1.18.0, the library also supports v1.5 signature verification without ASN.1 decoding the signature which can be indicated by passing
  3867. \textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter.
  3868. When performing a standard v1.5 verification the \textit{saltlen} parameter is ignored.
  3869. When performing a v1.5 verification without ASN.1 decoding additionally the \textit{hash\_idx} parameter is ignored.
  3870. \mysection{RSA Encryption Example}
  3871. \begin{small}
  3872. \begin{verbatim}
  3873. #include <tomcrypt.h>
  3874. int main(void)
  3875. {
  3876. int err, hash_idx, prng_idx, res;
  3877. unsigned long l1, l2;
  3878. unsigned char pt[16], pt2[16], out[1024];
  3879. rsa_key key;
  3880. /* register prng/hash */
  3881. if (register_prng(&sprng_desc) == -1) {
  3882. printf("Error registering sprng");
  3883. return EXIT_FAILURE;
  3884. }
  3885. /* register a math library (in this case TomsFastMath) */
  3886. ltc_mp = tfm_desc;
  3887. if (register_hash(&sha1_desc) == -1) {
  3888. printf("Error registering sha1");
  3889. return EXIT_FAILURE;
  3890. }
  3891. hash_idx = find_hash("sha1");
  3892. prng_idx = find_prng("sprng");
  3893. /* make an RSA-1024 key */
  3894. if ((err = rsa_make_key(NULL, /* PRNG state */
  3895. prng_idx, /* PRNG idx */
  3896. 1024/8, /* 1024-bit key */
  3897. 65537, /* we like e=65537 */
  3898. &key) /* where to store the key */
  3899. ) != CRYPT_OK) {
  3900. printf("rsa_make_key %s", error_to_string(err));
  3901. return EXIT_FAILURE;
  3902. }
  3903. /* fill in pt[] with a key we want to send ... */
  3904. l1 = sizeof(out);
  3905. if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
  3906. 16, /* data is 16 bytes long */
  3907. out, /* where to store ciphertext */
  3908. &l1, /* length of ciphertext */
  3909. "TestApp", /* our lparam for this program */
  3910. 7, /* lparam is 7 bytes long */
  3911. NULL, /* PRNG state */
  3912. prng_idx, /* prng idx */
  3913. hash_idx, /* hash idx */
  3914. &key) /* our RSA key */
  3915. ) != CRYPT_OK) {
  3916. printf("rsa_encrypt_key %s", error_to_string(err));
  3917. return EXIT_FAILURE;
  3918. }
  3919. /* now let's decrypt the encrypted key */
  3920. l2 = sizeof(pt2);
  3921. if ((err = rsa_decrypt_key(out, /* encrypted data */
  3922. l1, /* length of ciphertext */
  3923. pt2, /* where to put plaintext */
  3924. &l2, /* plaintext length */
  3925. "TestApp", /* lparam for this program */
  3926. 7, /* lparam is 7 bytes long */
  3927. hash_idx, /* hash idx */
  3928. &res, /* validity of data */
  3929. &key) /* our RSA key */
  3930. ) != CRYPT_OK) {
  3931. printf("rsa_decrypt_key %s", error_to_string(err));
  3932. return EXIT_FAILURE;
  3933. }
  3934. /* if all went well pt == pt2, l2 == 16, res == 1 */
  3935. }
  3936. \end{verbatim}
  3937. \end{small}
  3938. \mysection{RSA Key Format}
  3939. The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as
  3940. RSAPublicKey and RSAPrivateKey. Additionally, the OpenSSL key format is supported as well.
  3941. \subsection{RSA Key Export}
  3942. To export a RSA key use the following function.
  3943. \index{rsa\_export()}
  3944. \begin{verbatim}
  3945. int rsa_export(unsigned char *out,
  3946. unsigned long *outlen,
  3947. int type,
  3948. rsa_key *key);
  3949. \end{verbatim}
  3950. This will export the RSA key depending on the value of \textit{type}.
  3951. The RSAPublicKey (PKCS \#1 type) format will be used for the public key,
  3952. indicated by \textbf{PK\_PUBLIC}.
  3953. The RSAPrivateKey (PKCS \#1 type) format will be used for the private key,
  3954. indicated by \textbf{PK\_PRIVATE}.
  3955. As of v1.18.0 this function can also export OpenSSL-compatible formatted public RSA keys.
  3956. By OR'ing \textbf{PK\_STD} and \textbf{PK\_PUBLIC} the public key will be exported
  3957. in the SubjectPublicKeyInfo (X.509 type) format.
  3958. \subsection{RSA Key Import}
  3959. To import a RSA key use one of the following function.
  3960. \subsubsection{Import from standard formats}
  3961. This will import the key stored in \textit{in} of length inlen and import it to \textit{key}.
  3962. These formats are normally distributed in the PEM format, consisting of a label defining the content and base64 encoded DER-serialized data.
  3963. All the import functions expect binary DER data.
  3964. \index{rsa\_import()}
  3965. \begin{verbatim}
  3966. int rsa_import(const unsigned char *in,
  3967. unsigned long inlen,
  3968. rsa_key *key);
  3969. \end{verbatim}
  3970. This function can import both RSAPublicKey and RSAPrivateKey formats.
  3971. As of v1.06 this function can also import OpenSSL DER formatted public RSA keys. They are essentially encapsulated RSAPublicKeys. LibTomCrypt will
  3972. import the key, strip off the additional data and fill in the \textit{rsa\_key} structure.
  3973. \index{rsa\_import\_pkcs8()}
  3974. \begin{verbatim}
  3975. int rsa_import_pkcs8(const unsigned char *in,
  3976. unsigned long inlen,
  3977. const void *passwd,
  3978. unsigned long passwdlen,
  3979. rsa_key *key);
  3980. \end{verbatim}
  3981. This function can import RSA private keys serialized in PKCS\#8 format.
  3982. Where \textit{key} is the RSA key structure (uninitialized), \textit{inlen} bytes of \textit{in} buffer is the DER encoded key,
  3983. and \textit{pwdlen} bytes of \textit{pwd} is optional password/secret (use \textit{pwd = NULL} for keys without password protection).
  3984. For password-protected files all supported encryption algorithms are listed in \ref{fig:pkcs8}.
  3985. \index{rsa\_import\_x509()}
  3986. \begin{verbatim}
  3987. int rsa_import_x509(const unsigned char *in,
  3988. unsigned long inlen,
  3989. rsa_key *key);
  3990. \end{verbatim}
  3991. This function can import the RSA public key from a X.509 certificate.
  3992. \subsubsection{Import from plain big numbers}
  3993. \index{rsa\_set\_key()}
  3994. \begin{verbatim}
  3995. int rsa_set_key(const unsigned char *N,
  3996. unsigned long Nlen,
  3997. const unsigned char *e,
  3998. unsigned long elen,
  3999. const unsigned char *d,
  4000. unsigned long dlen,
  4001. rsa_key *key);
  4002. \end{verbatim}
  4003. This function can import the plain RSA key parameters \textit{N}, \textit{e} and \textit{d}.
  4004. The parameter \textit{d} is optional and only required when importing a private key.
  4005. \index{rsa\_set\_factors()}
  4006. \begin{verbatim}
  4007. int rsa_set_factors(const unsigned char *p,
  4008. unsigned long plen,
  4009. const unsigned char *q,
  4010. unsigned long qlen,
  4011. rsa_key *key);
  4012. \end{verbatim}
  4013. This function can import the plain RSA key factors \textit{p} and \textit{q}.
  4014. \index{rsa\_set\_crt\_params()}
  4015. \begin{verbatim}
  4016. int rsa_set_crt_params(const unsigned char *dP,
  4017. unsigned long dPlen,
  4018. const unsigned char *dQ,
  4019. unsigned long dQlen,
  4020. const unsigned char *qP,
  4021. unsigned long qPlen,
  4022. rsa_key *key);
  4023. \end{verbatim}
  4024. This function can import the plain RSA CRT (chinese remainder theorem) parameters \textit{dP}, \textit{dQ} and \textit{qP}.
  4025. After importing \textit{p}, \textit{q}, \textit{dP}, \textit{dQ} and \textit{qP}
  4026. the library can perfrom the optimized CRT calculations on private key operations.
  4027. \chapter{Diffie-Hellman Key Exchange}
  4028. \mysection{Background}
  4029. Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
  4030. of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
  4031. generates a large sub-group of prime order (for unique values of $x$).
  4032. A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{ }(\mbox{mod }p)$. The term
  4033. ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
  4034. Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange
  4035. a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
  4036. From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
  4037. $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
  4038. $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
  4039. the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
  4040. symmetric cipher.
  4041. It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
  4042. discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
  4043. modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
  4044. $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
  4045. To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
  4046. the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
  4047. smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
  4048. \mysection{Core Functions}
  4049. This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
  4050. provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
  4051. called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first set of routines
  4052. are to make a Diffie-Hellman private key pair:
  4053. \index{dh\_make\_key()}
  4054. \begin{verbatim}
  4055. int dh_set_pg_groupsize(int groupsize, dh_key *key);
  4056. int dh_generate_key(prng_state *prng, int wprng, dh_key *key);
  4057. \end{verbatim}
  4058. The ``groupsize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 1024 bytes which correspond
  4059. to key sizes of 768 to 8192 bits. The smaller the key the faster it is to use however it will be less secure. When
  4060. specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
  4061. above 512 it will return an error. So if you pass ``groupsize == 32'' it will use a 768 bit key but if you pass
  4062. ``groupsize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
  4063. to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
  4064. $p-1$ is equal to $2r$ where $r$ is a large prime. The bases are chosen to generate a group of order $r$ to prevent
  4065. leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
  4066. hard.
  4067. The next two routines are for exporting/importing Diffie-Hellman keys in/from DER encoded ASN.1. This is useful for transport
  4068. over communication mediums.
  4069. \index{dh\_export()} \index{dh\_import()}
  4070. \begin{verbatim}
  4071. int dh_export(unsigned char *out, unsigned long *outlen,
  4072. int type, dh_key *key);
  4073. int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
  4074. \end{verbatim}
  4075. The ASN.1 sequence used to represent a DH key is as following:
  4076. \begin{verbatim}
  4077. DiffieHellmanKey ::= SEQUENCE {
  4078. version Version,
  4079. flags Flags,
  4080. p INTEGER, -- prime
  4081. g INTEGER, -- base/group
  4082. n INTEGER -- either x when private key or y when public key }
  4083. Version ::= INTEGER { v1(0) }
  4084. Flags ::= BIT STRING {
  4085. privateKey (0) -- this BIT is '1' if it's a private key
  4086. -- or '0' if it's a public key
  4087. }
  4088. \end{verbatim}
  4089. These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
  4090. Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails.
  4091. You can free a ``dh\_key'' using:
  4092. \begin{verbatim}
  4093. void dh_free(dh_key *key);
  4094. \end{verbatim}
  4095. After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
  4096. with the other user using:
  4097. \index{dh\_shared\_secret()}
  4098. \begin{verbatim}
  4099. int dh_shared_secret(dh_key *private_key,
  4100. dh_key *public_key,
  4101. unsigned char *out, unsigned long *outlen);
  4102. \end{verbatim}
  4103. Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you. The result goes
  4104. into ``out'' and the length into ``outlen''. If all went correctly the data in ``out'' should be identical for both parties. It is important to
  4105. note that the two keys have to be the same size in order for this to work. There is a function to get the size of a
  4106. key:
  4107. \index{dh\_get\_groupsize()}
  4108. \begin{verbatim}
  4109. int dh_get_groupsize(dh_key *key);
  4110. \end{verbatim}
  4111. This returns the size in bytes of the modulus chosen for that key.
  4112. \mysection{Other Diffie-Hellman Functions}
  4113. To be able to import Diffie-Hellman keys LibTomCrypt provides several API functions.
  4114. \\
  4115. To import the prime and group from binary format:
  4116. \index{dh\_set\_pg()}
  4117. \begin{verbatim}
  4118. int dh_set_pg(const unsigned char *p, unsigned long plen,
  4119. const unsigned char *g, unsigned long glen,
  4120. dh_key *key);
  4121. \end{verbatim}
  4122. This sets the prime \textit{p} of length \textit{plen} and the generator/base \textit{g} of length \textit{glen} in the DH key \textit{key}.
  4123. \\
  4124. To import the prime and group from an ASN.1 encoded DHparam Sequence:
  4125. \index{dh\_set\_pg\_dhparam()}
  4126. \begin{verbatim}
  4127. int dh_set_pg_dhparam(const unsigned char *dhparam, unsigned long dhparamlen, dh_key *key);
  4128. \end{verbatim}
  4129. This sets the parameters in \textit{dhparam} of \textit{dhparamlen} in the DH key \textit{key}.
  4130. \\
  4131. To import a private or public key from binary data:
  4132. \index{dh\_set\_key()}
  4133. \begin{verbatim}
  4134. int dh_set_key(const unsigned char *in, unsigned long inlen, int type, dh_key *key);
  4135. \end{verbatim}
  4136. This will import, depending on \textit{type} which can be either \textit{PK\_PRIVATE} or \textit{PK\_PUBLIC},
  4137. the according part of the DH key \textit{key} from \textit{in} of length \textit{inlen}.
  4138. After import the key will be verified and in case of an error it will be free'd.
  4139. \mysection{Remarks on Usage}
  4140. Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
  4141. example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example. It is suggested that proper packaging be used. For example, if the public key sent is truncated these routines will not detect that.}:
  4142. \newpage
  4143. \begin{small}
  4144. \begin{verbatim}
  4145. int establish_secure_socket(int sock, int mode, unsigned char *key,
  4146. prng_state *prng, int wprng)
  4147. {
  4148. unsigned char buf[4096], buf2[4096];
  4149. unsigned long x, len;
  4150. int res, err, inlen;
  4151. dh_key mykey, theirkey;
  4152. /* make up our private key */
  4153. if ((err = dh_set_pg_groupsize(128, &mykey)) != CRYPT_OK) {
  4154. return err;
  4155. }
  4156. if ((err = dh_generate_key(prng, wprng, &mykey)) != CRYPT_OK) {
  4157. return err;
  4158. }
  4159. /* export our key as public */
  4160. x = sizeof(buf);
  4161. if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
  4162. res = err;
  4163. goto done2;
  4164. }
  4165. if (mode == 0) {
  4166. /* mode 0 so we send first */
  4167. if (send(sock, buf, x, 0) != x) {
  4168. res = CRYPT_ERROR;
  4169. goto done2;
  4170. }
  4171. /* get their key */
  4172. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  4173. res = CRYPT_ERROR;
  4174. goto done2;
  4175. }
  4176. } else {
  4177. /* mode >0 so we send second */
  4178. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  4179. res = CRYPT_ERROR;
  4180. goto done2;
  4181. }
  4182. if (send(sock, buf, x, 0) != x) {
  4183. res = CRYPT_ERROR;
  4184. goto done2;
  4185. }
  4186. }
  4187. if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
  4188. res = err;
  4189. goto done2;
  4190. }
  4191. /* make shared secret */
  4192. x = sizeof(buf);
  4193. if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
  4194. res = err;
  4195. goto done;
  4196. }
  4197. /* hash it */
  4198. len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
  4199. if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
  4200. res = err;
  4201. goto done;
  4202. }
  4203. /* clean up and return */
  4204. res = CRYPT_OK;
  4205. done:
  4206. dh_free(&theirkey);
  4207. done2:
  4208. dh_free(&mykey);
  4209. zeromem(buf, sizeof(buf));
  4210. zeromem(buf2, sizeof(buf2));
  4211. return res;
  4212. }
  4213. \end{verbatim}
  4214. \end{small}
  4215. \subsection{Remarks on The Snippet}
  4216. When the above code snippet is done (assuming all went well) there will be a shared 128-bit key in the ``key'' array
  4217. passed to ``establish\_secure\_socket()''.
  4218. \chapter{Elliptic Curve Cryptography - $GF(p)$}
  4219. \mysection{Introduction}
  4220. The library provides public-key cryptography based on elliptic curves over finite fields \textit{GF(p)}.
  4221. They are all curves over the integers modulo a prime. The curves have the basic equation:
  4222. \begin{equation}
  4223. y^2 = x^3 + a \cdot x + b\mbox{ }(\mbox{mod }p)
  4224. \end{equation}
  4225. \label{ecc-gf-p-equation}
  4226. The built--in curves range in order from $\approx 2^{112}$ points to $\approx 2^{521}$.
  4227. The advantage of ECC is the fact that it requires smaller keys than RSA or DSA to provide equivalent level of security.
  4228. The cryptographic foundation of ECC is the \textit{"elliptic curve discrete logarithm problem"} (ECDLP).
  4229. The library provides a set of core ECC functions as well as functions that are designed to be the Elliptic Curve
  4230. analogy for deriving a shared secret between a pair of keys (also known as \textit{ECDH}) and functions implementing the
  4231. analogy for digital signatures (also known as \textit{ECDSA}).
  4232. \mysection{Supported Curves}
  4233. The following table \ref{fig:builtincurves} shows all built--in curves supported by the library. On top of that one can also use a custom curve
  4234. defined by own parameters (the only limitation is that the curve must be based on equation \ref{ecc-gf-p-equation}).
  4235. \begin{table}[H]
  4236. \begin{center}
  4237. \begin{tabular}{|l|l|l|l|}
  4238. \hline \textbf{Curve Name} & \textbf{Alternative Names} & \textbf{OID} \\
  4239. \hline secp112r1 & & 1.3.132.0.6 \\
  4240. \hline secp112r2 & & 1.3.132.0.7 \\
  4241. \hline secp128r1 & & 1.3.132.0.28 \\
  4242. \hline secp128r2 & & 1.3.132.0.29 \\
  4243. \hline secp160r1 & & 1.3.132.0.8 \\
  4244. \hline secp160r2 & & 1.3.132.0.30 \\
  4245. \hline secp160k1 & & 1.3.132.0.9 \\
  4246. \hline secp192r1 & nistp192, prime192v1, P-192 & 1.2.840.10045.3.1.1 \\
  4247. \hline prime192v2 & & 1.2.840.10045.3.1.2 \\
  4248. \hline prime192v3 & & 1.2.840.10045.3.1.3 \\
  4249. \hline secp192k1 & & 1.3.132.0.31 \\
  4250. \hline secp224r1 & nistp224, P-224 & 1.3.132.0.33 \\
  4251. \hline secp224k1 & & 1.3.132.0.32 \\
  4252. \hline secp256r1 & nistp256, prime256v1, P-256 & 1.2.840.10045.3.1.7 \\
  4253. \hline secp256k1 & & 1.3.132.0.10 \\
  4254. \hline secp384r1 & nistp384, P-384 & 1.3.132.0.34 \\
  4255. \hline secp521r1 & nistp521, P-521 & 1.3.132.0.35 \\
  4256. \hline prime239v1 & & 1.2.840.10045.3.1.4 \\
  4257. \hline prime239v2 & & 1.2.840.10045.3.1.5 \\
  4258. \hline prime239v3 & & 1.2.840.10045.3.1.6 \\
  4259. \hline brainpoolP160r1 & & 1.3.36.3.3.2.8.1.1.1 \\
  4260. \hline brainpoolP192r1 & & 1.3.36.3.3.2.8.1.1.3 \\
  4261. \hline brainpoolP224r1 & & 1.3.36.3.3.2.8.1.1.5 \\
  4262. \hline brainpoolP256r1 & & 1.3.36.3.3.2.8.1.1.7 \\
  4263. \hline brainpoolP320r1 & & 1.3.36.3.3.2.8.1.1.9 \\
  4264. \hline brainpoolP384r1 & & 1.3.36.3.3.2.8.1.1.11 \\
  4265. \hline brainpoolP512r1 & & 1.3.36.3.3.2.8.1.1.13 \\
  4266. \hline brainpoolP160t1 & & 1.3.36.3.3.2.8.1.1.2 \\
  4267. \hline brainpoolP192t1 & & 1.3.36.3.3.2.8.1.1.4 \\
  4268. \hline brainpoolP224t1 & & 1.3.36.3.3.2.8.1.1.6 \\
  4269. \hline brainpoolP256t1 & & 1.3.36.3.3.2.8.1.1.8 \\
  4270. \hline brainpoolP320t1 & & 1.3.36.3.3.2.8.1.1.10 \\
  4271. \hline brainpoolP384t1 & & 1.3.36.3.3.2.8.1.1.12 \\
  4272. \hline brainpoolP512t1 & & 1.3.36.3.3.2.8.1.1.14 \\
  4273. \hline
  4274. \end{tabular}
  4275. \caption{Built--In Elliptic Curves over GF(p)}
  4276. \end{center}
  4277. \label{fig:builtincurves}
  4278. \end{table}
  4279. \mysection{Key Generation}
  4280. There is a key structure called \textit{ecc\_key} which is used by all ECC functions.
  4281. To generate a new private \textit{ecc\_key} there are basically two ways provided.
  4282. The first is via using one of the built--in curves and the second way is via using a user--supplied curve.
  4283. \subsection{Using Built--in Curves}
  4284. First a function is provided to look up curve name or OID of built--in curves:
  4285. \index{ecc\_find\_curve()}
  4286. \begin{verbatim}
  4287. int ecc_find_curve(const char *name_or_oid,
  4288. const ltc_ecc_curve **cu);
  4289. \end{verbatim}
  4290. The \textit{name\_or\_oid} argument will search by name, alternative name or OID as mentioned in Table \ref{fig:builtincurves}.
  4291. \index{ecc\_set\_curve()}
  4292. \begin{verbatim}
  4293. int ecc_set_curve(const ltc_ecc_curve *cu,
  4294. ecc_key *key);
  4295. \end{verbatim}
  4296. The function \textit{ecc\_set\_curve} initializes the \textit{key} structure with the curve parameters passed via \textit{cu}.
  4297. \index{ecc\_generate\_key()}
  4298. \begin{verbatim}
  4299. int ecc_generate_key(prng_state *prng,
  4300. int wprng,
  4301. ecc_key *key);
  4302. \end{verbatim}
  4303. The function \textit{ecc\_generate\_key} does the actual key generation. The function will free any internally
  4304. allocated resources if there is an error.
  4305. Example of creating an ECC key:
  4306. \begin{small}
  4307. \begin{verbatim}
  4308. prng_state prng;
  4309. int wprng;
  4310. ecc_key key;
  4311. const ltc_ecc_curve* cu;
  4312. if (register_all_prngs() != CRYPT_OK) return -1;
  4313. wprng = find_prng("yarrow");
  4314. if (rng_make_prng(128, wprng, &prng, NULL) != CRYPT_OK) return -1;
  4315. if (ecc_find_curve("nistp256", &cu) != CRYPT_OK) return -1;
  4316. if (ecc_set_curve(cu, &key) != CRYPT_OK) return -1;
  4317. if (ecc_generate_key(&prng, wprng, &key) != CRYPT_OK) return -1;
  4318. \end{verbatim}
  4319. \end{small}
  4320. \subsection{Extended Key Generation}
  4321. The library uses the following structure to describe an elliptic curve.
  4322. This structure can also be used for defining a custom curve based on user--supplied parameters.
  4323. \index{ltc\_ecc\_curve}
  4324. \begin{verbatim}
  4325. /** Structure defines a NIST GF(p) curve */
  4326. typedef struct {
  4327. /** The prime that defines the field the curve is in (encoded in hex) */
  4328. const char *prime;
  4329. /** The fields A param (hex) */
  4330. const char *A;
  4331. /** The fields B param (hex) */
  4332. const char *B;
  4333. /** The order of the curve (hex) */
  4334. const char *order;
  4335. /** The x co-ordinate of the base point on the curve (hex) */
  4336. const char *Gx;
  4337. /** The y co-ordinate of the base point on the curve (hex) */
  4338. const char *Gy;
  4339. /** The co-factor */
  4340. unsigned long cofactor;
  4341. /** The OID */
  4342. const char *OID;
  4343. } ltc_ecc_curve;
  4344. \end{verbatim}
  4345. The curve must be of the form $y^2 = x^3 + a \cdot x + b$, and all of the \textit{const char*} parameters have to be encoded in hexadecimal format.
  4346. Advanced example of creating an ECC key:
  4347. \begin{small}
  4348. \begin{verbatim}
  4349. prng_state prng;
  4350. int wprng;
  4351. ecc_key key;
  4352. const ltc_ecc_curve custom_curve = {
  4353. "FFFFFFFFFFFFFFFFFFFFFFFFFDE7", /* prime */
  4354. "0000000000000000000000000000", /* A */
  4355. "0000000000000000000000000003", /* B */
  4356. "0100000000000001ECEA551AD837E9", /* order */
  4357. "0000000000000000000000000001", /* Gx */
  4358. "0000000000000000000000000002", /* Gy */
  4359. 1, /* cofactor */
  4360. "2.23.43.1.4.8" /* OID */
  4361. };
  4362. if (register_all_prngs() != CRYPT_OK) return -1;
  4363. wprng = find_prng("yarrow");
  4364. if (rng_make_prng(128, wprng, &prng, NULL) != CRYPT_OK) return -1;
  4365. if (ecc_set_curve(&custom_curve, &key) != CRYPT_OK) return -1;
  4366. if (ecc_generate_key(&prng, wprng, &key) != CRYPT_OK) return -1;
  4367. \end{verbatim}
  4368. \end{small}
  4369. \subsection{Legacy Key Generation}
  4370. To generate a new key in a way compatible with libtomcrypt 1.18 and earlier the following function is provided:
  4371. \index{ecc\_make\_key()}
  4372. \begin{verbatim}
  4373. int ecc_make_key(prng_state *prng,
  4374. int wprng,
  4375. int keysize,
  4376. ecc_key *key);
  4377. \end{verbatim}
  4378. Where \textit{keysize} maps to the specific curve as follows:
  4379. \begin{table}[H]
  4380. \begin{center}
  4381. \begin{tabular}{|c|l|}
  4382. \hline \textbf{keysize} & \textbf{curve name} \\
  4383. \hline 14 & secp112r1 \\
  4384. \hline 16 & secp128r1 \\
  4385. \hline 20 & secp160r1 \\
  4386. \hline 24 & secp192r1, nistp192, prime192v1, P-192 \\
  4387. \hline 28 & secp224r1, nistp224, P-224 \\
  4388. \hline 32 & secp256r1, nistp256, prime256v1, P-256 \\
  4389. \hline 48 & secp384r1, nistp384, P-384 \\
  4390. \hline 66 & secp521r1, nistp521, P-521 \\
  4391. \hline
  4392. \end{tabular}
  4393. \caption{Mapping of ecc\_make\_key() keysizes to curves}
  4394. \end{center}
  4395. \label{fig:legacy-curve-names}
  4396. \end{table}
  4397. For backwards compatibility the function \textit{ecc\_make\_key\_ex} is provided, which is just a wrapper
  4398. around \textit{ecc\_set\_curve} and \textit{ecc\_generate\_key}.
  4399. \index{ecc\_make\_key\_ex()}
  4400. \begin{verbatim}
  4401. int ecc_make_key_ex(prng_state *prng,
  4402. int wprng,
  4403. ecc_key *key,
  4404. const ltc_ecc_curve *cu);
  4405. \end{verbatim}
  4406. This function generates a random ECC key over the curve specified by the parameters in \textit{cu}.
  4407. It is also possible to use a combination of \textit{ecc\_set\_curve\_by\_size} (similar to \textit{ecc\_set\_curve}) and \textit{ecc\_generate\_key}.
  4408. \index{ecc\_set\_curve\_by\_size}
  4409. \begin{verbatim}
  4410. int ecc_set_curve_by_size( int keysize,
  4411. ecc_key *key);
  4412. \end{verbatim}
  4413. The \textit{keysize} maps to the specific curve according to table \ref{fig:legacy-curve-names}.
  4414. \subsection{Key Free}
  4415. To free the memory allocated by one of \textit{ecc\_generate\_key()}, \textit{ecc\_make\_key()}, \textit{ecc\_make\_key\_ex()}, \textit{ecc\_import()},
  4416. \textit{ecc\_import\_openssl()}, \textit{ecc\_import\_x509()}, \textit{ecc\_import\_pkcs8()}, \textit{ecc\_ansi\_x963\_import()},
  4417. \textit{ecc\_ansi\_x963\_import\_ex()}, or \textit{ecc\_set\_key()} the following function is provided:
  4418. \index{ecc\_free()}
  4419. \begin{verbatim}
  4420. void ecc_free(ecc_key *key);
  4421. \end{verbatim}
  4422. \subsection{Key Helper Functions}
  4423. To get the curve OID as a NUL--terminated string the following function is provided:
  4424. \index{ecc\_get\_oid\_str()}
  4425. \begin{verbatim}
  4426. int ecc_get_oid_str( char *out,
  4427. unsigned long *outlen,
  4428. const ecc_key *key);
  4429. \end{verbatim}
  4430. Where \textit{key} is the key for which we want to extract its OID,
  4431. \textit{out} is where the ASCII output is placed, and the \textit{outlen}
  4432. parameter is updated to hold the output OID size (including NUL byte).
  4433. \mysection{Key Export and Import}
  4434. \subsection{Export Raw Key}
  4435. To export the raw value of the key (private or public) the following function is provided:
  4436. \index{ecc\_get\_key()}
  4437. \begin{verbatim}
  4438. int ecc_get_key(unsigned char *out,
  4439. unsigned long *outlen,
  4440. int type,
  4441. const ecc_key *key);
  4442. \end{verbatim}
  4443. Where \textit{key} is the key to export, \textit{out} is where the output is placed,
  4444. the \textit{outlen} parameter is updated to hold the output, and the \textit{type} indicates
  4445. what kind of export should be done (see table \ref{fig:ecc-get-key-type}).
  4446. \begin{table}[H]
  4447. \begin{center}
  4448. \begin{tabular}{|l|l|l|}
  4449. \hline \textbf{type} & \textbf{description} & \textbf{NIST-256 example} \\
  4450. \hline \textit{PK\_PRIVATE} & export the private key & output: 32 bytes \\
  4451. \hline \textit{PK\_PUBLIC} & export the public key (long form) & output: 65 bytes \\
  4452. \hline \textit{PK\_PUBLIC \textbar PK\_COMPRESSED} & export the public key (short form) & output: 33 bytes \\
  4453. \hline
  4454. \end{tabular}
  4455. \caption{Possible types of ecc\_get\_key()}
  4456. \label{fig:ecc-get-key-type}
  4457. \end{center}
  4458. \end{table}
  4459. Please note that the output data does not contain the information about the elliptic curve of the exported key
  4460. (one can just assume the size of the curve which is unambiguous). The information about the curve has to be kept
  4461. separately to be able to re-use the key after importing.
  4462. \subsection{Import Raw Key}
  4463. To import the raw value of the key (private or public) the following function is provided:
  4464. \index{ecc\_set\_key()}
  4465. \begin{verbatim}
  4466. int ecc_set_key(const unsigned char *in,
  4467. unsigned long inlen,
  4468. int type,
  4469. ecc_key *key);
  4470. \end{verbatim}
  4471. Where \textit{key} is the key structure with properly initialized curve parameters (see below),
  4472. \textit{inlen} bytes of \textit{in} buffer is imported, and the \textit{type} indicates
  4473. the key type -- either \textit{PK\_PUBLIC} or \textit{PK\_PRIVATE}.
  4474. For the actual import you need to know the curve of the imported key and load the key like this:
  4475. \begin{small}
  4476. \begin{verbatim}
  4477. ecc_key key;
  4478. const ltc_ecc_curve* cu;
  4479. if (ecc_find_curve("nistp256", &cu) != CRYPT_OK) return -1;
  4480. if (ecc_set_curve(cu, &key) != CRYPT_OK) return -1;
  4481. if (ecc_set_key(keybuf, keylen, PK_PRIVATE, &key) != CRYPT_OK) return -1;
  4482. \end{verbatim}
  4483. \end{small}
  4484. \subsection{Key Export -- OpenSSL compatible}
  4485. To export the key (private or public) in DER format compatible with OpenSSL the following function is provided:
  4486. \index{ecc\_export\_openssl()}
  4487. \begin{verbatim}
  4488. int ecc_export_openssl(unsigned char *out,
  4489. unsigned long *outlen,
  4490. int type,
  4491. const ecc_key *key);
  4492. \end{verbatim}
  4493. Where \textit{key} is the key to export, \textit{out} is where the output is placed,
  4494. the \textit{outlen} parameter is updated to hold the output, and the \textit{type} indicates
  4495. what kind of export should be done (see table \ref{fig:ecc-export-openssl-type}).
  4496. \begin{table}[H]
  4497. \begin{center}
  4498. \begin{tabular}{|l|l|l|}
  4499. \hline \textbf{type} & \textbf{note} \\
  4500. \hline \textit{PK\_PRIVATE} & the output contains all curve constants \\
  4501. \hline \textit{PK\_PRIVATE \textbar PK\_CURVEOID} & the output contains only curve OID \\
  4502. \hline \textit{PK\_PUBLIC} & all curve constants \\
  4503. \hline \textit{PK\_PUBLIC \textbar PK\_COMPRESSED} & all curve constants + using point compression \\
  4504. \hline \textit{PK\_PUBLIC \textbar PK\_CURVEOID} & only curve OID \\
  4505. \hline \textit{PK\_PUBLIC \textbar PK\_COMPRESSED \textbar PK\_CURVEOID} & only curve OID + using point compression \\
  4506. \hline
  4507. \end{tabular}
  4508. \caption{Possible types of ecc\_export\_openssl()}
  4509. \label{fig:ecc-export-openssl-type}
  4510. \end{center}
  4511. \end{table}
  4512. \subsection{Key Import -- OpenSSL compatible}
  4513. To import the key (private or public) in DER format compatible with OpenSSL the following function is provided:
  4514. \index{ecc\_import\_openssl()}
  4515. \begin{verbatim}
  4516. int ecc_import_openssl(const unsigned char *in,
  4517. unsigned long inlen,
  4518. ecc_key *key);
  4519. \end{verbatim}
  4520. Where \textit{key} is the ECC key structure (uninitialized), \textit{inlen} bytes of \textit{in} buffer is the DER encoded key.
  4521. \subsection{Public Key Import -- X.509 certificates}
  4522. To import the public key from a X.509 certificate (DER encoded) the following function is provided:
  4523. \index{ecc\_import\_x509()}
  4524. \begin{verbatim}
  4525. int ecc_import_x509(const unsigned char *in,
  4526. unsigned long inlen,
  4527. ecc_key *key);
  4528. \end{verbatim}
  4529. Where \textit{key} is the ECC key structure (uninitialized), \textit{inlen} bytes of \textit{in} buffer is the DER encoded certificate.
  4530. \subsection{Private Key Import -- PKCS\#8}
  4531. To import the private key (optionally password protected/encrypted) in PKCS\#8 (DER encoded) format the following function is provided:
  4532. \index{ecc\_import\_pkcs8()}
  4533. \begin{verbatim}
  4534. int ecc_import_pkcs8(const unsigned char *in,
  4535. unsigned long inlen,
  4536. const void *pwd,
  4537. unsigned long pwdlen,
  4538. ecc_key *key);
  4539. \end{verbatim}
  4540. Where \textit{key} is the ECC key structure (uninitialized), \textit{inlen} bytes of \textit{in} buffer is the DER encoded key,
  4541. and \textit{pwdlen} bytes of \textit{pwd} is optional password/secret (use \textit{pwd = NULL} for keys without password protection).
  4542. For password-protected files all supported encryption algorithms are listed in \ref{fig:pkcs8}.
  4543. \subsection{Key Export -- LTC proprietary (deprecated)}
  4544. LTC proprietary format for ECC public and private keys is defined as follows:
  4545. \begin{small}
  4546. \begin{verbatim}
  4547. ECCPublicKey ::= SEQUENCE {
  4548. flags BIT STRING(0), -- public/private flag (always zero),
  4549. keySize INTEGER, -- Curve size (in bits) divided by eight
  4550. -- and rounded down, e.g. 521 => 65
  4551. pubkey.x INTEGER, -- The X co-ordinate of the public key point
  4552. pubkey.y INTEGER, -- The Y co-ordinate of the public key point
  4553. }
  4554. ECCPrivateKey ::= SEQUENCE {
  4555. flags BIT STRING(1), -- public/private flag (always one),
  4556. keySize INTEGER, -- Curve size (in bits) divided by eight
  4557. -- and rounded down, e.g. 521 => 65
  4558. pubkey.x INTEGER, -- The X co-ordinate of the public key point
  4559. pubkey.y INTEGER, -- The Y co-ordinate of the public key point
  4560. secret.k INTEGER, -- The secret key scalar
  4561. }
  4562. \end{verbatim}
  4563. \end{small}
  4564. The first flags bit denotes whether the key is public (zero) or private (one).
  4565. To export an ECC key using the LibTomCrypt format the following function is provided:
  4566. \index{ecc\_export()}
  4567. \begin{verbatim}
  4568. int ecc_export(unsigned char *out,
  4569. unsigned long *outlen,
  4570. int type,
  4571. ecc_key *key);
  4572. \end{verbatim}
  4573. This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.
  4574. \subsection{Key Import -- LTC proprietary (deprecated)}
  4575. The following function imports a LibTomCrypt format ECC key:
  4576. \index{ecc\_import()}
  4577. \begin{verbatim}
  4578. int ecc_import(const unsigned char *in,
  4579. unsigned long inlen,
  4580. ecc_key *key);
  4581. \end{verbatim}
  4582. This will import the ECC key from \textit{in}, and store it in the ecc\_key structure pointed to by \textit{key}. If the operation fails it will free
  4583. any allocated memory automatically.
  4584. The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
  4585. \index{ecc\_import\_ex()}
  4586. \begin{verbatim}
  4587. int ecc_import_ex(const unsigned char *in,
  4588. unsigned long inlen,
  4589. ecc_key *key,
  4590. const ltc_ecc_curve *dp);
  4591. \end{verbatim}
  4592. This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets. The key is stored in
  4593. the ECC structure pointed to by \textit{key}. The curve is specified by the parameters pointed to by \textit{dp}. The function will free
  4594. all internally allocated memory upon error.
  4595. \subsection{ANSI X9.63 Export (deprecated)}
  4596. The following function exports an ECC public key in the ANSI X9.63 format:
  4597. \index{ecc\_ansi\_x963\_export()}
  4598. \begin{verbatim}
  4599. int ecc_ansi_x963_export( ecc_key *key,
  4600. unsigned char *out,
  4601. unsigned long *outlen);
  4602. \end{verbatim}
  4603. The ECC key pointed to by \textit{key} is exported in public fashion to the array pointed to by \textit{out}. The ANSI X9.63 format used is from
  4604. section 4.3.6 of the standard. It does not allow for the export of private keys.
  4605. \subsection{ANSI X9.63 Import (deprecated)}
  4606. The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
  4607. \index{ecc\_ansi\_x963\_import()}
  4608. \begin{verbatim}
  4609. int ecc_ansi_x963_import(const unsigned char *in,
  4610. unsigned long inlen,
  4611. ecc_key *key);
  4612. \end{verbatim}
  4613. This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The imported key is stored in the ECC key pointed to by
  4614. \textit{key}. The function will free any allocated memory upon error.
  4615. The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
  4616. \index{ecc\_ansi\_x963\_import\_ex()}
  4617. \begin{verbatim}
  4618. int ecc_ansi_x963_import_ex(const unsigned char *in,
  4619. unsigned long inlen,
  4620. ecc_key *key,
  4621. ltc_ecc_curve *dp);
  4622. \end{verbatim}
  4623. This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.
  4624. The imported key is stored in the ECC key pointed to by \textit{key}. The function will free any allocated memory upon error.
  4625. \mysection{Signatures (ECDSA)}
  4626. There are also functions to sign and verify messages. They use the ANSI X9.62 ECDSA algorithm to generate and verify signatures in the
  4627. ANSI X9.62 format.
  4628. \subsection{Signature Generation}
  4629. To sign a message digest (hash) use the following function:
  4630. \index{ecc\_sign\_hash()}
  4631. \begin{verbatim}
  4632. int ecc_sign_hash(const unsigned char *in,
  4633. unsigned long inlen,
  4634. unsigned char *out,
  4635. unsigned long *outlen,
  4636. prng_state *prng,
  4637. int wprng,
  4638. ecc_key *key);
  4639. \end{verbatim}
  4640. This function will ECDSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The signature
  4641. will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets. The function requires a properly seeded PRNG, and
  4642. the ECC \textit{key} provided must be a private key.
  4643. \index{ecc\_sign\_hash\_rfc7518()}
  4644. \begin{verbatim}
  4645. int ecc_sign_hash_rfc7518(const unsigned char *in,
  4646. unsigned long inlen,
  4647. unsigned char *out,
  4648. unsigned long *outlen,
  4649. prng_state *prng,
  4650. int wprng,
  4651. ecc_key *key);
  4652. \end{verbatim}
  4653. This function creates the same ECDSA signature as \textit{ecc\_sign\_hash} only the output format is different.
  4654. The format follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}, sometimes it is also called plain signature.
  4655. \index{ecc\_sign\_hash\_ex()}
  4656. \begin{verbatim}
  4657. int ecc_sign_hash_ex(const unsigned char *in,
  4658. unsigned long inlen,
  4659. unsigned char *out,
  4660. unsigned long *outlen,
  4661. prng_state *prng,
  4662. int wprng,
  4663. ecc_signature_type sigformat,
  4664. int *recid,
  4665. ecc_key *key);
  4666. \end{verbatim}
  4667. This function is an extended version of the ECDSA signature in \textit{ecc\_sign\_hash}, but with a choice of output formats
  4668. and an optional output of the recovery ID for use with \textit{ecc\_recover\_key}.
  4669. \subsection{Signature Verification}
  4670. \index{ecc\_verify\_hash()}
  4671. \begin{verbatim}
  4672. int ecc_verify_hash(const unsigned char *sig,
  4673. unsigned long siglen,
  4674. const unsigned char *hash,
  4675. unsigned long hashlen,
  4676. int *stat,
  4677. ecc_key *key);
  4678. \end{verbatim}
  4679. This function will verify the ECDSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest
  4680. pointed to by the array \textit{hash} of length \textit{hashlen}. It will store a non--zero value in \textit{stat} if the signature is valid. Note:
  4681. the function will not return an error if the signature is invalid. It will return an error, if the actual signature payload is an invalid format.
  4682. The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
  4683. The function \textit{ecc\_verify\_hash} implements signature format according to X9.62 ECDSA, and the output is compliant for GF(p) curves.
  4684. \index{ecc\_verify\_hash\_rfc7518()}
  4685. \begin{verbatim}
  4686. int ecc_verify_hash_rfc7518(const unsigned char *sig,
  4687. unsigned long siglen,
  4688. const unsigned char *hash,
  4689. unsigned long hashlen,
  4690. int *stat,
  4691. ecc_key *key);
  4692. \end{verbatim}
  4693. This function validate the ECDSA signature as \textit{ecc\_verify\_hash} only the signature input format
  4694. follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}.
  4695. \index{ecc\_verify\_hash\_ex()}
  4696. \begin{verbatim}
  4697. int ecc_verify_hash_ex(const unsigned char *sig,
  4698. unsigned long siglen,
  4699. const unsigned char *hash,
  4700. unsigned long hashlen,
  4701. ecc_signature_type sigformat,
  4702. int *stat,
  4703. ecc_key *key);
  4704. \end{verbatim}
  4705. This function validates an ECDSA signature as \textit{ecc\_verify\_hash} but with a choice of signature formats.
  4706. {\bf BEWARE:} With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems. The math
  4707. will still work, and in effect the signature will still work. With ECC keys the strength of the signature is limited
  4708. by the size of the hash, or the size of the key, whichever is smaller. For example, if you sign with SHA256 and a
  4709. P--192 key, you have in effect 96--bits of security. The library will not warn you if you make this mistake, so it
  4710. is important to check yourself before using the signatures.
  4711. \subsection{Public Key Recovery}
  4712. \index{ecc\_recover\_key()}
  4713. \begin{verbatim}
  4714. int ecc_recover_key(const unsigned char *sig,
  4715. unsigned long siglen,
  4716. const unsigned char *hash,
  4717. unsigned long hashlen,
  4718. int recid,
  4719. ecc_signature_type sigformat,
  4720. ecc_key *key);
  4721. \end{verbatim}
  4722. This function will recover (a) public key from the ECDSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, the message digest
  4723. pointed to by the array \textit{hash} of length \textit{hashlen}, and the recovery id \textit{recid}. It will store the recovered
  4724. key into \textit{key} and return CRYPT\_OK if recovery succeeds, or an error if recovery fails.
  4725. This is for compatibility with the (v,r,s) signatures used in Ethereum, where public keys are not explicitly shared,
  4726. only the parity of the public key. For curves like secp256k1, recid will take values of 0 or 1, corresponding to the
  4727. parity of the public key's y coordinate. For curves like secp112r2, with a cofactor of 4, values 0..7 are possible,
  4728. with the low bit corresponding to the parity and the higher bits specifying the public key's x coordinate's multiple
  4729. of the curve's order.
  4730. If the signature format contains the recovery id (currently only \textit{LTC\_ECCSIG\_ETH27}), \textit{recid} can be -1
  4731. which signals that the recovery id from the signature blob should be used. This means an application does not need to
  4732. extract the recovery id from such a signature in order to use this function.
  4733. The function \textit{ecc\_recover\_key} implements multiple signature formats, and the output is compliant for GF(p) curves.
  4734. \subsection{Signature Formats}
  4735. The following signature formats are suported:
  4736. \begin{figure}[hpbt]
  4737. \index{Signature Formats}
  4738. \begin{small}
  4739. \begin{center}
  4740. \begin{tabular}{|l|l|}
  4741. \hline \textbf{sigformat} & \textbf{description} \\
  4742. \hline LTC\_ECCSIG\_ANSIX962 & ASN.1 encoded, ANSI X9.62 \\
  4743. \hline LTC\_ECCSIG\_RFC7518 & raw R, S values as defined in RFC7518 \\
  4744. \hline LTC\_ECCSIG\_ETH27 & raw R, S, V values (V has 27 added) \\
  4745. \hline LTC\_ECCSIG\_RFC5656 & SSH+ECDSA format as defined in RFC5656 \\
  4746. \hline
  4747. \end{tabular}
  4748. \end{center}
  4749. \end{small}
  4750. \caption{Signature Formats}
  4751. \label{fig:sigformat}
  4752. \end{figure}
  4753. The \textit{LTC\_ECCSIG\_ETH27} format is based on the Ethereum Yellow Paper, see \url{https://github.com/ethereum/yellowpaper}
  4754. (Appendix F). However, convention allows the use of v=0,1 as equivalent to v=27,28 and both are accepted by
  4755. \textit{ecc\_recover\_key}.
  4756. \mysection{Shared Secret (ECDH)}
  4757. To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
  4758. \index{ecc\_shared\_secret()}
  4759. \begin{verbatim}
  4760. int ecc_shared_secret( ecc_key *private_key,
  4761. ecc_key *public_key,
  4762. unsigned char *out,
  4763. unsigned long *outlen);
  4764. \end{verbatim}
  4765. The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.
  4766. Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECDH.
  4767. \mysection{Encrypt and Decrypt (ECDH--based)}
  4768. ECDH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext. It is not strictly ANSI X9.63 compliant
  4769. but it is very similar. It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage. The following function
  4770. encrypts a short string (no longer than the message digest) using this technique:
  4771. \subsection{Encryption}
  4772. \index{ecc\_encrypt\_key()}
  4773. \begin{verbatim}
  4774. int ecc_encrypt_key(const unsigned char *in,
  4775. unsigned long inlen,
  4776. unsigned char *out,
  4777. unsigned long *outlen,
  4778. prng_state *prng,
  4779. int wprng,
  4780. int hash,
  4781. ecc_key *key);
  4782. \end{verbatim}
  4783. As the name implies this function can be used to encrypt a (symmetric) key, and is not intended for encrypting long messages directly. It will encrypt the
  4784. plaintext in the array pointed to by \textit{in} of length \textit{inlen} octets. It uses the public ECC key pointed to by \textit{key}, and
  4785. hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext. The ciphertext is stored in
  4786. the output buffer pointed to by \textit{out} of length \textit{outlen} octets.
  4787. The data is encrypted through the public ECC \textit{key} such that only the holder of the private key can decrypt the payload.
  4788. % This sounds to me like multi-party encryption, but that's not true, isn't it?
  4789. To have multiple recipients multiple calls to this function for each public ECC key are required.
  4790. \subsection{Decryption}
  4791. \index{ecc\_decrypt\_key()}
  4792. \begin{verbatim}
  4793. int ecc_decrypt_key(const unsigned char *in,
  4794. unsigned long inlen,
  4795. unsigned char *out,
  4796. unsigned long *outlen,
  4797. ecc_key *key);
  4798. \end{verbatim}
  4799. This function will decrypt an encrypted payload. The \textit{key} provided must be the private key corresponding to the public key
  4800. used during encryption. If the wrong key is provided the function will not specifically return an error code. It is important
  4801. to use some form of challenge response in that case (e.g. compute a MAC of a known string).
  4802. \subsection{Encryption Format}
  4803. The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
  4804. \begin{verbatim}
  4805. ECCEncrypt ::= SEQUENCE {
  4806. hashID OBJECT IDENTIFIER, -- OID of hash used
  4807. pubkey OCTET STRING , -- Encapsulated ECCPublicKey
  4808. skey OCTET STRING -- xor of plaintext and
  4809. --"hash of shared secret"
  4810. }
  4811. \end{verbatim}
  4812. \chapter{Elliptic Curve Cryptography - $Montgomery/Twisted Edwards$}
  4813. \mysection{Introduction}
  4814. The library provides functionality for \textit{Curve25519}-based \textit{X25519} Diffie-Hellman shared secrets
  4815. and \textit{EdDSA} a.k.a \textit{Ed25519} signature schemes.
  4816. The implementation is based on the \textit{tweetnacl}\footnote{\url{https://tweetnacl.cr.yp.to/}} reference implementation
  4817. as provided by Daniel J. Bernstein et.al. and only slightly modified to better fit in the library.
  4818. Both algorithms share the key structure called \textit{curve25519\_key} which is used by all Curve25519 functions.
  4819. As Curve25519 and Ed25519 are based on the same elliptic curve, but use different mathematics, the keys are not
  4820. compatible to each other.
  4821. It is possible to convert a Curve-Key to an Ed-Key and vice-versa, but this is not provided (yet).
  4822. \mysection{Curve25519-based Diffie-Hellman Key Exchange - X25519}
  4823. The library provides the Diffie-Hellman Key Exchange algorithm \textit{X25519} for curve25519 as specified in RFC 7748.
  4824. \subsection{X25519 Key Operations}
  4825. The \textit{X25519} algorithm API provides the following set of functions to create, import and export keys.
  4826. \index{x25519\_make\_key}
  4827. \begin{verbatim}
  4828. int x25519_make_key(prng_state *prng, int wprng, curve25519_key *key);
  4829. \end{verbatim}
  4830. To generate a fresh X25529 key, one can use \textit{x25519\_make\_key} which will create a private\&public key-pair.
  4831. \index{x25519\_import}
  4832. \begin{verbatim}
  4833. int x25519_import(const unsigned char *in, unsigned long inlen, curve25519_key *key);
  4834. \end{verbatim}
  4835. The \textit{x25519\_import} function can be used to import a public key in DER-encoded \textit{SubjectPublicKeyInfo} format.
  4836. \index{x25519\_import\_raw}
  4837. \begin{verbatim}
  4838. int x25519_import_raw(const unsigned char *in, unsigned long inlen, int which, curve25519_key *key);
  4839. \end{verbatim}
  4840. To import a public or private key in raw format, one can use the function \textit{x25519\_import\_raw}.
  4841. \index{x25519\_import\_x509}
  4842. \begin{verbatim}
  4843. int x25519_import_x509(const unsigned char *in, unsigned long inlen, curve25519_key *key);
  4844. \end{verbatim}
  4845. To import a public key from a DER-encoded \textit{X.509} certificate, one can use the function \textit{x25519\_import\_x509}.
  4846. \index{x25519\_import\_pkcs8}
  4847. \begin{verbatim}
  4848. int x25519_import_pkcs8(const unsigned char *in, unsigned long inlen,
  4849. const void *pwd, unsigned long pwdlen,
  4850. curve25519_key *key);
  4851. \end{verbatim}
  4852. To import a private key in the \textit{OneAsymmetricKey} a.k.a \textit{PKCS \#8} format, either plain or PBES encrypted,
  4853. one can use the function \textit{x25519\_import\_pkcs8}.
  4854. \index{x25519\_export}
  4855. \begin{verbatim}
  4856. int x25519_export( unsigned char *out, unsigned long *outlen,
  4857. int which,
  4858. const curve25519_key *key);
  4859. \end{verbatim}
  4860. To export a key, the function \textit{x25519\_export} is provided.
  4861. It has support for the following output formats:
  4862. \begin{figure}[H]
  4863. \begin{center}
  4864. \begin{tabular}{|c|c|}
  4865. \hline \textbf{which} & \textbf{output format} \\
  4866. \hline PK\_PRIVATE & Raw \\
  4867. \hline PK\_PRIVATE \& PK\_STD & PKCS \#8 \\
  4868. \hline PK\_PUBLIC & Raw \\
  4869. \hline PK\_PUBLIC \& PK\_STD & SubjectPublicKeyInfo \\
  4870. \hline
  4871. \end{tabular}
  4872. \end{center}
  4873. \caption{Possible x25519\_export() output formats}
  4874. \end{figure}
  4875. \subsection{X25519 Cryptographic Operations}
  4876. To construct a Diffie-Hellman shared secret with a private and a public X25519 key, use the following function:
  4877. \index{x25519\_shared\_secret}
  4878. \begin{verbatim}
  4879. int x25519_shared_secret(const curve25519_key *private_key,
  4880. const curve25519_key *public_key,
  4881. unsigned char *out, unsigned long *outlen);
  4882. \end{verbatim}
  4883. This will construct the shared secret between the private- and the public-key and store the result in \textit{out} of length \textit{outlen}.
  4884. \mysection{Curve25519-based EdDSA Signature Scheme - Ed25519}
  4885. The library provides the EdDSA algorithm for the edwards25519 curve in the PureEdDSA variant as specified in RFC 8032.
  4886. \subsection{EdDSA Key Operations}
  4887. The \textit{Ed25519} algorithm API provides the following set of functions to create, import and export keys.
  4888. \index{ed25519\_make\_key}
  4889. \begin{verbatim}
  4890. int ed25519_make_key(prng_state *prng, int wprng, curve25519_key *key);
  4891. \end{verbatim}
  4892. To generate a fresh Ed25529 key, one can use \textit{ed25519\_make\_key} which will create a private\&public key-pair.
  4893. \index{ed25519\_import}
  4894. \begin{verbatim}
  4895. int ed25519_import(const unsigned char *in, unsigned long inlen, curve25519_key *key);
  4896. \end{verbatim}
  4897. The \textit{ed25519\_import} function can be used to import a public key in DER-encoded \textit{SubjectPublicKeyInfo} format.
  4898. \index{ed25519\_import\_raw}
  4899. \begin{verbatim}
  4900. int ed25519_import_raw(const unsigned char *in, unsigned long inlen, int which, curve25519_key *key);
  4901. \end{verbatim}
  4902. To import a public or private key in raw format, one can use the function \textit{ed25519\_import\_raw}.
  4903. \index{ed25519\_import\_x509}
  4904. \begin{verbatim}
  4905. int ed25519_import_x509(const unsigned char *in, unsigned long inlen, curve25519_key *key);
  4906. \end{verbatim}
  4907. To import a public key from a DER-encoded \textit{X.509} certificate, one can use the function \textit{ed25519\_import\_x509}.
  4908. \index{ed25519\_import\_pkcs8}
  4909. \begin{verbatim}
  4910. int ed25519_import_pkcs8(const unsigned char *in, unsigned long inlen,
  4911. const void *pwd, unsigned long pwdlen,
  4912. curve25519_key *key);
  4913. \end{verbatim}
  4914. To import a private key in the \textit{OneAsymmetricKey} a.k.a \textit{PKCS \#8} format, either plain or PBES encrypted,
  4915. one can use the function \textit{ed25519\_import\_pkcs8}.
  4916. \index{ed25519\_export}
  4917. \begin{verbatim}
  4918. int ed25519_export( unsigned char *out, unsigned long *outlen,
  4919. int which,
  4920. const curve25519_key *key);
  4921. \end{verbatim}
  4922. To export a key, the function \textit{ed25519\_export} is provided.
  4923. It has support for the following output formats:
  4924. \begin{figure}[H]
  4925. \begin{center}
  4926. \begin{tabular}{|c|c|}
  4927. \hline \textbf{which} & \textbf{output format} \\
  4928. \hline PK\_PRIVATE & Raw \\
  4929. \hline PK\_PRIVATE \& PK\_STD & PKCS \#8 \\
  4930. \hline PK\_PUBLIC & Raw \\
  4931. \hline PK\_PUBLIC \& PK\_STD & SubjectPublicKeyInfo \\
  4932. \hline
  4933. \end{tabular}
  4934. \end{center}
  4935. \caption{Possible ed25519\_export() output formats}
  4936. \end{figure}
  4937. \subsection{EdDSA Cryptographic Operations}
  4938. To sign and/or verify a message use the following functions:
  4939. \index{ed25519\_sign}
  4940. \index{ed25519ctx\_sign}
  4941. \index{ed25519ph\_sign}
  4942. \begin{verbatim}
  4943. int ed25519_sign(const unsigned char *msg, unsigned long msglen,
  4944. unsigned char *sig, unsigned long *siglen,
  4945. const curve25519_key *private_key);
  4946. int ed25519ctx_sign(const unsigned char *msg, unsigned long msglen,
  4947. unsigned char *sig, unsigned long *siglen,
  4948. const unsigned char *ctx, unsigned long ctxlen,
  4949. const curve25519_key *private_key);
  4950. int ed25519ph_sign(const unsigned char *msg, unsigned long msglen,
  4951. unsigned char *sig, unsigned long *siglen,
  4952. const unsigned char *ctx, unsigned long ctxlen,
  4953. const curve25519_key *private_key);
  4954. \end{verbatim}
  4955. These functions will EdDSA sign the message stored in the array pointed to by \textit{msg} of length \textit{msglen} octets. The signature
  4956. will be stored in the array pointed to by \textit{sig} of length \textit{siglen} octets. The \texttt{ctx} and \texttt{ph} variants also
  4957. allow passing a context \textit{ctx} of length \textit{ctxlen} octets. This context is allowed to be max. 255 octets long.
  4958. \index{ed25519\_verify}
  4959. \index{ed25519ctx\_verify}
  4960. \index{ed25519ph\_verify}
  4961. \begin{verbatim}
  4962. int ed25519_verify(const unsigned char *msg, unsigned long msglen,
  4963. const unsigned char *sig, unsigned long siglen,
  4964. int *stat,
  4965. const curve25519_key *public_key);
  4966. int ed25519ctx_verify(const unsigned char *msg, unsigned long msglen,
  4967. const unsigned char *sig, unsigned long siglen,
  4968. const unsigned char *ctx, unsigned long ctxlen,
  4969. int *stat,
  4970. const curve25519_key *public_key);
  4971. int ed25519ph_verify(const unsigned char *msg, unsigned long msglen,
  4972. const unsigned char *sig, unsigned long siglen,
  4973. const unsigned char *ctx, unsigned long ctxlen,
  4974. int *stat,
  4975. const curve25519_key *public_key);
  4976. \end{verbatim}
  4977. These functions will verify the EdDSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message
  4978. pointed to by the array \textit{msg} of length \textit{msglen}. It will store a non--zero value in \textit{stat} if the signature is valid. Note:
  4979. the function will not return an error if the signature is invalid. It will only return an error if the actual signature payload is an invalid format.
  4980. \chapter{Digital Signature Algorithm}
  4981. \mysection{Introduction}
  4982. The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
  4983. reduce the bandwidth of the signatures. For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.
  4984. With DSA, you need a group of order at least 160--bits. By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature
  4985. would require only at least 40 bytes.
  4986. \mysection{Key Format}
  4987. Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
  4988. now so that others can interoperate with this library.
  4989. \begin{verbatim}
  4990. DSAPublicKey ::= SEQUENCE {
  4991. publicFlags BIT STRING(0), -- must be 0
  4992. g INTEGER , -- base generator
  4993. -- check that g^q mod p == 1
  4994. -- and that 1 < g < p - 1
  4995. p INTEGER , -- prime modulus
  4996. q INTEGER , -- order of sub-group
  4997. -- (must be prime)
  4998. y INTEGER , -- public key, specifically,
  4999. -- g^x mod p,
  5000. -- check that y^q mod p == 1
  5001. -- and that 1 < y < p - 1
  5002. }
  5003. DSAPrivateKey ::= SEQUENCE {
  5004. publicFlags BIT STRING(1), -- must be 1
  5005. g INTEGER , -- base generator
  5006. -- check that g^q mod p == 1
  5007. -- and that 1 < g < p - 1
  5008. p INTEGER , -- prime modulus
  5009. q INTEGER , -- order of sub-group
  5010. -- (must be prime)
  5011. y INTEGER , -- public key, specifically,
  5012. -- g^x mod p,
  5013. -- check that y^q mod p == 1
  5014. -- and that 1 < y < p - 1
  5015. x INTEGER -- private key
  5016. }
  5017. \end{verbatim}
  5018. The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys. This makes the structure uniquely decodable,
  5019. and easy to work with.
  5020. \mysection{Key Generation}
  5021. To make a DSA key you must call the following function
  5022. \begin{verbatim}
  5023. int dsa_make_key(prng_state *prng,
  5024. int wprng,
  5025. int group_size,
  5026. int modulus_size,
  5027. dsa_key *key);
  5028. \end{verbatim}
  5029. The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor. \textit{group\_size} and
  5030. \textit{modulus\_size} control the difficulty of forging a signature. Both parameters are in bytes. The larger the
  5031. \textit{group\_size} the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
  5032. $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
  5033. \begin{figure}[H]
  5034. \begin{center}
  5035. \begin{tabular}{|c|c|c|}
  5036. \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
  5037. \hline 80 & 20 & 128 \\
  5038. \hline 120 & 30 & 256 \\
  5039. \hline 140 & 35 & 384 \\
  5040. \hline 160 & 40 & 512 \\
  5041. \hline
  5042. \end{tabular}
  5043. \end{center}
  5044. \caption{DSA Key Sizes}
  5045. \end{figure}
  5046. When you are finished with a DSA key you can call the following function to free the memory used.
  5047. \index{dsa\_free()}
  5048. \begin{verbatim}
  5049. void dsa_free(dsa_key *key);
  5050. \end{verbatim}
  5051. \mysection{Key Verification}
  5052. Each DSA key is composed of the following variables.
  5053. \begin{enumerate}
  5054. \item $q$ a small prime of magnitude $256^{group\_size}$.
  5055. \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
  5056. \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
  5057. value. For this library they start at $h = 2$ and step until $g$ is not $1$.
  5058. \item $x$ a random secret (the secret key) in the range $1 < x < q$
  5059. \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
  5060. \end{enumerate}
  5061. A DSA key is considered valid if it passes all of the following tests.
  5062. \begin{enumerate}
  5063. \item $q$ must be prime.
  5064. \item $p$ must be prime.
  5065. \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
  5066. \item $g$ must be less than $p$.
  5067. \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
  5068. \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  5069. \item $1 < y < p - 1$
  5070. \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  5071. \end{enumerate}
  5072. Tests one and two ensure that the values will at least form a field which is required for the signatures to
  5073. function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
  5074. forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
  5075. ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
  5076. is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
  5077. that $y$ belongs to a multiplicative sub-group of order $q$.
  5078. The following function will perform these tests.
  5079. \index{dsa\_verify\_key()}
  5080. \begin{verbatim}
  5081. int dsa_verify_key(dsa_key *key, int *stat);
  5082. \end{verbatim}
  5083. This will test \textit{key} and store the result in \textit{stat}. If the result is $stat = 0$ the DSA key failed one of the tests
  5084. and should not be used at all. If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).
  5085. \mysection{Signatures}
  5086. \subsection{Signature Generation}
  5087. To generate a DSA signature call the following function:
  5088. \index{dsa\_sign\_hash()}
  5089. \begin{verbatim}
  5090. int dsa_sign_hash(const unsigned char *in,
  5091. unsigned long inlen,
  5092. unsigned char *out,
  5093. unsigned long *outlen,
  5094. prng_state *prng,
  5095. int wprng,
  5096. dsa_key *key);
  5097. \end{verbatim}
  5098. Which will sign the data in \textit{in} of length \textit{inlen} bytes. The signature is stored in \textit{out} and the size
  5099. of the signature in \textit{outlen}. If the signature is longer than the size you initially specify in \textit{outlen} nothing
  5100. is stored and the function returns an error code. The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.
  5101. \subsection{Signature Verification}
  5102. To verify a hash created with that function use the following function:
  5103. \index{dsa\_verify\_hash()}
  5104. \begin{verbatim}
  5105. int dsa_verify_hash(const unsigned char *sig,
  5106. unsigned long siglen,
  5107. const unsigned char *hash,
  5108. unsigned long inlen,
  5109. int *stat,
  5110. dsa_key *key);
  5111. \end{verbatim}
  5112. Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.
  5113. It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.
  5114. \mysection{DSA Encrypt and Decrypt}
  5115. As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads. It works similar to the ECC encryption where
  5116. a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext. The format used is functional port of
  5117. the ECC encryption format to the DSA algorithm.
  5118. \subsection{DSA Encryption}
  5119. This function will encrypt a small payload with a recipients public DSA key.
  5120. \index{dsa\_encrypt\_key()}
  5121. \begin{verbatim}
  5122. int dsa_encrypt_key(const unsigned char *in,
  5123. unsigned long inlen,
  5124. unsigned char *out,
  5125. unsigned long *outlen,
  5126. prng_state *prng,
  5127. int wprng,
  5128. int hash,
  5129. dsa_key *key);
  5130. \end{verbatim}
  5131. This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}. The
  5132. length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer. The DSA \textit{key} can be
  5133. a public key.
  5134. \subsection{DSA Decryption}
  5135. \index{dsa\_decrypt\_key()}
  5136. \begin{verbatim}
  5137. int dsa_decrypt_key(const unsigned char *in,
  5138. unsigned long inlen,
  5139. unsigned char *out,
  5140. unsigned long *outlen,
  5141. dsa_key *key);
  5142. \end{verbatim}
  5143. This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
  5144. The DSA \textit{key} must be a private key.
  5145. \mysection{DSA Key Import and Export}
  5146. \subsection{DSA Key Export}
  5147. To export a DSA key so that it can be transported use the following function:
  5148. \index{dsa\_export()}
  5149. \begin{verbatim}
  5150. int dsa_export(unsigned char *out,
  5151. unsigned long *outlen,
  5152. int type,
  5153. dsa_key *key);
  5154. \end{verbatim}
  5155. This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
  5156. initialized to the maximum buffer size). The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
  5157. depending on whether you want to export a private or public copy of the DSA key.
  5158. \subsection{DSA Key Import}
  5159. To import an exported DSA key use the following function
  5160. :
  5161. \index{dsa\_import()}
  5162. \begin{verbatim}
  5163. int dsa_import(const unsigned char *in,
  5164. unsigned long inlen,
  5165. dsa_key *key);
  5166. \end{verbatim}
  5167. This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}. If the process fails the function
  5168. will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
  5169. \mysection{Other DSA Functions}
  5170. The following functions allow to create a DSA key in 2 steps:
  5171. \begin{enumerate}
  5172. \item Load or generate \textit{p}, \textit{q}, \textit{g} part of the key via \textit{dsa\_set\_pqg()}, \textit{dsa\_set\_pqg\_dsaparam()} or \textit{dsa\_generate\_pqg()}.
  5173. \item Load or generate the actual DSA key -- private (\textit{x} and \textit{y} values) or public (\textit{y} value).
  5174. \end{enumerate}
  5175. \index{dsa\_set\_pqg()}
  5176. \begin{verbatim}
  5177. int dsa_set_pqg(const unsigned char *p, unsigned long plen,
  5178. const unsigned char *q, unsigned long qlen,
  5179. const unsigned char *g, unsigned long glen,
  5180. dsa_key *key);
  5181. \end{verbatim}
  5182. This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary
  5183. representation of \textit{p} (with length of \textit{plen}), \textit{q} (with length of \textit{qlen}) and \textit{g} (with length of \textit{glen}).
  5184. A simple DSA key validity check (without primality testing) is performed at the end of this function.
  5185. \index{dsa\_set\_pqg\_dsaparam()}
  5186. \begin{verbatim}
  5187. int dsa_set_pqg_dsaparam(const unsigned char *dsaparam,
  5188. unsigned long dsaparamlen,
  5189. dsa_key *key);
  5190. \end{verbatim}
  5191. This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary representation
  5192. of DSA parameters stored as a binary data in a buffer \textit{dsaparam} (with length of \textit{dsaparamlen}). A simple DSA key validity
  5193. check (without primality testing) is performed at the end of this function. The \textit{dsaparam} can be generated via:
  5194. \begin{verbatim}
  5195. openssl dsaparam 2048 -outform DER -out dsaparam.der
  5196. \end{verbatim}
  5197. \index{dsa\_generate\_pqg()}
  5198. \begin{verbatim}
  5199. int dsa_generate_pqg(prng_state *prng,
  5200. int wprng,
  5201. int group_size,
  5202. int modulus_size,
  5203. dsa_key *key);
  5204. \end{verbatim}
  5205. This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure with newly generated random values.
  5206. As for the parameters they are the same as by \textit{dsa\_make\_key}.
  5207. \index{dsa\_set\_key()}
  5208. \begin{verbatim}
  5209. int dsa_set_key(const unsigned char *in,
  5210. unsigned long inlen,
  5211. int type,
  5212. dsa_key *key);
  5213. \end{verbatim}
  5214. This function can be used for setting the actual DSA key. If \textit{type} is \textit{PK\_PRIVATE} then the buffer \textit{in}
  5215. (with length of \textit{inlen}) contains a binary representation of \textit{x} part of the key (the public part \textit{y} is computed).
  5216. If \textit{type} is \textit{PK\_PUBLIC} then the buffer \textit{in} contains a binary representation of \textit{y} part of the key.
  5217. \index{dsa\_generate\_key()}
  5218. \begin{verbatim}
  5219. int dsa_generate_key(prng_state *prng,
  5220. int wprng,
  5221. dsa_key *key);
  5222. \end{verbatim}
  5223. This function generates a private DSA key containing both \textit{x} and \textit{y} parts.
  5224. \chapter{Standards Support}
  5225. \mysection{ASN.1 Formats}
  5226. LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
  5227. are all provided with three basic functions with \textit{similar} prototypes. One function has been dedicated to calculate the length in octets of a given
  5228. format, and two functions have been dedicated to encoding and decoding the format.
  5229. On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types. They are provided
  5230. in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure. It is defined as the following:
  5231. \index{ltc\_asn1\_list structure}
  5232. \begin{verbatim}
  5233. typedef struct {
  5234. ltc_asn1_type type;
  5235. void *data;
  5236. unsigned long size;
  5237. int used;
  5238. int optional;
  5239. ltc_asn1_class klass;
  5240. ltc_asn1_pc pc;
  5241. ulong64 tag;
  5242. struct ltc_asn1_list_ *prev, *next,
  5243. *child, *parent;
  5244. } ltc_asn1_list;
  5245. \end{verbatim}
  5246. \index{LTC\_SET\_ASN1 macro}
  5247. The \textit{type} field is one of the following ASN.1 field definitions. The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the
  5248. \textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type). The \textit{used} field is primarily for the CHOICE decoder
  5249. and reflects if the particular member of a list was the decoded data type. To help build the lists in an orderly fashion the macro
  5250. \textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.
  5251. It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size). An example usage would be:
  5252. \begin{small}
  5253. \begin{verbatim}
  5254. ...
  5255. ltc_asn1_list sequence[3];
  5256. unsigned long three=3;
  5257. LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING, "hello", 5);
  5258. LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three, 1);
  5259. LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL, NULL, 0);
  5260. \end{verbatim}
  5261. \end{small}
  5262. The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
  5263. \begin{small}
  5264. \begin{verbatim}
  5265. ...
  5266. ltc_asn1_list sequence[3];
  5267. unsigned long three=3;
  5268. int x=0;
  5269. LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING, "hello", 5);
  5270. LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three, 1);
  5271. LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL, NULL, 0);
  5272. \end{verbatim}
  5273. \end{small}
  5274. \begin{figure}[h]
  5275. \begin{center}
  5276. \begin{small}
  5277. \begin{tabular}{|l|l|}
  5278. \hline \textbf{Definition} & \textbf{ASN.1 Type} \\
  5279. \hline LTC\_ASN1\_EOL & End of a ASN.1 list structure. \\
  5280. \hline LTC\_ASN1\_BOOLEAN & BOOLEAN type \\
  5281. \hline LTC\_ASN1\_INTEGER & INTEGER (uses mp\_int) \\
  5282. \hline LTC\_ASN1\_SHORT\_INTEGER & INTEGER (32--bit using unsigned long) \\
  5283. \hline LTC\_ASN1\_BIT\_STRING & BIT STRING (one bit per char) \\
  5284. \hline LTC\_ASN1\_OCTET\_STRING & OCTET STRING (one octet per char) \\
  5285. \hline LTC\_ASN1\_NULL & NULL \\
  5286. \hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER \\
  5287. \hline LTC\_ASN1\_IA5\_STRING & IA5 STRING (one octet per char) \\
  5288. \hline LTC\_ASN1\_PRINTABLE\_STRING & PRINTABLE STRING (one octet per char) \\
  5289. \hline LTC\_ASN1\_UTF8\_STRING & UTF8 STRING (one wchar\_t per char) \\
  5290. \hline LTC\_ASN1\_UTCTIME & UTCTIME (see ltc\_utctime structure) \\
  5291. \hline LTC\_ASN1\_CHOICE & CHOICE \\
  5292. \hline LTC\_ASN1\_SEQUENCE & SEQUENCE (and SEQUENCE OF) \\
  5293. \hline LTC\_ASN1\_SET & SET \\
  5294. \hline LTC\_ASN1\_SETOF & SET OF \\
  5295. \hline LTC\_ASN1\_RAW\_BIT\_STRING & BIT STRING (one octet per char) \\
  5296. \hline LTC\_ASN1\_TELETEX\_STRING & TELETEX STRING (one octet per char) \\
  5297. \hline LTC\_ASN1\_GENERALIZEDTIME & GeneralizedTime (see ltc\_generalizedtime structure) \\
  5298. \hline LTC\_ASN1\_CUSTOM\_TYPE & A custom type (see LTC\_SET\_ASN1\_CUSTOM\_XXX macros) \\
  5299. \hline
  5300. \end{tabular}
  5301. \caption{List of ASN.1 Supported Types}
  5302. \index{ltc\_asn1\_type}
  5303. \end{small}
  5304. \end{center}
  5305. \end{figure}
  5306. \index{LTC\_ASN1\_CUSTOM\_TYPE}
  5307. \index{LTC\_SET\_ASN1\_CUSTOM\_CONSTRUCTED macro}
  5308. \index{LTC\_SET\_ASN1\_CUSTOM\_PRIMITIVE macro}
  5309. To be able to encode and decode all other valid ASN.1 Identifiers, such as Context-Specific types the macros
  5310. \textit{LTC\_SET\_ASN1\_CUSTOM\_CONSTRUCTED(list, index, Class, Tag, Data)} resp.
  5311. \textit{LTC\_SET\_ASN1\_CUSTOM\_PRIMITIVE(list, index, Class, Tag, Type, Data, Size)} have been provided.
  5312. They will assign to the \textit{index}th position in the \textit{list} the Identifier-triplet (Class, CONSTRUCTED resp. PRIMITIVE, Tag).
  5313. An example usage would be:
  5314. \begin{small}
  5315. \begin{verbatim}
  5316. ...
  5317. ltc_asn1_list sequence[4], custom[1];
  5318. unsigned long three=3;
  5319. unsigned char buf[128];
  5320. LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING, "hello", 5);
  5321. LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three, 1);
  5322. LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL, NULL, 0);
  5323. LTC_SET_ASN1_CUSTOM_PRIMITIVE(sequence, 3, LTC_ASN1_CL_CONTEXT_SPECIFIC, 23, \
  5324. LTC_ASN1_OCTET_STRING, buf, sizeof(buf));
  5325. LTC_SET_ASN1_CUSTOM_CONSTRUCTED(custom, 0, LTC_ASN1_CL_CONTEXT_SPECIFIC, 0, sequence);
  5326. \end{verbatim}
  5327. \end{small}
  5328. This would allow (un)pack'ing the given \textit{sequence} from/in the context-specific tag \textit{[0]}.
  5329. \subsection{SEQUENCE Type}
  5330. The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
  5331. \subsubsection{SEQUENCE Encoding}
  5332. To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
  5333. with the following function.
  5334. \index{der\_encode\_sequence()}\index{LTC\_ASN1\_EOL}
  5335. \begin{verbatim}
  5336. int der_encode_sequence(ltc_asn1_list *list,
  5337. unsigned long inlen,
  5338. unsigned char *out,
  5339. unsigned long *outlen);
  5340. \end{verbatim}
  5341. This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it. The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}. The
  5342. function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
  5343. The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
  5344. verbatim to the dependent encoder. The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions. In these cases
  5345. the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
  5346. \subsubsection{SEQUENCE Decoding}
  5347. \index{der\_decode\_sequence()}
  5348. \index{der\_decode\_sequence\_strict()}
  5349. Decoding a SEQUENCE is similar to encoding. You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size
  5350. (in certain cases). For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
  5351. units of the respective type has been loaded.
  5352. \begin{verbatim}
  5353. int der_decode_sequence(const unsigned char *in,
  5354. unsigned long inlen,
  5355. ltc_asn1_list *list,
  5356. unsigned long outlen);
  5357. int der_decode_sequence_strict(const unsigned char *in,
  5358. unsigned long inlen,
  5359. ltc_asn1_list *list,
  5360. unsigned long outlen);
  5361. \end{verbatim}
  5362. This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets. The function will stop (gracefully) when it runs out of items to decode.
  5363. It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occurred.
  5364. The regular variant will return \textbf{CRYPT\_INPUT\_TOO\_LONG} in cases where there was more data to be decoded given through \textit{inlen} than the ASN.1 length-tag specified.
  5365. The strict variant \textit{der\_decode\_sequence\_strict()} returns an error in this case.
  5366. For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
  5367. \begin{enumerate}
  5368. \item (RAW) BIT STRING
  5369. \item OCTET STRING
  5370. \item OBJECT IDENTIFIER
  5371. \item IA5 STRING
  5372. \item PRINTABLE STRING
  5373. \item TELETEX STRING
  5374. \item UTF8 STRING
  5375. \end{enumerate}
  5376. \subsubsection{SEQUENCE Length}
  5377. The length of a SEQUENCE can be determined with the following function.
  5378. \index{der\_length\_sequence()}
  5379. \begin{verbatim}
  5380. int der_length_sequence(ltc_asn1_list *list,
  5381. unsigned long inlen,
  5382. unsigned long *outlen);
  5383. \end{verbatim}
  5384. This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.
  5385. \subsubsection{SEQUENCE Multiple Argument Lists}\index{LTC\_ASN1\_EOL}
  5386. For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
  5387. \index{der\_encode\_sequence\_multi()}
  5388. \index{der\_decode\_sequence\_multi()}
  5389. \begin{verbatim}
  5390. int der_encode_sequence_multi(unsigned char *out,
  5391. unsigned long *outlen, ...);
  5392. int der_decode_sequence_multi(const unsigned char *in,
  5393. unsigned long inlen, ...);
  5394. \end{verbatim}
  5395. These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
  5396. The list of items are specified as a triple of the form \textit{(type, size, data)} where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
  5397. and \textit{data} is \textbf{void} pointer. The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
  5398. It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function. Constants such as \textit{1} without
  5399. a cast or prototype are of type \textbf{int} by default. Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.
  5400. \begin{small}
  5401. \begin{verbatim}
  5402. unsigned char buf[MAXBUFSIZE];
  5403. unsigned long buflen;
  5404. int err;
  5405. buflen = sizeof(buf);
  5406. if ((err =
  5407. der_encode_sequence_multi(buf, &buflen,
  5408. LTC_ASN1_IA5_STRING, 5UL, "Hello",
  5409. LTC_ASN1_IA5_STRING, 7UL, " World!",
  5410. LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
  5411. // error handling
  5412. }
  5413. \end{verbatim}
  5414. \end{small}
  5415. This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively. Note the usage of the \textbf{UL} modifier
  5416. on the size parameters. This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
  5417. \subsection{SET and SET OF}
  5418. \index{SET} \index{SET OF}
  5419. SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code. However, they are different, and they should
  5420. be carefully noted. The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of
  5421. a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.
  5422. \subsubsection{SET Encoding}
  5423. SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use. They are encoded with the following function:
  5424. \index{der\_encode\_set()}
  5425. \begin{verbatim}
  5426. int der_encode_set(ltc_asn1_list *list,
  5427. unsigned long inlen,
  5428. unsigned char *out,
  5429. unsigned long *outlen);
  5430. \end{verbatim}
  5431. This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.
  5432. The function will make a copy of the list provided, and sort it by the TAG. Objects with identical TAGs are additionally sorted on their original placement in the
  5433. array (to make the process deterministic).
  5434. This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
  5435. \subsubsection{SET Decoding}
  5436. The SET type can be decoded with the following function.
  5437. \index{der\_decode\_set()}
  5438. \begin{verbatim}
  5439. int der_decode_set(const unsigned char *in,
  5440. unsigned long inlen,
  5441. ltc_asn1_list *list,
  5442. unsigned long outlen);
  5443. \end{verbatim}
  5444. This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.
  5445. It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.
  5446. \subsubsection{SET Length}
  5447. The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.
  5448. \subsubsection{SET OF Encoding}
  5449. A \textit{SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object. They are
  5450. used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
  5451. use. They are encoded with the following function.
  5452. \index{der\_encode\_setof()}
  5453. \begin{verbatim}
  5454. int der_encode_setof(ltc_asn1_list *list,
  5455. unsigned long inlen,
  5456. unsigned char *out,
  5457. unsigned long *outlen);
  5458. \end{verbatim}
  5459. This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.
  5460. The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer. This
  5461. means you need at least enough memory to keep an additional copy of the output on the heap.
  5462. \subsubsection{SET OF Decoding}
  5463. Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().
  5464. \subsubsection{SET OF Length}
  5465. Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.
  5466. \subsection{ASN.1 INTEGER}
  5467. To encode or decode INTEGER data types use the following functions.
  5468. \index{der\_encode\_integer()}\index{der\_decode\_integer()}\index{der\_length\_integer()}
  5469. \begin{verbatim}
  5470. int der_encode_integer( void *num,
  5471. unsigned char *out,
  5472. unsigned long *outlen);
  5473. int der_decode_integer(const unsigned char *in,
  5474. unsigned long inlen,
  5475. void *num);
  5476. int der_length_integer( void *num,
  5477. unsigned long *len);
  5478. \end{verbatim}
  5479. These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER. To encode smaller values without allocating
  5480. a bignum to store the value, the \textit{short} INTEGER functions were made available.
  5481. \index{der\_encode\_short\_integer()}\index{der\_decode\_short\_integer()}\index{der\_length\_short\_integer()}
  5482. \begin{verbatim}
  5483. int der_encode_short_integer(unsigned long num,
  5484. unsigned char *out,
  5485. unsigned long *outlen);
  5486. int der_decode_short_integer(const unsigned char *in,
  5487. unsigned long inlen,
  5488. unsigned long *num);
  5489. int der_length_short_integer(unsigned long num,
  5490. unsigned long *outlen);
  5491. \end{verbatim}
  5492. These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits). For values in the range $0 \dots 2^{32} - 1$ the integer
  5493. and short integer functions can encode and decode each others outputs.
  5494. \subsection{ASN.1 BIT STRING}
  5495. \index{der\_encode\_bit\_string()}\index{der\_decode\_bit\_string()}\index{der\_length\_bit\_string()}
  5496. \begin{verbatim}
  5497. int der_encode_bit_string(const unsigned char *in,
  5498. unsigned long inlen,
  5499. unsigned char *out,
  5500. unsigned long *outlen);
  5501. int der_decode_bit_string(const unsigned char *in,
  5502. unsigned long inlen,
  5503. unsigned char *out,
  5504. unsigned long *outlen);
  5505. int der_length_bit_string(unsigned long nbits,
  5506. unsigned long *outlen);
  5507. \end{verbatim}
  5508. These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf{char} per bit. A non--zero value will be interpreted
  5509. as a one bit, and a zero value a zero bit.
  5510. \subsection{ASN.1 RAW BIT STRING}
  5511. \index{der\_encode\_raw\_bit\_string()}\index{der\_decode\_raw\_bit\_string()}
  5512. \begin{verbatim}
  5513. int der_encode_raw_bit_string(const unsigned char *in,
  5514. unsigned long inlen,
  5515. unsigned char *out,
  5516. unsigned long *outlen);
  5517. int der_decode_raw_bit_string(const unsigned char *in,
  5518. unsigned long inlen,
  5519. unsigned char *out,
  5520. unsigned long *outlen);
  5521. \end{verbatim}
  5522. These will encode or decode a BIT STRING data type.
  5523. The bits are passed in (or read out) using one \textbf{unsigned char} per 8 bit.
  5524. This function differs from the normal BIT STRING, as it can be used to directly
  5525. process raw binary data and store it to resp. read it from an ASN.1 BIT STRING
  5526. data type.
  5527. The length function is the same as for the normal BIT STRING \textit{der\_length\_bit\_string()}.
  5528. \subsection{ASN.1 OCTET STRING}
  5529. \index{der\_encode\_octet\_string()}\index{der\_decode\_octet\_string()}\index{der\_length\_octet\_string()}
  5530. \begin{verbatim}
  5531. int der_encode_octet_string(const unsigned char *in,
  5532. unsigned long inlen,
  5533. unsigned char *out,
  5534. unsigned long *outlen);
  5535. int der_decode_octet_string(const unsigned char *in,
  5536. unsigned long inlen,
  5537. unsigned char *out,
  5538. unsigned long *outlen);
  5539. int der_length_octet_string(unsigned long noctets,
  5540. unsigned long *outlen);
  5541. \end{verbatim}
  5542. These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf{unsigned char} each.
  5543. \subsection{ASN.1 OBJECT IDENTIFIER}
  5544. \index{der\_encode\_object\_identifier()}\index{der\_decode\_object\_identifier()}\index{der\_length\_object\_identifier()}
  5545. \begin{verbatim}
  5546. int der_encode_object_identifier(unsigned long *words,
  5547. unsigned long nwords,
  5548. unsigned char *out,
  5549. unsigned long *outlen);
  5550. int der_decode_object_identifier(const unsigned char *in,
  5551. unsigned long inlen,
  5552. unsigned long *words,
  5553. unsigned long *outlen);
  5554. int der_length_object_identifier(unsigned long *words,
  5555. unsigned long nwords,
  5556. unsigned long *outlen);
  5557. \end{verbatim}
  5558. These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
  5559. $0 \ldots 2^{32} - 1$.
  5560. \subsection{ASN.1 IA5 STRING}
  5561. \index{der\_encode\_ia5\_string()}\index{der\_decode\_ia5\_string()}\index{der\_length\_ia5\_string()}
  5562. \begin{verbatim}
  5563. int der_encode_ia5_string(const unsigned char *in,
  5564. unsigned long inlen,
  5565. unsigned char *out,
  5566. unsigned long *outlen);
  5567. int der_decode_ia5_string(const unsigned char *in,
  5568. unsigned long inlen,
  5569. unsigned char *out,
  5570. unsigned long *outlen);
  5571. int der_length_ia5_string(const unsigned char *octets,
  5572. unsigned long noctets,
  5573. unsigned long *outlen);
  5574. \end{verbatim}
  5575. These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
  5576. to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
  5577. say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
  5578. that the build platform honours the run--time platforms character conventions.
  5579. \subsection{ASN.1 TELETEX STRING}
  5580. \index{der\_decode\_teletex\_string()}\index{der\_length\_teletex\_string()}
  5581. \begin{verbatim}
  5582. int der_decode_teletex_string(const unsigned char *in,
  5583. unsigned long inlen,
  5584. unsigned char *out,
  5585. unsigned long *outlen);
  5586. int der_length_teletex_string(const unsigned char *octets,
  5587. unsigned long noctets,
  5588. unsigned long *outlen);
  5589. \end{verbatim}
  5590. These will decode a TELETEX STRING.
  5591. The characters are read in individual \textbf{char} elements.
  5592. The internal structure is similar to that of the IA5 STRING implementation, to
  5593. be able to provide a stable conversion independent of the build-- and run--time
  5594. platform.
  5595. \subsection{ASN.1 PRINTABLE STRING}
  5596. \index{der\_encode\_printable\_string()}\index{der\_decode\_printable\_string()}\index{der\_length\_printable\_string()}
  5597. \begin{verbatim}
  5598. int der_encode_printable_string(const unsigned char *in,
  5599. unsigned long inlen,
  5600. unsigned char *out,
  5601. unsigned long *outlen);
  5602. int der_decode_printable_string(const unsigned char *in,
  5603. unsigned long inlen,
  5604. unsigned char *out,
  5605. unsigned long *outlen);
  5606. int der_length_printable_string(const unsigned char *octets,
  5607. unsigned long noctets,
  5608. unsigned long *outlen);
  5609. \end{verbatim}
  5610. These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
  5611. to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
  5612. say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
  5613. that the build platform honours the run-time platforms character conventions.
  5614. \subsection{ASN.1 UTF8 STRING}
  5615. \index{der\_encode\_utf8\_string()}\index{der\_decode\_utf8\_string()}\index{der\_length\_utf8\_string()}
  5616. \begin{verbatim}
  5617. int der_encode_utf8_string(const wchar_t *in,
  5618. unsigned long inlen,
  5619. unsigned char *out,
  5620. unsigned long *outlen);
  5621. int der_decode_utf8_string(const unsigned char *in,
  5622. unsigned long inlen,
  5623. wchar_t *out,
  5624. unsigned long *outlen);
  5625. int der_length_utf8_string(const wchar_t *octets,
  5626. unsigned long noctets,
  5627. unsigned long *outlen);
  5628. \end{verbatim}
  5629. These will encode or decode an UTF8 STRING. The characters are read or stored in individual \textbf{wchar\_t} elements. These function performs no internal
  5630. mapping and treat the characters as literals.
  5631. These functions use the \textbf{wchar\_t} type which is not universally available. In those cases, the library will typedef it to \textbf{unsigned long}. If you
  5632. intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.
  5633. \subsection{ASN.1 UTCTIME}
  5634. The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
  5635. \index{ltc\_utctime structure}
  5636. \begin{verbatim}
  5637. typedef struct {
  5638. unsigned YY, /* year 00--99 */
  5639. MM, /* month 01--12 */
  5640. DD, /* day 01--31 */
  5641. hh, /* hour 00--23 */
  5642. mm, /* minute 00--59 */
  5643. ss, /* second 00--59 */
  5644. off_dir, /* timezone offset direction 0 == +, 1 == - */
  5645. off_hh, /* timezone offset hours */
  5646. off_mm; /* timezone offset minutes */
  5647. } ltc_utctime;
  5648. \end{verbatim}
  5649. The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
  5650. will be subtracted. For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of
  5651. \textit{2005, June 20th, 22:04:00} with a time offset of +05h00.
  5652. \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
  5653. \begin{verbatim}
  5654. int der_encode_utctime( ltc_utctime *utctime,
  5655. unsigned char *out,
  5656. unsigned long *outlen);
  5657. int der_decode_utctime(const unsigned char *in,
  5658. unsigned long *inlen,
  5659. ltc_utctime *out);
  5660. int der_length_utctime( ltc_utctime *utctime,
  5661. unsigned long *outlen);
  5662. \end{verbatim}
  5663. The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the
  5664. input. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
  5665. It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
  5666. \subsection{ASN.1 GeneralizedTime}
  5667. The GeneralizedTime type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
  5668. \index{ltc\_utctime structure}
  5669. \begin{verbatim}
  5670. typedef struct {
  5671. unsigned YYYY, /* year 0--9999 */
  5672. MM, /* month 1--12 */
  5673. DD, /* day 1--31 */
  5674. hh, /* hour 0--23 */
  5675. mm, /* minute 0--59 */
  5676. ss, /* second 0--59 */
  5677. fs, /* fractional seconds 1--UINT_MAX */
  5678. off_dir, /* timezone offset direction 0 == +, 1 == - */
  5679. off_hh, /* timezone offset hours */
  5680. off_mm; /* timezone offset minutes */
  5681. } ltc_generalizedtime;
  5682. \end{verbatim}
  5683. The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
  5684. will be subtracted. For instance, the array $\lbrace 2005, 6, 20, 22, 4, 0, 122, 0, 5, 0 \rbrace$ represents the current time of
  5685. \textit{2005, June 20th, 22:04:00.122} with a time offset of +05h00.
  5686. \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
  5687. \begin{verbatim}
  5688. int der_encode_generalizedtime(ltc_generalizedtime *gtime,
  5689. unsigned char *out,
  5690. unsigned long *outlen);
  5691. int der_decode_generalizedtime(const unsigned char *in,
  5692. unsigned long *inlen,
  5693. ltc_generalizedtime *out);
  5694. int der_length_generalizedtime(ltc_generalizedtime *gtime,
  5695. unsigned long *outlen);
  5696. \end{verbatim}
  5697. The encoder will store time in one of the following ASN.1 formats, either \textit{YYYYMMDDhhmmssZ} or
  5698. \textit{YYYYMMDDhhmmss$\pm$hhmm} or\textit{YYYYMMDDhhmmss.fsZ} or \textit{YYYYMMDDhhmmss.fs$\pm$hhmm},
  5699. and perform minimal error checking on the input.
  5700. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but
  5701. rational) useful for catching packet errors.
  5702. The fractional seconds are always added in case they are not $0$.
  5703. The implementation of fractional seconds is currently unreliable and you can't detect decoded
  5704. resp. encode leading $0$'s (e.g. \textit{20170424232717.005Z} would be decoded as
  5705. \textit{22. April 2017, 23:27:17.5}).
  5706. It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
  5707. \subsection{ASN.1 CHOICE}
  5708. The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}. There is no encoder for the CHOICE type, only a
  5709. decoder. The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet. The list can contain any ASN.1 data
  5710. type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.
  5711. There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
  5712. \index{der\_decode\_choice()}
  5713. \begin{verbatim}
  5714. int der_decode_choice(const unsigned char *in,
  5715. unsigned long *inlen,
  5716. ltc_asn1_list *list,
  5717. unsigned long outlen);
  5718. \end{verbatim}
  5719. This will decode the input in the \textit{in} field of length \textit{inlen}. It uses the provided ASN.1 list specified in the \textit{list} field which has
  5720. \textit{outlen} elements. The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field
  5721. will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
  5722. \subsection{ASN.1 Custom Types}
  5723. To be able to represent all other valid types besides the primitive types having their own decoder, the \textit{custom\_type} de- and encoders are provided.
  5724. \index{der\_encode\_custom\_type()} \index{der\_decode\_custom\_type()} \index{der\_length\_custom\_type()} \index{LTC\_ASN1\_CUSTOM\_TYPE}
  5725. \begin{verbatim}
  5726. int der_encode_custom_type(const ltc_asn1_list *root,
  5727. unsigned char *out, unsigned long *outlen);
  5728. int der_decode_custom_type(const unsigned char *in, unsigned long inlen,
  5729. ltc_asn1_list *root);
  5730. int der_length_custom_type(const ltc_asn1_list *root,
  5731. unsigned long *outlen,
  5732. unsigned long *payloadlen);
  5733. \end{verbatim}
  5734. The usage of this de- and encoder is a bit different than the others since the type to be encoded has to be passed to the function.
  5735. Therefore the \textit{root} parameter identifies the type that should be encoded which has been set by the \textit{LTC\_SET\_ASN1}
  5736. and \textit{LTC\_SET\_ASN1\_IDENTIFIER}, resp. \textit{LTC\_SET\_ASN1\_CUSTOM} macros.
  5737. The value to de-/encode has to be linked through the \textit{data} argument of the \textit{LTC\_SET\_ASN1} macro, as done for sequences.
  5738. The value that should be de-/encoded can either be a primitive or a constructed type.
  5739. \subsection{ASN.1 Flexi Decoder}
  5740. The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets without first knowing the structure of the data.
  5741. Where der\_decode\_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely free form.
  5742. The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent}
  5743. and \textit{child}. The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using \textit{next} and \textit{prev}) and items
  5744. encoded in a SEQUENCE are stored as a \textit{child} element.
  5745. When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the \textit{child}
  5746. pointer points to a new list of items contained within the object.
  5747. \index{der\_decode\_sequence\_flexi()}
  5748. \begin{verbatim}
  5749. int der_decode_sequence_flexi(const unsigned char *in,
  5750. unsigned long *inlen,
  5751. ltc_asn1_list **out);
  5752. \end{verbatim}
  5753. This will decode items in the \textit{in} buffer of max input length \textit{inlen} and store the newly created pointer to the list in \textit{out}. This function allocates
  5754. all required memory for the decoding. It stores the number of octets read back into \textit{inlen}.
  5755. The function will terminate when either it hits an invalid ASN.1 tag, or it reads \textit{inlen} octets. An early termination is a soft error, and returns
  5756. normally. The decoded list \textit{out} will point to the very first element of the list (i.e. both parent and prev pointers will be \textbf{NULL}).
  5757. An invalid decoding will terminate the process, and free the allocated memory automatically.
  5758. The flexi decoder calls itself when decoding a constructed type. This leads to
  5759. a 'child process' that will terminate when it decodes an unkown/invalid
  5760. identifier and leaves an allocated but uninitialized child element.
  5761. However the parent processing will continue with a "soft-error".
  5762. This can be detected by checking for \textit{child} elements with
  5763. type \textbf{LTC\_ASN1\_EOL} after decoding.
  5764. The v1.18.0 of the library had support for decoding two new types, \textbf{LTC\_ASN1\_CONSTRUCTED} and \textbf{LTC\_ASN1\_CONTEXT\_SPECIFIC},
  5765. which has been replaced in FIXME-version-next by a more complete approach.
  5766. As of FIXME-version-next all ASN.1 Identifiers which don't have a decoder implemented (and thereby their own type) will be marked as
  5767. \textbf{LTC\_ASN1\_CUSTOM\_TYPE}.
  5768. \textbf{Note:} the list decoded by this function is \textbf{NOT} in the correct form for der\_encode\_sequence() to use directly. You will first
  5769. have to convert the list by first storing all of the siblings in an array then storing all the children as sub-lists of a sequence using the \textit{.data}
  5770. pointer. Currently no function in LibTomCrypt provides this ability.
  5771. \subsubsection{Sample Decoding}
  5772. Suppose we decode the following structure:
  5773. \begin{small}
  5774. \begin{verbatim}
  5775. User ::= SEQUENCE {
  5776. Name IA5 STRING
  5777. LoginToken SEQUENCE {
  5778. passwdHash OCTET STRING
  5779. pubkey ECCPublicKey
  5780. }
  5781. LastOn UTCTIME
  5782. }
  5783. \end{verbatim}
  5784. \end{small}
  5785. \begin{flushleft}and we decoded it with the following code:\end{flushleft}
  5786. \begin{small}
  5787. \begin{verbatim}
  5788. unsigned char inbuf[MAXSIZE];
  5789. unsigned long inbuflen;
  5790. ltc_asn1_list *list;
  5791. int err;
  5792. /* somehow fill inbuf/inbuflen */
  5793. if ((err = der_decode_sequence_flexi(inbuf, inbuflen, &list)) != CRYPT_OK) {
  5794. printf("Error decoding: %s\n", error_to_string(err));
  5795. exit(EXIT_FAILURE);
  5796. }
  5797. \end{verbatim}
  5798. \end{small}
  5799. At this point \textit{list} would point to the SEQUENCE identified by \textit{User}. It would have no sibblings (prev or next), and only a child node. Walking to the child
  5800. node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
  5801. \begin{small}
  5802. \begin{verbatim}
  5803. list = list->child;
  5804. \end{verbatim}
  5805. \end{small}
  5806. Now \textit{list} points to the \textit{Name} member (with the tag IA5 STRING). The \textit{data}, \textit{size}, and \textit{type} members of \textit{list} should reflect
  5807. that of an IA5 STRING. The sibbling will now be the \textit{LoginToken} SEQUENCE. The sibbling has a child node which points to the \textit{passwdHash} OCTET STRING.
  5808. We can walk to this node with the following code:
  5809. \begin{small}
  5810. \begin{verbatim}
  5811. /* list already pointing to 'Name' */
  5812. list = list->next->child;
  5813. \end{verbatim}
  5814. \end{small}
  5815. At this point, \textit{list} will point to the \textit{passwdHash} member of the innermost SEQUENCE. This node has a sibbling, the \textit{pubkey} member of the SEQUENCE.
  5816. The \textit{LastOn} member of the SEQUENCE is a sibbling of the LoginToken node, if we wanted to walk there we would have to go up and over via:
  5817. \begin{small}
  5818. \begin{verbatim}
  5819. list = list->parent->next;
  5820. \end{verbatim}
  5821. \end{small}
  5822. At this point, we are pointing to the last node of the list. Lists are terminated in all directions by a \textbf{NULL} pointer. All nodes are doubly linked so that you
  5823. can walk up and down the nodes without keeping pointers lying around.
  5824. \subsubsection{Shrink'ing a Flexi List}
  5825. While decoding the flexi decoder will recursively decode an ASN.1 \textit{constructed} type it will store the decoded list
  5826. as well as the plain data that was decoded.
  5827. To free up this additional data a shrink function is provided.
  5828. \index{der\_sequence\_shrink()}
  5829. \begin{verbatim}
  5830. void der_sequence_shrink(ltc_asn1_list *in);
  5831. \end{verbatim}
  5832. This will free all the plain constructed data, but keep the decoded list intact.
  5833. \subsubsection{Free'ing a Flexi List}
  5834. To free the list use the following function.
  5835. \index{der\_sequence\_free()}
  5836. \begin{verbatim}
  5837. void der_sequence_free(ltc_asn1_list *in);
  5838. \end{verbatim}
  5839. This will free all of the memory allocated by der\_decode\_sequence\_flexi().
  5840. \mysection{Password Based Cryptography}
  5841. \subsection{PKCS \#5}
  5842. \index{PKCS \#5}
  5843. In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
  5844. is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
  5845. for completeness. Algorithm Two is a bit more modern and more flexible to work with.
  5846. The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.
  5847. \subsubsection{Algorithm One}
  5848. Algorithm One accepts as input a password, an 8--byte salt, and an iteration counter. The iteration counter is meant to act as delay for
  5849. people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
  5850. algorithm and produces an output no longer than the output of the hash.
  5851. \index{pkcs\_5\_alg1()}
  5852. \begin{alltt}
  5853. int pkcs_5_alg1(const unsigned char *password,
  5854. unsigned long password_len,
  5855. const unsigned char *salt,
  5856. int iteration_count,
  5857. int hash_idx,
  5858. unsigned char *out,
  5859. unsigned long *outlen)
  5860. \end{alltt}
  5861. Where \textit{password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
  5862. The \textit{salt} is a fixed size 8--byte array which should be random for each user and session. The \textit{iteration\_count} is the delay desired
  5863. on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.
  5864. The output of length up to \textit{outlen} is stored in \textit{out}. If \textit{outlen} is initially larger than the size of the hash functions output
  5865. it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in \textit{out}.
  5866. \index{pkcs\_5\_alg1\_openssl()}
  5867. \begin{alltt}
  5868. int pkcs_5_alg1_openssl(const unsigned char *password,
  5869. unsigned long password_len,
  5870. const unsigned char *salt,
  5871. int iteration_count,
  5872. int hash_idx,
  5873. unsigned char *out,
  5874. unsigned long *outlen)
  5875. \end{alltt}
  5876. As above, but we generate as many bytes as requested in outlen per the OpenSSL extension to Algorithm One. If you are trying to be compatible with OpenSSL's EVP\_BytesToKey() or the "openssl enc" command line (or variants such as perl's Crypt::CBC), then use this function with MD5 as your hash (ick!) and iteration\_count=1 (double-ick!!).
  5877. \subsubsection{Algorithm Two}
  5878. Algorithm Two is the recommended algorithm for this task. It allows variable length salts, and can produce outputs larger than the
  5879. hash functions output. As such, it can easily be used to derive session keys for ciphers and MACs as well initialization vectors as required
  5880. from a single password and invocation of this algorithm.
  5881. \index{pkcs\_5\_alg2()}
  5882. \begin{alltt}
  5883. int pkcs_5_alg2(const unsigned char *password,
  5884. unsigned long password_len,
  5885. const unsigned char *salt,
  5886. unsigned long salt_len,
  5887. int iteration_count,
  5888. int hash_idx,
  5889. unsigned char *out,
  5890. unsigned long *outlen)
  5891. \end{alltt}
  5892. Where \textit{password} is the users password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
  5893. The \textit{salt} is an array of size \textit{salt\_len}. It should be random for each user and session. The \textit{iteration\_count} is the delay desired
  5894. on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table. The output of length up to
  5895. \textit{outlen} is stored in \textit{out}.
  5896. \begin{verbatim}
  5897. /* demo to show how to make session state material
  5898. * from a password */
  5899. #include <tomcrypt.h>
  5900. int main(void)
  5901. {
  5902. unsigned char password[100], salt[100],
  5903. cipher_key[16], cipher_iv[16],
  5904. mac_key[16], outbuf[48];
  5905. int err, hash_idx;
  5906. unsigned long outlen, password_len, salt_len;
  5907. /* register hash and get it's idx .... */
  5908. /* get users password and make up a salt ... */
  5909. /* create the material (100 iterations in algorithm) */
  5910. outlen = sizeof(outbuf);
  5911. if ((err = pkcs_5_alg2(password, password_len, salt,
  5912. salt_len, 100, hash_idx, outbuf,
  5913. &outlen))
  5914. != CRYPT_OK) {
  5915. /* error handle */
  5916. }
  5917. /* now extract it */
  5918. memcpy(cipher_key, outbuf, 16);
  5919. memcpy(cipher_iv, outbuf+16, 16);
  5920. memcpy(mac_key, outbuf+32, 16);
  5921. /* use material (recall to store the salt in the output) */
  5922. }
  5923. \end{verbatim}
  5924. \subsection{bcrypt}
  5925. \index{bcrypt}
  5926. bcrypt is a password hashing function, similar to PKCS \#5, but it is based on the blowfish symmetric cipher.
  5927. It is widely used in e.g. OpenBSD as default password hash algorithm, or in encrypted OpenSSH key files.
  5928. This implementation provides the PBKDF version as used in OpenSSH key files.
  5929. The OpenBSD implementation is fixed to SHA512 as hashing algorithm, but this generalized implementation works with any hashing algorithm.
  5930. To hash a password with the bcrypt PBKDF algorithm, the following API function is provided.
  5931. \index{bcrypt()}
  5932. \begin{alltt}
  5933. int bcrypt_pbkdf_openbsd(const void *secret, unsigned long secret_len,
  5934. const unsigned char *salt, unsigned long salt_len,
  5935. unsigned int rounds, int hash_idx,
  5936. unsigned char *out, unsigned long *outlen);
  5937. \end{alltt}
  5938. The \textit{secret} parameter is the secret of length \textit{secret\_len} (most of the time a utf-8 encoded user password).
  5939. The \textit{salt} parameter is a pointer to the array of octets of length \textit{salt\_len} containing the salt.
  5940. The \textit{rounds} parameter defines the number of iterations of the expensive key setup that shall be executed.
  5941. The \textit{hash\_idx} parameter defines the hash algorithm that shall be used.
  5942. The \textit{out} parameter shall be a pointer to a buffer of at least 32 octets,
  5943. where \textit{outlen} contains the available buffer size on input and the written size after the invocation.
  5944. \mysection{PKCS \#8}
  5945. \index{PKCS \#8}
  5946. The library has built-in support for PKCS \#8 decoding as specified in RFC 5208.
  5947. Encoding of private keys into PKCS \#8 is not supported.
  5948. The library supports the following encryption algorithms:
  5949. \begin{table}[H]
  5950. \begin{center}
  5951. \begin{tabular}{|l|l|}
  5952. \hline \textbf{Scheme} & \textbf{Algorithm} \\
  5953. \hline PBES1 & pbeWithMD2AndDES-CBC \\
  5954. \hline PBES1 & pbeWithMD2AndRC2-CBC \\
  5955. \hline PBES1 & pbeWithMD5AndDES-CBC \\
  5956. \hline PBES1 & pbeWithMD5AndRC2-CBC \\
  5957. \hline PBES1 & pbeWithSHA1AndDES-CBC \\
  5958. \hline PBES1 & pbeWithSHA1AndRC2-CBC \\
  5959. \hline PBES1 & pbeWithSHAAnd3-KeyTripleDES-CBC \\
  5960. \hline PBES2 + PBKDF2 & desCBC \\
  5961. \hline PBES2 + PBKDF2 & rc2CBC \\
  5962. \hline PBES2 + PBKDF2 & des-EDE3-CBC \\
  5963. \hline PBES2 + PBKDF2 & aes128-CBC \\
  5964. \hline PBES2 + PBKDF2 & aes192-CBC \\
  5965. \hline PBES2 + PBKDF2 & aes256-CBC \\
  5966. \hline
  5967. \end{tabular}
  5968. \caption{Supported PKCS\#8 encryption algorithms}
  5969. \end{center}
  5970. \label{fig:pkcs8}
  5971. \end{table}
  5972. The PKCS \#8 import has no direct API endpoints, but it is available through Public Key Algorithm-specific
  5973. \textit{pkaX\_import\_pkcs8()} functions.
  5974. \mysection{Key Derviation Functions}
  5975. \subsection{HKDF}
  5976. \index{HKDF}
  5977. A key derivation function (KDF) is a basic and essential component of cryptographic systems. Its goal is to take some source of initial
  5978. keying material and derive from it one or more cryptographically strong secret keys.
  5979. HKDF follows the "extract-then-expand" paradigm, where the KDF logically consists of two modules. The first stage takes the input
  5980. keying material and "extracts" from it a fixed-length pseudorandom key K. The second stage "expands" the key K into several additional
  5981. pseudorandom keys (the output of the KDF).
  5982. In many applications, the input keying material is not necessarily distributed uniformly, and the attacker may have some partial
  5983. knowledge about it (for example, a Diffie-Hellman value computed by a key exchange protocol) or even partial control of it (as in some
  5984. entropy-gathering applications). Thus, the goal of the "extract" stage is to "concentrate" the possibly dispersed entropy of the input
  5985. keying material into a short, but cryptographically strong, pseudorandom key. In some applications, the input may already be a
  5986. good pseudorandom key; in these cases, the "extract" stage is not necessary, and the "expand" part can be used alone.
  5987. The second stage "expands" the pseudorandom key to the desired length; the number and lengths of the output keys depend on the
  5988. specific cryptographic algorithms for which the keys are needed.
  5989. \subsection{HKDF Extract}
  5990. To perform the extraction phase, use the following function:
  5991. \index{hkdf\_extract()}
  5992. \begin{alltt}
  5993. int hkdf_extract( int hash_idx,
  5994. const unsigned char *salt,
  5995. unsigned long saltlen,
  5996. const unsigned char *in,
  5997. unsigned long inlen,
  5998. unsigned char *out,
  5999. unsigned long *outlen);
  6000. \end{alltt}
  6001. The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
  6002. The \textit{salt} parameter is a pointer to the array of octets of length \textit{saltlen} containing the salt or a NULL pointer if a salt is not being used (in that case set saltlen to 0).
  6003. \textit{in} is a pointer to an array of octets of length \textit{inlen} containing the source entropy. The extracted output is stored in the location pointed to by \textit{out}.
  6004. You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated to the length of the extracted output. If \textit{outlen} is too small the extracted output will be truncated.
  6005. While the salt is optional, using one improves HKDF's security. If used, the salt should be randomly chosen, but does not need to be secret and may be re-used. Please see RFC5869 section 3.1 for more details.
  6006. \subsection{HKDF Expand}
  6007. To perform the expansion phase, use the following function:
  6008. \index{hkdf\_expand()}
  6009. \begin{alltt}
  6010. int hkdf_expand( int hash_idx,
  6011. const unsigned char *info,
  6012. unsigned long infolen,
  6013. const unsigned char *in,
  6014. unsigned long inlen,
  6015. unsigned char *out,
  6016. unsigned long outlen);
  6017. \end{alltt}
  6018. The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
  6019. The \textit{info} parameter, an array of octets of length \textit{infolen}, is an optional parameter (set \textit{info} to NULL and \textit{infolen} to 0 if not using it) which
  6020. may be used to bind the derived keys to some application and context specific information. This prevents the same keying material from being generated in different contexts. Please see RFC5869 section 3.2 for more information.
  6021. The extracted keying material is passed as octet array \textit{in} of length \textit{inlen}. Expanded output of length \textit{outlen} is generated and stored in octet arrat \textit{out}.
  6022. \subsection{HKDF Extract-and-Expand}
  6023. To perform both phases together, use the following function:
  6024. \index{hkdf()}
  6025. \begin{alltt}
  6026. int hkdf( int hash_idx,
  6027. const unsigned char *salt,
  6028. unsigned long saltlen,
  6029. const unsigned char *info,
  6030. unsigned long infolen,
  6031. const unsigned char *in,
  6032. unsigned long inlen,
  6033. unsigned char *out,
  6034. unsigned long outlen);
  6035. \end{alltt}
  6036. Parameters are as in \textit{hkdf\_extract()} and \textit{hkdf\_expand()}.
  6037. \mysection{SSH}
  6038. The library provides functions to encode and decode SSH data as specified in RFC4251 Ch. 5.
  6039. \subsection{Data types}
  6040. The following enum is used to indicate a specific SSH data type
  6041. (besides EOL which is an internal one that indicates the end of a sequence).
  6042. \begin{figure}[h]
  6043. \begin{center}
  6044. \begin{small}
  6045. \begin{tabular}{|l|l|l|}
  6046. \hline \textbf{Definition} & \textbf{arg data Type} & \textbf{SSH Type} \\
  6047. \hline LTC\_SSHDATA\_EOL & - & End of SSH data sequence. \\
  6048. \hline LTC\_SSHDATA\_BYTE & \texttt{unsigned char} & \texttt{byte} type \\
  6049. \hline LTC\_SSHDATA\_BOOLEAN & \texttt{unsigned char} & \texttt{boolean} type \\
  6050. \hline LTC\_SSHDATA\_UINT32 & \texttt{ulong32} & \texttt{uint32} \\
  6051. \hline LTC\_SSHDATA\_UINT64 & \texttt{ulong64} & \texttt{uint64} \\
  6052. \hline LTC\_SSHDATA\_STRING & \texttt{char*} & \texttt{string} (one octet per char) \\
  6053. \hline LTC\_SSHDATA\_MPINT & \texttt{mp\_int} & \texttt{mpint} \\
  6054. \hline LTC\_SSHDATA\_NAMELIST & \texttt{char*} & \texttt{name-list} (which works exactly like a \texttt{string}) \\
  6055. \hline
  6056. \end{tabular}
  6057. \caption{List of SSH Supported Types}
  6058. \index{ssh\_data\_type}
  6059. \end{small}
  6060. \end{center}
  6061. \end{figure}
  6062. \subsection{De- and Encoding with Multiple Argument Lists}
  6063. \index{ssh\_encode\_sequence\_multi()}
  6064. \index{ssh\_decode\_sequence\_multi()}
  6065. The API works similar to the ASN.1 SEQUENCE multi en- and decoders.
  6066. They either encode or decode a sequence of the supported SSH types where the items are specified after the length parameter.
  6067. \begin{verbatim}
  6068. int ssh_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
  6069. \end{verbatim}
  6070. Where \texttt{out} points to the destination buffer and \texttt{outlen} points
  6071. on function invocation to the length of the destination buffer
  6072. and after returning it will be filled with the number of octets written to the buffer.
  6073. The encoding function \texttt{ssh\_encode\_sequence\_multi()} expects its items to be a pair of \texttt{(type, data)},
  6074. except for the \texttt{string} resp. \texttt{name-list} type, which expects the triple \texttt{(type, data, size)}
  6075. with \texttt{size} being of type \texttt{unsigned long}.
  6076. \begin{verbatim}
  6077. int ssh_decode_sequence_multi(const unsigned char *in, unsigned long *inlen, ...);
  6078. \end{verbatim}
  6079. Where \texttt{in} points to the buffer with the sequence to decode and \texttt{inlen} points
  6080. on function invocation to the length of the sequence
  6081. and after returning it will be filled with the decoded number of octets.
  6082. The decoding function \texttt{ssh\_decode\_sequence\_multi()} expects its items to be a pair of \texttt{(type, data*)},
  6083. except for the \texttt{string} resp. \texttt{name-list} type, which expects the triple \texttt{(type, data, size*)}
  6084. with \texttt{size*} being of type \texttt{unsigned long*}.
  6085. \chapter{Miscellaneous}
  6086. \mysection{Base64 Encoding and Decoding}
  6087. The library provides functions to encode and decode a RFC 4648 Base64 coding scheme.
  6088. \subsection{Standard 'base64' encoding}
  6089. The characters used in the mappings are:
  6090. \begin{verbatim}
  6091. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
  6092. \end{verbatim}
  6093. Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
  6094. common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
  6095. where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
  6096. original input. After the first four characters is the rest of the message.
  6097. Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
  6098. put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
  6099. break up the first four characters.
  6100. To encode a binary string in base64 call:
  6101. \index{base64\_encode()}
  6102. \begin{verbatim}
  6103. int base64_encode(const unsigned char *in,
  6104. unsigned long len,
  6105. char *out,
  6106. unsigned long *outlen);
  6107. \end{verbatim}
  6108. Where \textit{in} is the binary string and \textit{out} is where the ASCII output is placed. You must set the value of \textit{outlen} prior
  6109. to calling this function and it sets the length of the base64 output in \textit{outlen} when it is done. To decode a base64
  6110. string call:
  6111. \index{base64\_decode()}
  6112. \begin{verbatim}
  6113. int base64_decode( const char *in,
  6114. unsigned long len,
  6115. unsigned char *out,
  6116. unsigned long *outlen);
  6117. \end{verbatim}
  6118. The function \textit{base64\_decode} works in a dangerously relaxed way which allows decoding some inputs that do not strictly follow the standard.
  6119. If you want to be strict during decoding you can use:
  6120. \index{base64\_strict\_decode()}
  6121. \begin{verbatim}
  6122. int base64_strict_decode( const char *in,
  6123. unsigned long len,
  6124. unsigned char *out,
  6125. unsigned long *outlen);
  6126. \end{verbatim}
  6127. There is also so called sane mode that ignores white-spaces (\textit{CR}, \textit{LF}, \textit{TAB}, \textit{space}),
  6128. does not care about trailing \textit{=} and also ignores the last input byte in case it is \textit{NUL}.
  6129. \index{base64\_sane\_decode()}
  6130. \begin{verbatim}
  6131. int base64_sane_decode( const char *in,
  6132. unsigned long len,
  6133. unsigned char *out,
  6134. unsigned long *outlen);
  6135. \end{verbatim}
  6136. \subsection{URL--safe 'base64url' encoding}
  6137. The characters used in the mappings are:
  6138. \begin{verbatim}
  6139. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
  6140. \end{verbatim}
  6141. Those characters are sometimes also called URL and filename safe alphabet.
  6142. The interface is analogous to \textit{base64\_xxxx} functions in previous chapter.
  6143. \index{base64url\_encode()}
  6144. \index{base64url\_strict\_encode()}
  6145. \index{base64url\_decode()}
  6146. \index{base64url\_strict\_decode()}
  6147. \index{base64url\_sane\_decode()}
  6148. \begin{verbatim}
  6149. int base64url_encode(const unsigned char *in, unsigned long len,
  6150. char *out, unsigned long *outlen);
  6151. int base64url_strict_encode(const unsigned char *in, unsigned long inlen,
  6152. char *out, unsigned long *outlen);
  6153. int base64url_decode( const char *in, unsigned long len,
  6154. unsigned char *out, unsigned long *outlen);
  6155. int base64url_strict_decode( const char *in, unsigned long len,
  6156. unsigned char *out, unsigned long *outlen);
  6157. int base64url_sane_decode( const char *in, unsigned long len,
  6158. unsigned char *out, unsigned long *outlen);
  6159. \end{verbatim}
  6160. \mysection{Base32 Encoding and Decoding}
  6161. The library provides functions to encode and decode a Base32 coding scheme. The supported mappings are:
  6162. \begin{figure}[H]
  6163. \begin{center}
  6164. \begin{tabular}{|l|l|l|}
  6165. \hline \textbf{id} & \textbf{Mapping} & \textbf{Name} \\
  6166. \hline BASE32\_RFC4648 & ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 & RFC-4648 \\
  6167. \hline BASE32\_BASE32HEX & 0123456789ABCDEFGHIJKLMNOPQRSTUV & Base32hex \\
  6168. \hline BASE32\_ZBASE32 & YBNDRFG8EJKMCPQXOT1UWISZA345H769 & ZBase32 \\
  6169. \hline BASE32\_CROCKFORD & 0123456789ABCDEFGHJKMNPQRSTVWXYZ & Crockford \\
  6170. \hline
  6171. \end{tabular}
  6172. \end{center}
  6173. \caption{Base32 coding schemes}
  6174. \end{figure}
  6175. To encode a binary string in base32 call:
  6176. \index{base32\_encode()}
  6177. \begin{verbatim}
  6178. int base32_encode(const unsigned char *in,
  6179. unsigned long len,
  6180. char *out,
  6181. unsigned long *outlen,
  6182. base32_alphabet id);
  6183. \end{verbatim}
  6184. Where \textit{in} is the binary string, \textit{out} is where the ASCII output is placed and \textit{id} is
  6185. \textit{BASE32\_RFC4648}, \textit{BASE32\_BASE32HEX}, \textit{BASE32\_ZBASE32} or \textit{BASE32\_CROCKFORD} according the table above.
  6186. To decode a base32 string call:
  6187. \index{base32\_decode()}
  6188. \begin{verbatim}
  6189. int base32_decode(const char *in,
  6190. unsigned long len,
  6191. unsigned char *out,
  6192. unsigned long *outlen,
  6193. base32_alphabet id);
  6194. \end{verbatim}
  6195. \mysection{Base16 Encoding and Decoding}
  6196. The library provides functions to encode and decode a Base16 a.k.a Hex string.
  6197. To encode a binary string in base16 call:
  6198. \index{base16\_encode()}
  6199. \begin{verbatim}
  6200. int base16_encode(const unsigned char *in, unsigned long inlen,
  6201. char *out, unsigned long *outlen,
  6202. unsigned int options);
  6203. \end{verbatim}
  6204. Where \textit{in} is the binary string,
  6205. \textit{out} is where the ASCII output is placed
  6206. and \textit{options} is either $0$ to use lower-letter \textit{a..f} or else to use caps \textit{A..F}.
  6207. To decode a base16 string call:
  6208. \index{base16\_decode()}
  6209. \begin{verbatim}
  6210. int base16_decode(const char *in, unsigned long inlen,
  6211. unsigned char *out, unsigned long *outlen);
  6212. \end{verbatim}
  6213. \mysection{Padding data}
  6214. The library provides functions to pad and depad according to several standards, please refer to Figure \ref{fig:paddingmodes} for details about the supported standards.
  6215. \subsection{Padding mode argument}
  6216. All functions have a \textit{mode} argument which must be set to the bit-wise OR of the desired blocksize and one of the modes as shown in the following table:
  6217. \begin{figure}[H]
  6218. \begin{minipage}{\textwidth}
  6219. \begin{center}
  6220. \begin{tabular}{|l|l|}
  6221. \hline \textbf{mode} & \textbf{Standard} \\
  6222. \hline LTC\_PAD\_PKCS7 & a.k.a CMS; best described in RFC-5652 / PKCS \#7; also mentioned in PKCS \#5 which refers to RFC-1423 \\
  6223. \hline LTC\_PAD\_ISO\_10126 & ISO/IEC 10126 \footnote{\textit{ISO/IEC 10126} support is only available when the library is built with \textit{rng\_get\_bytes()} support} \\
  6224. \hline LTC\_PAD\_ANSI\_X923 & ANSI X.923 \\
  6225. \hline LTC\_PAD\_ONE\_AND\_ZERO & ISO/IEC 7816-4 \\
  6226. \hline LTC\_PAD\_ZERO & ISO/IEC 10118-1 \\
  6227. \hline LTC\_PAD\_ZERO\_ALWAYS & ISO/IEC 10118-1 \footnote{\textit{LTC\_PAD\_ZERO\_ALWAYS} adds an entire block of padding if the plaintext length is divisible by the blocksize} \\
  6228. \hline
  6229. \end{tabular}
  6230. \end{center}
  6231. \end{minipage}
  6232. \caption{Padding modes}
  6233. \label{fig:paddingmodes}
  6234. \end{figure}
  6235. \textit{ISO/IEC 10126} has been withdrawn as an ISO/IEC standard in 2007 and is only provided for historical reasons (it was used e.g. in early versions of TLS/SSL).
  6236. Therefore it should not be used for new designs.
  6237. \subsection{Padding}
  6238. To pad data call:
  6239. \index{padding\_pad()}
  6240. \begin{verbatim}
  6241. int padding_pad(unsigned char *data,
  6242. unsigned long length,
  6243. unsigned long *padded_length,
  6244. unsigned long mode);
  6245. \end{verbatim}
  6246. Where \textit{data} is a pointer to a buffer containing the data to pad,
  6247. \textit{length} is the original length of the data to pad and
  6248. \textit{padded\_length} is a pointer that should contain the length of buffer available and will contain the padded data-length.
  6249. It is possible to call this function with \textit{padded\_length} set to $0$ which will then return with the error-code \textit{CRYPT\_BUFFER\_OVERFLOW}
  6250. and \textit{padded\_length} set to the required size of the buffer.
  6251. \subsection{Depadding}
  6252. To depad data call:
  6253. \index{padding\_depad()}
  6254. \begin{verbatim}
  6255. int padding_depad(unsigned char *data,
  6256. unsigned long *length,
  6257. unsigned long mode);
  6258. \end{verbatim}
  6259. Where \textit{data} is a pointer to the data to depad,
  6260. \textit{length} is a pointer that should contain the length of the padded data and will be updated to contain the length of the data after depadding.
  6261. \mysection{Primality Testing}
  6262. \index{Primality Testing}
  6263. The library includes primality testing and random prime functions as well. The primality tester will perform the test in
  6264. two phases. First it will perform trial division by the first few primes. Second it will perform \textit{LTC\_MILLER\_RABIN\_REPS} (pre-defined to $35$) rounds of the
  6265. Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
  6266. composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
  6267. the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
  6268. $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
  6269. When making random primes the trial division step is in fact an optimized implementation of \textit{Implementation of Fast RSA Key Generation on Smart Cards}\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
  6270. In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candidate
  6271. is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
  6272. math operations. As a result the routine can scan ahead to the next number required for testing with very little work
  6273. involved.
  6274. In the event that a composite did make it through it would most likely cause the the algorithm trying to use it to fail. For
  6275. instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
  6276. as $\phi(pq)$ or $(p - 1)(q - 1)$. The decryption exponent $d$ is found as $de \equiv 1\mbox{ }(\mbox{mod } \phi(pq))$. If either $p$ or $q$ is composite the value of $d$ will be incorrect and the user
  6277. will not be able to sign or decrypt messages at all. Suppose $p$ was prime and $q$ was composite this is just a variation of
  6278. the multi-prime RSA. Suppose $q = rs$ for two primes $r$ and $s$ then $\phi(pq) = (p - 1)(r - 1)(s - 1)$ which clearly is
  6279. not equal to $(p - 1)(rs - 1)$.
  6280. These are not technically part of the LibTomMath library but this is the best place to document them.
  6281. To test if a \textit{mp\_int} is prime call:
  6282. \begin{verbatim}
  6283. int is_prime(mp_int *N, int *result);
  6284. \end{verbatim}
  6285. This puts a one in \textit{result} if the number is probably prime, otherwise it places a zero in it. It is assumed that if
  6286. it returns an error that the value in \textit{result} is undefined. To make
  6287. a random prime call:
  6288. \begin{verbatim}
  6289. int rand_prime( mp_int *N,
  6290. unsigned long len,
  6291. prng_state *prng,
  6292. int wprng);
  6293. \end{verbatim}
  6294. Where \textit{len} is the size of the prime in bytes ($2 \le len \le 256$). You can set \textit{len} to the negative size you want
  6295. to get a prime of the form $p \equiv 3\mbox{ }(\mbox{mod } 4)$. So if you want a 1024-bit prime of this sort pass
  6296. \textit{len = -128} to the function. Upon success it will return {\bf CRYPT\_OK} and \textit{N} will contain an integer which
  6297. is very likely prime.
  6298. \mysection{Random MPI Generation}
  6299. \index{Random MPI Generation}
  6300. Several Public Key Cryptography algorithms require random MPI's for operations like signature generation.
  6301. The library provides two API functions to generate random MPI's which allow the utilisation of a user-defined PRNG to aquire the random data.
  6302. \index{rand\_bn\_bits()}
  6303. \begin{verbatim}
  6304. int rand_bn_bits( void *N,
  6305. int bits,
  6306. prng_state *prng,
  6307. int wprng);
  6308. \end{verbatim}
  6309. This sets \textit{N} to a \textit{bits}-long random MPI.
  6310. \index{rand\_bn\_upto()}
  6311. \begin{verbatim}
  6312. int rand_bn_upto( void *N,
  6313. void *limit,
  6314. prng_state *prng,
  6315. int wprng);
  6316. \end{verbatim}
  6317. This ensures that \textit{N} is set to a random MPI in the range $1 \le N < limit$.
  6318. \mysection{Helper functions}
  6319. \subsection{Zero'ing data}
  6320. Optimizing compilers are sometimes allowed to remove an invocation of \textit{memset(out, 0, outlen)},
  6321. which could result in sensitive data not being zero'ed out. LibTomCrypt, therefore, implements a variant
  6322. of this routine, \textit{zeromem(out, outlen)}, which won't be optimized away.
  6323. \index{zeromem()}
  6324. \begin{verbatim}
  6325. void zeromem(volatile void *out, size_t outlen);
  6326. \end{verbatim}
  6327. This zero's the buffer \textit{out} of size \textit{outlen}.
  6328. \subsection{Constant-time memory compare}
  6329. Some symmetric-key cryptographic operation-modes are vulnerable to timing attacks in case non-contant-time memory comparison functions
  6330. are used to compare results. Therefore LibTomCrypt implements a constant-time memory compare function.
  6331. \index{mem\_neq()}
  6332. \begin{verbatim}
  6333. int mem_neq(const void *a, const void *b, size_t len);
  6334. \end{verbatim}
  6335. This will compare the buffer \textit{a} against the buffer \textit{b} for \textit{len} bytes.
  6336. The return value is either \textit{0} when the content of \textit{a} and \textit{b} is equal or \textit{1} when it differs.
  6337. \subsection{Radix to binary conversion}
  6338. All public-key cryptographic algorithms provide a way to import and/or export their key parameters in binary format.
  6339. In order to be able to import keys stored in different formats, e.g. hexadecimal strings, the \textit{radix\_to\_bin()} function is provided.
  6340. \index{radix\_to\_bin()}
  6341. \begin{verbatim}
  6342. int radix_to_bin(const void *in, int radix, void *out, unsigned long *len);
  6343. \end{verbatim}
  6344. This will convert the MPI \textit{in} of radix \textit{radix} to the buffer pointed to by \textit{out}.
  6345. The field \textit{len} is a pointer to the length of the buffer on input and the length stored on output.
  6346. In case you don't know the length of the buffer you can use \textit{radix\_to\_bin()} to determine the length for you.
  6347. \begin{verbatim}
  6348. #include <tomcrypt.h>
  6349. int main(void)
  6350. {
  6351. const char *mpi = "AABBCCDD";
  6352. unsigned long l = 0;
  6353. void* buf;
  6354. int ret;
  6355. ltc_mp = ltm_desc;
  6356. if (radix_to_bin(mpi, 16, NULL, &l) != CRYPT_BUFFER_OVERFLOW)
  6357. return EXIT_FAILURE;
  6358. buf = malloc(l);
  6359. ret = EXIT_SUCCESS;
  6360. if (radix_to_bin(mpi, 16, buf, &l) != CRYPT_OK)
  6361. ret = EXIT_FAILURE;
  6362. free(buf);
  6363. return ret;
  6364. }
  6365. \end{verbatim}
  6366. \mysection{Dynamic Language Support}
  6367. \index{Dynamic Language Support}
  6368. Various LibTomCrypt functions require that their callers define a struct
  6369. (or a union) and provide a pointer to it, or allocate sufficient memory and
  6370. provide its pointer. Programs written in C or C++ can obtain the necessary
  6371. information by simply including the appropriate header files, but dynamic
  6372. languages like Python don't understand C header files, and without assistance,
  6373. have no way to know how much memory to allocate. A similar story can be told
  6374. for certain LTC constant values.
  6375. LTC's Dynamic Language Support provides functions that return the size of
  6376. a named struct or union, the value of a named constant, a list of all sizes
  6377. supported, and a list of all named constants supported. Two additional
  6378. functions can initialize LTM and TFM.
  6379. To get the size of a named struct or union:
  6380. \begin{verbatim}
  6381. int crypt_get_size( const char *namein,
  6382. unsigned int *sizeout);
  6383. \end{verbatim}
  6384. $namein$ is spelled exactly as found in the C header files. This function will
  6385. return -1 if $namein$ is not found.
  6386. To get the value of a named constant:
  6387. \begin{verbatim}
  6388. int crypt_get_constant(const char *namein,
  6389. int *valueout);
  6390. \end{verbatim}
  6391. $namein$ is spelled exactly as found in the C header files. Again, -1 is
  6392. returned if $namein$ is not found.
  6393. To get the names of all the supported structs, unions and constants:
  6394. \begin{verbatim}
  6395. int crypt_list_all_sizes( char *names_list,
  6396. unsigned int *names_list_size);
  6397. int crypt_list_all_constants( char *names_list,
  6398. unsigned int *names_list_size);
  6399. \end{verbatim}
  6400. You may want to call these functions twice, first to get the amount
  6401. of memory to be allocated for the $names\_list$, and a final time to
  6402. actually populate $names\_list$. If $names\_list$ is NULL,
  6403. $names\_list\_size$ will be the minimum size needed to receive the
  6404. complete $names\_list$. If $names\_list$ is NOT NULL, $names\_list$ must
  6405. be a pointer to sufficient memory into which the $names\_list$ will be
  6406. written. Also, the value in $names\_list\_size$ sets the upper bound of
  6407. the number of characters to be written. A -1 return value signifies
  6408. insufficient space.
  6409. The format of the $names\_list$ string is a series of $name,value$ pairs
  6410. where each name and value is separated by a comma, the pairs are separated
  6411. by newlines, and the list is null terminated.
  6412. Here is a Python program demonstrating how to call various LTC dynamic
  6413. language support functions.
  6414. A more detailed example is given in the library source in \texttt{demos/demo\_dynamic.py}.
  6415. \begin{verbatim}
  6416. from ctypes import *
  6417. # load the OSX shared/dynamic library
  6418. LIB = CDLL('libtomcrypt.dylib')
  6419. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6420. # print info about this library
  6421. little = c_int() # assume False is big
  6422. word32 = c_int() # assume False is 64-bit
  6423. LIB.crypt_get_constant('ENDIAN_LITTLE', byref(little))
  6424. LIB.crypt_get_constant('ENDIAN_32BITWORD', byref(word32))
  6425. print('this lib was compiled for a %s endian %d-bit processor'
  6426. % ('little' if little else 'big', 32 if word32 else 64))
  6427. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6428. # print the size of the struct named "sha256_state"
  6429. struct_size = c_int()
  6430. # don't forget to add the '_struct' or '_union' suffix
  6431. LIB.crypt_get_size('sha256_state_struct', byref(struct_size))
  6432. print('allocate %d bytes for sha256_state' % struct_size.value)
  6433. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6434. # print a list of all supported named constants
  6435. list_size = c_int()
  6436. # call with NULL to calc the min size needed for the list
  6437. LIB.crypt_list_all_constants(None, byref(list_size))
  6438. # allocate required space
  6439. names_list = c_buffer(list_size.value)
  6440. # call again providing a pointer to where to write the list
  6441. LIB.crypt_list_all_constants(names_list, byref(list_size))
  6442. print(names_list.value)
  6443. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  6444. # print a list of all supported named structs and unions
  6445. list_size = c_int()
  6446. # call with NULL to calc the min size needed for the list
  6447. LIB.crypt_list_all_sizes(None, byref(list_size))
  6448. # allocate required space
  6449. names_list = c_buffer(list_size.value)
  6450. # call again providing a pointer to where to write the list
  6451. LIB.crypt_list_all_sizes(names_list, byref(list_size))
  6452. print(names_list.value)
  6453. \end{verbatim}
  6454. \chapter{Programming Guidelines}
  6455. \mysection{Secure Pseudo Random Number Generators}
  6456. Probably the single most vulnerable point of any cryptosystem is the PRNG. Without one, generating and protecting secrets
  6457. would be impossible. The requirement that one be setup correctly is vitally important, and to address this point the library
  6458. does provide two RNG sources that will address the largest amount of end users as possible. The \textit{sprng} PRNG provides an easy to
  6459. access source of entropy for any application on a UNIX (and the like) or Windows computer.
  6460. However, when the end user is not on one of these platforms, the application developer must address the issue of finding
  6461. entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
  6462. a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
  6463. \mysection{Preventing Trivial Errors}
  6464. Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values. All of the functions
  6465. which output variable length strings will require you to pass the length of the destination. If the size of your output
  6466. buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
  6467. Also, virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors, as simple
  6468. typos can cause algorithms to fail to work as desired.
  6469. \mysection{Registering Your Algorithms}
  6470. To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
  6471. before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
  6472. A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
  6473. having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
  6474. write the few functions required plus a descriptor. After registering your PRNG, all of the library functions that
  6475. need a PRNG can instantly take advantage of it. The same applies for ciphers, hashes, and bignum math routines.
  6476. \mysection{Key Sizes}
  6477. \subsection{Symmetric Ciphers}
  6478. For symmetric ciphers, use as large as of a key as possible. For the most part \textit{bits are cheap} so using a 256--bit key
  6479. is not a hard thing to do. As a good rule of thumb do not use a key smaller than 128 bits.
  6480. \subsection{Asymmetric Ciphers}
  6481. The following chart gives the work factor for solving a DH/RSA public key using the NFS. The work factor for a key of order
  6482. $n$ is estimated to be
  6483. \begin{equation}
  6484. e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
  6485. \end{equation}
  6486. Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
  6487. is:
  6488. \begin{figure}[H]
  6489. \begin{center}
  6490. \begin{tabular}{|c|c|}
  6491. \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
  6492. \hline 512 & 63.92 \\
  6493. \hline 768 & 76.50 \\
  6494. \hline 1024 & 86.76 \\
  6495. \hline 1536 & 103.37 \\
  6496. \hline 2048 & 116.88 \\
  6497. \hline 2560 & 128.47 \\
  6498. \hline 3072 & 138.73 \\
  6499. \hline 4096 & 156.49 \\
  6500. \hline
  6501. \end{tabular}
  6502. \end{center}
  6503. \caption{RSA/DH Key Strength}
  6504. \end{figure}
  6505. The work factor for ECC keys is much higher since the best attack is still fully exponential. Given a key of magnitude
  6506. $n$ it requires $\sqrt n$ work. The following table summarizes the work required:
  6507. \begin{figure}[H]
  6508. \begin{center}
  6509. \begin{tabular}{|c|c|}
  6510. \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
  6511. \hline 112 & 56 \\
  6512. \hline 128 & 64 \\
  6513. \hline 160 & 80 \\
  6514. \hline 192 & 96 \\
  6515. \hline 224 & 112 \\
  6516. \hline 256 & 128 \\
  6517. \hline 384 & 192 \\
  6518. \hline 521 & 260.5 \\
  6519. \hline
  6520. \end{tabular}
  6521. \end{center}
  6522. \caption{ECC Key Strength}
  6523. \end{figure}
  6524. Using the above tables the following suggestions for key sizes seems appropriate:
  6525. \begin{center}
  6526. \begin{tabular}{|c|c|c|}
  6527. \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
  6528. \hline Near term & 1024 & 160 \\
  6529. \hline Short term & 1536 & 192 \\
  6530. \hline Long Term & 2560 & 384 \\
  6531. \hline
  6532. \end{tabular}
  6533. \end{center}
  6534. \mysection{Thread Safety}
  6535. The library is not fully thread safe but several simple precautions can be taken to avoid any problems. The registry functions
  6536. such as register\_cipher() are not thread safe no matter what you do. It is best to call them from your programs initialization
  6537. code before threads are initiated.
  6538. The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
  6539. thread has its own state variables then they will not affect each other, and are fully thread safe. This is fairly simple with symmetric ciphers
  6540. and hashes.
  6541. \index{LTC\_PTHREAD}
  6542. The only sticky issue is a shared PRNG which can be alleviated with the careful use of mutex devices. Defining LTC\_PTHREAD for instance, enables
  6543. pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.
  6544. \chapter{Configuring and Building the Library}
  6545. \mysection{Introduction}
  6546. The library is fairly flexible about how it can be built, used, and generally distributed. Additions are being made with
  6547. each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
  6548. the build process to make a smaller library. This is particularly useful for shared libraries.
  6549. As of v1.06 of the library, the build process has been moved to two steps for the typical LibTomCrypt application. This is because
  6550. LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath, GnuMP, or TomsFastMath).
  6551. The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
  6552. configured. Note that LibTomCrypt can be built with no internal math descriptors. This means that one must be provided at either
  6553. build, or run time for the application. LibTomCrypt comes with three math descriptors that provide a standard interface to math
  6554. libraries.
  6555. \mysection{Makefile variables}
  6556. All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process. Most of the
  6557. settings can be overwritten from the command line which makes custom installation a breeze.
  6558. \subsection{MAKE, CC, AR and CROSS\_COMPILE}
  6559. \index{MAKE} \index{CC} \index{AR} \index{CROSS\_COMPILE}
  6560. The MAKE, CC and AR flags can all be overwritten. They default to \textit{make}, \textit{\$CC} and \textit{\$AR} respectively.
  6561. Changing MAKE allows you to change what program will be invoked to handle sub--directories. For example, this
  6562. \begin{verbatim}
  6563. gmake install MAKE=gmake
  6564. \end{verbatim}
  6565. \begin{flushleft} will build and install the libraries with the \textit{gmake} tool. Similarly, \end{flushleft}
  6566. \begin{verbatim}
  6567. make CC=arm-gcc AR=arm-ar
  6568. \end{verbatim}
  6569. \begin{flushleft} will build the library using \textit{arm--gcc} as the compiler and \textit{arm--ar} as the archiver. \end{flushleft}
  6570. \begin{verbatim}
  6571. make CROSS_COMPILE=arm-none-eabi-
  6572. \end{verbatim}
  6573. \begin{flushleft} will build the library using the \textit{arm--none--eabi--} prefix'ed toolchain. \end{flushleft}
  6574. \subsection{IGNORE\_SPEED and LTC\_DEBUG}
  6575. \index{IGNORE\_SPEED} \index{LTC\_DEBUG}
  6576. When \textbf{IGNORE\_SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
  6577. CFLAGS on the command line. E.g. to add debugging
  6578. \begin{verbatim}
  6579. make IGNORE_SPEED=1 CFLAGS="-g3"
  6580. \end{verbatim}
  6581. This will turn off optimizations and add \textit{-g3} to the CFLAGS which enables debugging.
  6582. Alternatively one can define \textbf{LTC\_DEBUG} instead, which additionally defines \textit{LTC\_NO\_ASM} and enables debug output on test failures.
  6583. Defining \textit{LTC\_DEBUG=2} has the effect to enable verbose output in some of the tests.
  6584. \begin{verbatim}
  6585. make LTC_DEBUG=2
  6586. \end{verbatim}
  6587. \begin{flushleft} will build the library without compiler-optimisation or architecture specific code and will enable debugging
  6588. and verbose debug output. \end{flushleft}
  6589. \subsection{LIBNAME}
  6590. \index{LIBNAME}
  6591. \textbf{LIBNAME} is the name of the output library (archive) to create. It defaults to \textit{libtomcrypt.a} for static builds and \textit{libtomcrypt.la} for
  6592. shared.
  6593. On installation of the shared library the appropriately versioned \textit{libtomcrypt.so}, \textit{libtomcrypt.so.0} etc. will be created by \textit{libtool}.
  6594. \subsection{Installation Directories}
  6595. \index{DESTDIR} \index{PREFIX} \index{LIBPATH} \index{INCPATH} \index{DATAPATH} \index{BINPATH}
  6596. \textbf{DESTDIR} is the location where the output will be stored. It default to an empty string.
  6597. \textbf{PREFIX} is the prefix for the installation directories. It defaults to \textit{/usr/local}.
  6598. \textbf{LIBPATH} is the location of the library directory which defaults to \textit{\$PREFIX/lib}.
  6599. \textbf{INCPATH} is the location of the header file directory which defaults to \textit{\$PREFIX/include}.
  6600. \textbf{DATAPATH} is the location of the data (documentation) directory which defaults to \textit{\$PREFIX/share/doc/libtomcrypt/pdf}.
  6601. \textbf{BINPATH} is the location of the binary file directory which defaults to \textit{\$PREFIX/bin}.
  6602. They allow to configure the installation locations of the libary.
  6603. \begin{verbatim}
  6604. make PREFIX=/home/tom/project DATAPATH=/home/tom/project/docs install
  6605. \end{verbatim}
  6606. This will build the library and install it to the directories under \textit{/home/tom/project/}. e.g.
  6607. \begin{small}
  6608. \begin{verbatim}
  6609. /home/tom/project/:
  6610. total 1
  6611. drwxr-xr-x 2 tom users 80 Jul 30 16:02 docs
  6612. drwxr-xr-x 2 tom users 528 Jul 30 16:02 include
  6613. drwxr-xr-x 2 tom users 80 Jul 30 16:02 lib
  6614. /home/tom/project/docs:
  6615. total 452
  6616. -rwxr-xr-x 1 tom users 459009 Jul 30 16:02 crypt.pdf
  6617. /home/tom/project/include:
  6618. total 132
  6619. -rwxr-xr-x 1 tom users 2482 Jul 30 16:02 tomcrypt.h
  6620. -rwxr-xr-x 1 tom users 702 Jul 30 16:02 tomcrypt_argchk.h
  6621. -rwxr-xr-x 1 tom users 2945 Jul 30 16:02 tomcrypt_cfg.h
  6622. -rwxr-xr-x 1 tom users 22763 Jul 30 16:02 tomcrypt_cipher.h
  6623. -rwxr-xr-x 1 tom users 5174 Jul 30 16:02 tomcrypt_custom.h
  6624. -rwxr-xr-x 1 tom users 11314 Jul 30 16:02 tomcrypt_hash.h
  6625. -rwxr-xr-x 1 tom users 11571 Jul 30 16:02 tomcrypt_mac.h
  6626. -rwxr-xr-x 1 tom users 13614 Jul 30 16:02 tomcrypt_macros.h
  6627. -rwxr-xr-x 1 tom users 14714 Jul 30 16:02 tomcrypt_math.h
  6628. -rwxr-xr-x 1 tom users 632 Jul 30 16:02 tomcrypt_misc.h
  6629. -rwxr-xr-x 1 tom users 10934 Jul 30 16:02 tomcrypt_pk.h
  6630. -rwxr-xr-x 1 tom users 2634 Jul 30 16:02 tomcrypt_pkcs.h
  6631. -rwxr-xr-x 1 tom users 7067 Jul 30 16:02 tomcrypt_prng.h
  6632. -rwxr-xr-x 1 tom users 1467 Jul 30 16:02 tomcrypt_test.h
  6633. /home/tom/project/lib:
  6634. total 1073
  6635. -rwxr-xr-x 1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
  6636. \end{verbatim}
  6637. \end{small}
  6638. For further information see: \url{https://www.gnu.org/prep/standards/html_node/DESTDIR.html}
  6639. and \url{https://www.freebsd.org/doc/en/books/porters-handbook/porting-prefix.html}.
  6640. \mysection{Extra libraries}
  6641. \index{EXTRALIBS}
  6642. \textbf{EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
  6643. that GCC expects for global archives.
  6644. \begin{verbatim}
  6645. make install test timing CFLAGS="-DTFM_DESC -DUSE_TFM" EXTRALIBS=-ltfm
  6646. \end{verbatim}
  6647. This will install the library using the TomsFastMath library and link the \textit{libtfm.a} library out of the default library search path. The two
  6648. defines are explained below. You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
  6649. the \textbf{EXTRALIBS} variable by separating them by a space.
  6650. Note that \textbf{EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
  6651. \mysection{Building a Static Library}
  6652. Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
  6653. \begin{verbatim}
  6654. make install CFLAGS="-DTFM_DESC"
  6655. \end{verbatim}
  6656. That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously. You can enable
  6657. the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly, you can build the library with no built--in
  6658. math descriptors.
  6659. \begin{verbatim}
  6660. make install
  6661. \end{verbatim}
  6662. In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
  6663. public key functions.
  6664. Note that even if you include the built--in descriptors you must link against the source library as well.
  6665. \begin{verbatim}
  6666. gcc -DTFM_DESC myprogram.c -ltomcrypt -ltfm -o myprogram
  6667. \end{verbatim}
  6668. This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
  6669. we define \textbf{TFM\_DESC} for compilation. This is so that the TFM descriptor symbol will be defined for the client application to make use of without
  6670. giving warnings.
  6671. \mysection{Building a Shared Library}
  6672. LibTomCrypt can also be built as a shared library through the \textit{makefile.shared} make script. It is similar to use as the static script except
  6673. that you \textbf{must} specify the \textbf{EXTRALIBS} variable at install time.
  6674. \begin{verbatim}
  6675. make -f makefile.shared install CFLAGS="-DTFM_DESC" EXTRALIBS=-ltfm
  6676. \end{verbatim}
  6677. This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
  6678. shared build process requires libtool to be installed.
  6679. \mysection{Building with CMake}
  6680. LibTomCrypt can also be built via CMake.
  6681. \begin{verbatim}
  6682. git clone https://github.com/libtom/libtomcrypt.git
  6683. mkdir -p libtomcrypt/build
  6684. cd libtomcrypt/build
  6685. cmake ..
  6686. make -j$(nproc)
  6687. \end{verbatim}
  6688. Per default a static library in \textbf{Release} configuration is built, without tests and building against the LibTomMath library.
  6689. A shared library build can be done by setting \textbf{-DBUILD\_SHARED\_LIBS=On} when invoking the \textbf{cmake} command.
  6690. Tests can be enabled by setting \textbf{-DBUILD\_TESTING=On} when invoking the \textbf{cmake} command.
  6691. \mysection{Header Configuration}
  6692. The file \textit{tomcrypt\_cfg.h} is what lets you control various high level macros which control the behaviour of the library. Build options are also
  6693. stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.
  6694. \subsubsection{ARGTYPE}
  6695. This lets you control how the LTC\_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
  6696. NULL. There are four settings for ARGTYPE. When set to 0, it will have the default behaviour of printing a message to
  6697. stderr and raising a SIGABRT signal. This is provided so all platforms that use LibTomCrypt can have an error that functions
  6698. similarly. When set to 1, it will simply pass on to the assert() macro. When set to 2, the macro will display the error to
  6699. stderr then return execution to the caller. This could lead to a segmentation fault (e.g. when a pointer is \textbf{NULL}) but is useful
  6700. if you handle signals on your own. When set to 3, it will resolve to a empty macro and no error checking will be performed. Finally, when set
  6701. to 4, it will return CRYPT\_INVALID\_ARG to the caller.
  6702. \subsubsection{Endianness}
  6703. There are five macros related to endianness issues. For little endian platforms define, \textbf{ENDIAN\_LITTLE}. For big endian
  6704. platforms define \textbf{ENDIAN\_BIG}. Similarly when the default word size of an \textit{unsigned long} is 32-bits define \textbf{ENDIAN\_32BITWORD}
  6705. or define \textbf{ENDIAN\_64BITWORD} when its 64-bits. If you do not define any of them the library will automatically use \textbf{ENDIAN\_NEUTRAL}
  6706. which will work on all platforms.
  6707. Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.
  6708. \mysection{Customisation}
  6709. There are also options you can specify from the \textit{tomcrypt\_custom.h} header file.
  6710. \subsection{X memory routines}
  6711. \index{XMALLOC}\index{XREALLOC}\index{XCALLOC}\index{XFREE}\index{XMEMSET}\index{XMEMCPY}\index{XMEMMOVE}\index{XMEMCMP}\index{XSTRCMP}\index{XSTRNCPY}
  6712. At the top of tomcrypt\_custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on. They resolve to
  6713. the name of the respective functions from the standard C library by default. This lets you substitute in your own memory routines.
  6714. If you substitute in your own functions they must behave like the standard C library functions in terms of what they expect as input and
  6715. output.
  6716. These macros are handy for working with platforms which do not have a standard C library.
  6717. For instance, the OLPC\footnote{See \url{http://dev.laptop.org/git?p=bios-crypto;a=summary}}
  6718. bios code uses these macros to redirect to very compact heap and string operations.
  6719. \subsection{X clock routines}
  6720. The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
  6721. the default clock() used with a replacement. By default the standard C library clock() function is used.
  6722. \subsection{LTC\_NO\_FILE}
  6723. During the build if LTC\_NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
  6724. functions and instead simply return CRYPT\_NOP. This should help resolve any linker errors stemming from a lack of
  6725. file I/O on embedded platforms.
  6726. \subsection{LTC\_CLEAN\_STACK}
  6727. When this functions is defined the functions that store key material on the stack will clean up afterwards.
  6728. Assumes that you have no memory paging with the stack.
  6729. \subsection{LTC\_TEST}
  6730. When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build. This is the default configuration.
  6731. If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.
  6732. \subsection{LTC\_NO\_FAST}
  6733. When this has been defined the library will not use faster word oriented operations. By default, they are only enabled for platforms
  6734. which can be auto-detected. This macro ensures that they are never enabled.
  6735. \subsection{LTC\_FAST}
  6736. This mode (auto-detected with x86\_32, x86\_64 platforms with GCC or CLANG) configures various routines such as ctr\_encrypt() or
  6737. cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
  6738. cutting down the overhead of the respective functions.
  6739. This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
  6740. it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_FAST
  6741. is not \textit{portable} since unaligned accesses are not covered by the ISO C specifications.
  6742. In practice however, you can use it on pretty much any platform (even MIPS) with care.
  6743. By design the \textit{fast} mode functions won't get unaligned on their own. For instance, if you call ctr\_encrypt() right after calling
  6744. ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only. However, if you
  6745. call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
  6746. cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
  6747. whole word XOR operations. These operations will be unaligned.
  6748. The simplest precaution is to make sure you process all data in power of two blocks and handle \textit{remainder} at the end. e.g. If you are
  6749. CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.
  6750. \index{LTC\_FAST\_TYPE}
  6751. If you do plan on using the \textit{LTC\_FAST} mode, a \textit{LTC\_FAST\_TYPE} type which resolves to an optimal sized
  6752. data type you can perform integer operations with is required. For the auto-detected platforms this type will be defined automatically. Ideally it should be four or eight bytes since it must properly divide the size
  6753. of your block cipher (e.g. 16 bytes for AES). This means sadly if you're on a platform with 57--bit words (or something) you can't
  6754. use this mode. So sad.
  6755. \subsection{LTC\_NO\_ASM}
  6756. When this has been defined the library will not use any inline assembler. Only a few platforms support assembler inlines but various versions of ICC and GCC
  6757. cannot handle all of the assembler functions.
  6758. \subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
  6759. There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
  6760. self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
  6761. dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
  6762. cipher and a hash function.
  6763. Also see technical note number five for more details.
  6764. \subsection{LTC\_EASY}
  6765. When defined the library is configured to build fewer algorithms and modes. Mostly it sticks to NIST and ANSI approved algorithms. See
  6766. the header file \textit{tomcrypt\_custom.h} for more details. It is meant to provide literally an easy method of trimming the library
  6767. build to the most minimum of useful functionality.
  6768. \subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
  6769. Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
  6770. to allow some trade-offs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
  6771. requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
  6772. defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
  6773. tables at a cost of 4KB of memory. The cipher will be much faster as a result.
  6774. When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
  6775. useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
  6776. will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
  6777. it will not speed up the encryption or decryption functions.
  6778. \subsection{GCM\_TABLES}
  6779. When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
  6780. It also increases the initialization time and is not suitable when you are going to use a key a few times only.
  6781. \subsection{GCM\_TABLES\_SSE2}
  6782. \index{SSE2}
  6783. When defined GCM will use the SSE2 instructions to perform the $GF(2^x)$ multiply using 16 128--bit XOR operations. It shaves a few cycles per byte
  6784. of GCM output on both the AMD64 and Intel Pentium 4 platforms. Requires GCC and an SSE2 equipped platform.
  6785. \subsection{LTC\_SMALL\_CODE}
  6786. When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
  6787. These variants are slower but can save quite a bit of code space.
  6788. \subsection{LTC\_PTHREAD}
  6789. When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
  6790. it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
  6791. Generally the rule of thumb is to setup the tables once at startup and then leave them be. This added build flag simply makes updating
  6792. the tables safer.
  6793. \subsection{LTC\_ECC\_TIMING\_RESISTANT}
  6794. When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
  6795. algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
  6796. where timing side channels pose a significant threat.
  6797. This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_ECC\_TIMING\_RESISTANT}.
  6798. \subsection{LTC\_RSA\_BLINDING}
  6799. When this has been defined the RSA modular exponentiation will use a blinding algorithm to improve timing resistance.
  6800. This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_BLINDING}.
  6801. \subsection{LTC\_RSA\_CRT\_HARDENING}
  6802. When this has been defined the RSA modular exponentiation will do some sanity checks regarding the CRT parameters and the operations' results.
  6803. This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_CRT\_HARDENING}.
  6804. \subsection{Math Descriptors}
  6805. The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
  6806. libraries. When \textbf{GMP\_DESC}, \textbf{LTM\_DESC}, or \textbf{TFM\_DESC} are defined
  6807. descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.
  6808. In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
  6809. to tell the program which library to use. Only one of the USE flags can be defined at once.
  6810. \index{GMP\_DESC} \index{USE\_GMP} \index{LTM\_DESC} \index{TFM\_DESC} \index{USE\_LTM} \index{USE\_TFM}
  6811. \begin{small}
  6812. \begin{verbatim}
  6813. make -f makefile.shared install timing CFLAGS="-DGMP_DESC -DLTM_DESC -DTFM_DESC -DUSE_TFM" \
  6814. EXTRALIBS="-lgmp -ltommath -ltfm"
  6815. \end{verbatim}
  6816. \end{small}
  6817. That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.
  6818. To avoid random crashes and run--time errors in the form \texttt{LTC\_ARGCHK 'ltc\_mp.name != NULL' failure ...}, one has to
  6819. initialise the \texttt{ltc\_mp} struct. This can be done in multiple ways as shown below.
  6820. \index{crypt\_mp\_init()}
  6821. \begin{verbatim}
  6822. int crypt_mp_init(const char* mpi);
  6823. \end{verbatim}
  6824. To ease the setup of a specific math descriptor, in cases where the library was compiled with support for multiple MPI libraries,
  6825. the function \textit{crypt\_mp\_init()} is provided.
  6826. It takes a string to the desired MPI library to use as an argument.
  6827. The three default MPI libraries are identified as follows, \textit{LibTomMath} as \texttt{"ltm"}, \textit{TomsFastmath} as \texttt{"tfm"}
  6828. and the \textit{GNU Multi Precision Arithmetic Library} as \texttt{"gmp"}.
  6829. The identification happens case-insensitive and only on the first character.
  6830. \begin{verbatim}
  6831. #include <tomcrypt.h>
  6832. int main(void)
  6833. {
  6834. /* set it by hand */
  6835. ltc_mp = gmp_desc;
  6836. ltc_mp = ltm_desc;
  6837. ltc_mp = tfm_desc;
  6838. /* use the provided API */
  6839. crypt_mp_init("GMP");
  6840. crypt_mp_init("LibTomMath");
  6841. crypt_mp_init("TomsFastMath");
  6842. }
  6843. \end{verbatim}
  6844. \chapter{Optimizations}
  6845. \mysection{Introduction}
  6846. The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash, PRNG or bignum library and the dependent API will not
  6847. require updating. This has the nice benefit that one can add ciphers (etc.) not have to re--write portions of the API. For the most part, LibTomCrypt has also been written
  6848. to be highly portable and easy to build out of the box on pretty much any platform. As such there are no assembler inlines throughout the code, I make no assumptions
  6849. about the platform, etc...
  6850. That works well for most cases but there are times where performance is of the essence. This API allows optimized routines to be dropped in--place of the existing
  6851. portable routines. For instance, hand optimized assembler versions of AES could be provided. Any existing function that uses the cipher could automatically use
  6852. the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
  6853. At the heart of this flexibility is the \textit{descriptor} system. A descriptor is essentially just a C \textit{struct} which describes the algorithm and provides pointers
  6854. to functions that do the required work. For a given class of operation (e.g. cipher, hash, prng, bignum) the functions of a descriptor have identical prototypes which makes
  6855. development simple. In most dependent routines all an end developer has to do is register\_XXX() the descriptor and they are set.
  6856. \mysection{Ciphers}
  6857. The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
  6858. \label{sec:cipherdesc}
  6859. \begin{small}
  6860. \begin{verbatim}
  6861. struct ltc_cipher_descriptor {
  6862. /** name of cipher */
  6863. char *name;
  6864. /** internal ID */
  6865. unsigned char ID;
  6866. /** min keysize (octets) */
  6867. int min_key_length,
  6868. /** max keysize (octets) */
  6869. max_key_length,
  6870. /** block size (octets) */
  6871. block_length,
  6872. /** default number of rounds */
  6873. default_rounds;
  6874. /** Setup the cipher
  6875. @param key The input symmetric key
  6876. @param keylen The length of the input key (octets)
  6877. @param num_rounds The requested number of rounds (0==default)
  6878. @param skey [out] The destination of the scheduled key
  6879. @return CRYPT_OK if successful
  6880. */
  6881. int (*setup)(const unsigned char *key,
  6882. int keylen,
  6883. int num_rounds,
  6884. symmetric_key *skey);
  6885. /** Encrypt a block
  6886. @param pt The plaintext
  6887. @param ct [out] The ciphertext
  6888. @param skey The scheduled key
  6889. @return CRYPT_OK if successful
  6890. */
  6891. int (*ecb_encrypt)(const unsigned char *pt,
  6892. unsigned char *ct,
  6893. symmetric_key *skey);
  6894. /** Decrypt a block
  6895. @param ct The ciphertext
  6896. @param pt [out] The plaintext
  6897. @param skey The scheduled key
  6898. @return CRYPT_OK if successful
  6899. */
  6900. int (*ecb_decrypt)(const unsigned char *ct,
  6901. unsigned char *pt,
  6902. symmetric_key *skey);
  6903. /** Test the block cipher
  6904. @return CRYPT_OK if successful,
  6905. CRYPT_NOP if self-testing has been disabled
  6906. */
  6907. int (*test)(void);
  6908. /** Terminate the context
  6909. @param skey The scheduled key
  6910. */
  6911. void (*done)(symmetric_key *skey);
  6912. /** Determine a key size
  6913. @param keysize [in/out] The size of the key desired
  6914. The suggested size
  6915. @return CRYPT_OK if successful
  6916. */
  6917. int (*keysize)(int *keysize);
  6918. /** Accelerators **/
  6919. /** Accelerated ECB encryption
  6920. @param pt Plaintext
  6921. @param ct Ciphertext
  6922. @param blocks The number of complete blocks to process
  6923. @param skey The scheduled key context
  6924. @return CRYPT_OK if successful
  6925. */
  6926. int (*accel_ecb_encrypt)(const unsigned char *pt,
  6927. unsigned char *ct,
  6928. unsigned long blocks,
  6929. symmetric_key *skey);
  6930. /** Accelerated ECB decryption
  6931. @param pt Plaintext
  6932. @param ct Ciphertext
  6933. @param blocks The number of complete blocks to process
  6934. @param skey The scheduled key context
  6935. @return CRYPT_OK if successful
  6936. */
  6937. int (*accel_ecb_decrypt)(const unsigned char *ct,
  6938. unsigned char *pt,
  6939. unsigned long blocks,
  6940. symmetric_key *skey);
  6941. /** Accelerated CBC encryption
  6942. @param pt Plaintext
  6943. @param ct Ciphertext
  6944. @param blocks The number of complete blocks to process
  6945. @param IV The initial value (input/output)
  6946. @param skey The scheduled key context
  6947. @return CRYPT_OK if successful
  6948. */
  6949. int (*accel_cbc_encrypt)(const unsigned char *pt,
  6950. unsigned char *ct,
  6951. unsigned long blocks,
  6952. unsigned char *IV,
  6953. symmetric_key *skey);
  6954. /** Accelerated CBC decryption
  6955. @param pt Plaintext
  6956. @param ct Ciphertext
  6957. @param blocks The number of complete blocks to process
  6958. @param IV The initial value (input/output)
  6959. @param skey The scheduled key context
  6960. @return CRYPT_OK if successful
  6961. */
  6962. int (*accel_cbc_decrypt)(const unsigned char *ct,
  6963. unsigned char *pt,
  6964. unsigned long blocks,
  6965. unsigned char *IV,
  6966. symmetric_key *skey);
  6967. /** Accelerated CTR encryption
  6968. @param pt Plaintext
  6969. @param ct Ciphertext
  6970. @param blocks The number of complete blocks to process
  6971. @param IV The initial value (input/output)
  6972. @param mode little or big endian counter (mode=0 or mode=1)
  6973. @param skey The scheduled key context
  6974. @return CRYPT_OK if successful
  6975. */
  6976. int (*accel_ctr_encrypt)(const unsigned char *pt,
  6977. unsigned char *ct,
  6978. unsigned long blocks,
  6979. unsigned char *IV,
  6980. int mode,
  6981. symmetric_key *skey);
  6982. /** Accelerated LRW
  6983. @param pt Plaintext
  6984. @param ct Ciphertext
  6985. @param blocks The number of complete blocks to process
  6986. @param IV The initial value (input/output)
  6987. @param tweak The LRW tweak
  6988. @param skey The scheduled key context
  6989. @return CRYPT_OK if successful
  6990. */
  6991. int (*accel_lrw_encrypt)(const unsigned char *pt,
  6992. unsigned char *ct,
  6993. unsigned long blocks,
  6994. unsigned char *IV,
  6995. const unsigned char *tweak,
  6996. symmetric_key *skey);
  6997. /** Accelerated LRW
  6998. @param ct Ciphertext
  6999. @param pt Plaintext
  7000. @param blocks The number of complete blocks to process
  7001. @param IV The initial value (input/output)
  7002. @param tweak The LRW tweak
  7003. @param skey The scheduled key context
  7004. @return CRYPT_OK if successful
  7005. */
  7006. int (*accel_lrw_decrypt)(const unsigned char *ct,
  7007. unsigned char *pt,
  7008. unsigned long blocks,
  7009. unsigned char *IV,
  7010. const unsigned char *tweak,
  7011. symmetric_key *skey);
  7012. /** Accelerated CCM packet (one-shot)
  7013. @param key The secret key to use
  7014. @param keylen The length of the secret key (octets)
  7015. @param uskey A previously scheduled key [can be NULL]
  7016. @param nonce The session nonce [use once]
  7017. @param noncelen The length of the nonce
  7018. @param header The header for the session
  7019. @param headerlen The length of the header (octets)
  7020. @param pt [out] The plaintext
  7021. @param ptlen The length of the plaintext (octets)
  7022. @param ct [out] The ciphertext
  7023. @param tag [out] The destination tag
  7024. @param taglen [in/out] The max size and resulting size
  7025. of the authentication tag
  7026. @param direction Encrypt or Decrypt direction (0 or 1)
  7027. @return CRYPT_OK if successful
  7028. */
  7029. int (*accel_ccm_memory)(
  7030. const unsigned char *key, unsigned long keylen,
  7031. symmetric_key *uskey,
  7032. const unsigned char *nonce, unsigned long noncelen,
  7033. const unsigned char *header, unsigned long headerlen,
  7034. unsigned char *pt, unsigned long ptlen,
  7035. unsigned char *ct,
  7036. unsigned char *tag, unsigned long *taglen,
  7037. int direction);
  7038. /** Accelerated GCM packet (one shot)
  7039. @param key The secret key
  7040. @param keylen The length of the secret key
  7041. @param IV The initialization vector
  7042. @param IVlen The length of the initialization vector
  7043. @param adata The additional authentication data (header)
  7044. @param adatalen The length of the adata
  7045. @param pt The plaintext
  7046. @param ptlen The length of the plaintext/ciphertext
  7047. @param ct The ciphertext
  7048. @param tag [out] The MAC tag
  7049. @param taglen [in/out] The MAC tag length
  7050. @param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
  7051. @return CRYPT_OK on success
  7052. */
  7053. int (*accel_gcm_memory)(
  7054. const unsigned char *key, unsigned long keylen,
  7055. const unsigned char *IV, unsigned long IVlen,
  7056. const unsigned char *adata, unsigned long adatalen,
  7057. unsigned char *pt, unsigned long ptlen,
  7058. unsigned char *ct,
  7059. unsigned char *tag, unsigned long *taglen,
  7060. int direction);
  7061. /** Accelerated one shot OMAC
  7062. @param key The secret key
  7063. @param keylen The key length (octets)
  7064. @param in The message
  7065. @param inlen Length of message (octets)
  7066. @param out [out] Destination for tag
  7067. @param outlen [in/out] Initial and final size of out
  7068. @return CRYPT_OK on success
  7069. */
  7070. int (*omac_memory)(
  7071. const unsigned char *key, unsigned long keylen,
  7072. const unsigned char *in, unsigned long inlen,
  7073. unsigned char *out, unsigned long *outlen);
  7074. /** Accelerated one shot XCBC
  7075. @param key The secret key
  7076. @param keylen The key length (octets)
  7077. @param in The message
  7078. @param inlen Length of message (octets)
  7079. @param out [out] Destination for tag
  7080. @param outlen [in/out] Initial and final size of out
  7081. @return CRYPT_OK on success
  7082. */
  7083. int (*xcbc_memory)(
  7084. const unsigned char *key, unsigned long keylen,
  7085. const unsigned char *in, unsigned long inlen,
  7086. unsigned char *out, unsigned long *outlen);
  7087. /** Accelerated one shot F9
  7088. @param key The secret key
  7089. @param keylen The key length (octets)
  7090. @param in The message
  7091. @param inlen Length of message (octets)
  7092. @param out [out] Destination for tag
  7093. @param outlen [in/out] Initial and final size of out
  7094. @return CRYPT_OK on success
  7095. @remark Requires manual padding
  7096. */
  7097. int (*f9_memory)(
  7098. const unsigned char *key, unsigned long keylen,
  7099. const unsigned char *in, unsigned long inlen,
  7100. unsigned char *out, unsigned long *outlen);
  7101. };
  7102. \end{verbatim}
  7103. \end{small}
  7104. \subsection{Name}
  7105. \index{find\_cipher()}
  7106. The \textit{name} parameter specifies the name of the cipher. This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
  7107. tables.
  7108. \subsection{Internal ID}
  7109. This is a single byte Internal ID you can use to distinguish ciphers from each other.
  7110. \subsection{Key Lengths}
  7111. The minimum key length is \textit{min\_key\_length} and is measured in octets. Similarly the maximum key length is \textit{max\_key\_length}. They can be equal
  7112. and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
  7113. \subsection{Block Length}
  7114. The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.
  7115. \subsection{Rounds}
  7116. Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit{default\_rounds}.
  7117. \subsection{Setup}
  7118. To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets \textit{key} of length \textit{keylen} octets. The user
  7119. can specify the number of rounds they want through \textit{num\_rounds} where $num\_rounds = 0$ means use the default. The destination of a scheduled key is stored
  7120. in \textit{skey}.
  7121. Inside the \textit{symmetric\_key} union there is a \textit{void *data} which you can use to allocate data if you need a data structure that does not fit with the existing
  7122. ones provided. Just make sure in your \textit{done()} function that you free the allocated memory.
  7123. \subsection{Single block ECB}
  7124. To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided. The plaintext and ciphertext buffers are allowed to overlap so you
  7125. must make sure you do not overwrite the output before you are finished with the input.
  7126. \subsection{Testing}
  7127. The test() function is used to self--test the \textit{device}. It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly. You may return
  7128. \textbf{CRYPT\_NOP} to indicate that no testing was performed.
  7129. \subsection{Key Sizing}
  7130. Occasionally, a function will want to find a suitable key size to use since the input is oddly sized. The keysize() function is for this case. It accepts a
  7131. pointer to an integer which represents the desired size. The function then has to match it to the exact or a lower key size that is valid for the cipher. For
  7132. example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer. It must not round up and must return an error if the keysize
  7133. cannot be mapped to a valid key size for the cipher.
  7134. \subsection{Acceleration}
  7135. The next set of functions cover the accelerated functionality of the cipher descriptor. Any combination of these functions may be set to \textbf{NULL} to indicate
  7136. it is not supported. In those cases the software defaults are used (using the single ECB block routines).
  7137. \subsubsection{Accelerated ECB}
  7138. These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks. These functions are accessed
  7139. through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The \textit{blocks} count is the number of complete blocks to process.
  7140. \subsubsection{Accelerated CBC}
  7141. These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
  7142. The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CBC initialization vector. It is an input upon calling this function and must be
  7143. updated by the function before returning.
  7144. \subsubsection{Accelerated CTR}
  7145. This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
  7146. The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CTR counter vector. It is an input upon calling this function and must be
  7147. updated by the function before returning. The \textit{mode} value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or
  7148. little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.
  7149. This function (and the way it's called) differs from the other two since ctr\_encrypt() allows any size input plaintext. The accelerator will only be
  7150. called if the following conditions are met.
  7151. \begin{enumerate}
  7152. \item The accelerator is present
  7153. \item The CTR pad is empty
  7154. \item The remaining length of the input to process is greater than or equal to the block size.
  7155. \end{enumerate}
  7156. The \textit{CTR pad} is empty when a multiple (including zero) blocks of text have been processed. That is, if you pass in seven bytes to AES--CTR mode you would have to
  7157. pass in a minimum of nine extra bytes before the accelerator could be called. The CTR accelerator must increment the counter (and store it back into the
  7158. buffer provided) before encrypting it to create the pad.
  7159. The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
  7160. \subsubsection{Accelerated LRW}
  7161. These functions are meant for accelerated LRW. They process blocks of input in lengths of multiples of 16 octets. They must accept the \textit{IV} and \textit{tweak}
  7162. state variables and updated them prior to returning. Note that you may want to disable \textbf{LRW\_TABLES} in \textit{tomcrypt\_custom.h} if you intend
  7163. to use accelerators for LRW.
  7164. While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_setiv() more efficient.
  7165. Note that calling lrw\_done() will only invoke the cipher\_descriptor[].done() function on the \textit{symmetric\_key} parameter of the LRW state. That means
  7166. if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
  7167. the plugin solely to do LRW with the cipher. That way cipher\_descriptor[].setup() means to init LRW resources and cipher\_descriptor[].done() means to
  7168. free them.
  7169. \subsubsection{Accelerated CCM}
  7170. This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
  7171. by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance). This
  7172. function MUST support both key passing methods.
  7173. \begin{center}
  7174. \begin{small}
  7175. \begin{tabular}{|r|r|l|}
  7176. \hline \textbf{key} & \textbf{uskey} & \textbf{Source of key} \\
  7177. \hline NULL & NULL & Error, not supported \\
  7178. \hline non-NULL & NULL & Use key, do a key schedule \\
  7179. \hline NULL & non-NULL & Use uskey, key schedule not required \\
  7180. \hline non-NULL & non-NULL & Use uskey, key schedule not required \\
  7181. \hline
  7182. \end{tabular}
  7183. \end{small}
  7184. \end{center}
  7185. \index{ccm\_memory()} This function is called when the user calls ccm\_memory().
  7186. \subsubsection{Accelerated GCM}
  7187. \index{gcm\_memory()}
  7188. This function is meant for accelerated GCM encryption or decryption. It processes the entire packet in one call. Note that the setup() function will not
  7189. be called prior to this. This function must handle scheduling the key provided on its own. It is called when the user calls gcm\_memory().
  7190. \subsubsection{Accelerated OMAC}
  7191. \index{omac\_memory()}
  7192. This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_memory().
  7193. \subsubsection{Accelerated XCBC-MAC}
  7194. \index{xcbc\_memory()}
  7195. This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_memory().
  7196. \subsubsection{Accelerated F9}
  7197. \index{f9\_memory()}
  7198. This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory(). Like f9\_memory(), it requires
  7199. the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.
  7200. \mysection{One--Way Hashes}
  7201. The hash functions are accessed through the ltc\_hash\_descriptor structure.
  7202. \begin{small}
  7203. \begin{verbatim}
  7204. struct ltc_hash_descriptor {
  7205. /** name of hash */
  7206. char *name;
  7207. /** internal ID */
  7208. unsigned char ID;
  7209. /** Size of digest in octets */
  7210. unsigned long hashsize;
  7211. /** Input block size in octets */
  7212. unsigned long blocksize;
  7213. /** ASN.1 OID */
  7214. unsigned long OID[16];
  7215. /** Length of DER encoding */
  7216. unsigned long OIDlen;
  7217. /** Init a hash state
  7218. @param hash The hash to initialize
  7219. @return CRYPT_OK if successful
  7220. */
  7221. int (*init)(hash_state *hash);
  7222. /** Process a block of data
  7223. @param hash The hash state
  7224. @param in The data to hash
  7225. @param inlen The length of the data (octets)
  7226. @return CRYPT_OK if successful
  7227. */
  7228. int (*process)( hash_state *hash,
  7229. const unsigned char *in,
  7230. unsigned long inlen);
  7231. /** Produce the digest and store it
  7232. @param hash The hash state
  7233. @param out [out] The destination of the digest
  7234. @return CRYPT_OK if successful
  7235. */
  7236. int (*done)( hash_state *hash,
  7237. unsigned char *out);
  7238. /** Self-test
  7239. @return CRYPT_OK if successful,
  7240. CRYPT_NOP if self-tests have been disabled
  7241. */
  7242. int (*test)(void);
  7243. /* accelerated hmac callback: if you need to-do
  7244. multiple packets just use the generic hmac_memory
  7245. and provide a hash callback
  7246. */
  7247. int (*hmac_block)(const unsigned char *key,
  7248. unsigned long keylen,
  7249. const unsigned char *in,
  7250. unsigned long inlen,
  7251. unsigned char *out,
  7252. unsigned long *outlen);
  7253. };
  7254. \end{verbatim}
  7255. \end{small}
  7256. \subsection{Name}
  7257. This is the name the hash is known by and what find\_hash() will look for.
  7258. \subsection{Internal ID}
  7259. This is the internal ID byte used to distinguish the hash from other hashes.
  7260. \subsection{Digest Size}
  7261. The \textit{hashsize} variable indicates the length of the output in octets.
  7262. \subsection{Block Size}
  7263. The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
  7264. invocation.
  7265. \subsection{OID Identifier}
  7266. This is the universal ASN.1 Object Identifier for the hash.
  7267. \subsection{Initialization}
  7268. The init function initializes the hash and prepares it to process message bytes.
  7269. \subsection{Process}
  7270. This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
  7271. guaranteed to be a multiple of the block size in length.
  7272. \subsection{Done}
  7273. The done function terminates the hash and returns the message digest.
  7274. \subsection{Acceleration}
  7275. A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
  7276. \subsection{HMAC Acceleration}
  7277. The hmac\_block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_memory() if present. If you need
  7278. to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_memory() as provided in LibTomCrypt.
  7279. \mysection{Pseudo--Random Number Generators}
  7280. The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
  7281. \begin{small}
  7282. \begin{verbatim}
  7283. struct ltc_prng_descriptor {
  7284. /** Name of the PRNG */
  7285. char *name;
  7286. /** size in bytes of exported state */
  7287. int export_size;
  7288. /** Start a PRNG state
  7289. @param prng [out] The state to initialize
  7290. @return CRYPT_OK if successful
  7291. */
  7292. int (*start)(prng_state *prng);
  7293. /** Add entropy to the PRNG
  7294. @param in The entropy
  7295. @param inlen Length of the entropy (octets)
  7296. @param prng The PRNG state
  7297. @return CRYPT_OK if successful
  7298. */
  7299. int (*add_entropy)(const unsigned char *in,
  7300. unsigned long inlen,
  7301. prng_state *prng);
  7302. /** Ready a PRNG state to read from
  7303. @param prng The PRNG state to ready
  7304. @return CRYPT_OK if successful
  7305. */
  7306. int (*ready)(prng_state *prng);
  7307. /** Read from the PRNG
  7308. @param out [out] Where to store the data
  7309. @param outlen Length of data desired (octets)
  7310. @param prng The PRNG state to read from
  7311. @return Number of octets read
  7312. */
  7313. unsigned long (*read)(unsigned char *out,
  7314. unsigned long outlen,
  7315. prng_state *prng);
  7316. /** Terminate a PRNG state
  7317. @param prng The PRNG state to terminate
  7318. @return CRYPT_OK if successful
  7319. */
  7320. int (*done)(prng_state *prng);
  7321. /** Export a PRNG state
  7322. @param out [out] The destination for the state
  7323. @param outlen [in/out] The max size and resulting size
  7324. @param prng The PRNG to export
  7325. @return CRYPT_OK if successful
  7326. */
  7327. int (*pexport)(unsigned char *out,
  7328. unsigned long *outlen,
  7329. prng_state *prng);
  7330. /** Import a PRNG state
  7331. @param in The data to import
  7332. @param inlen The length of the data to import (octets)
  7333. @param prng The PRNG to initialize/import
  7334. @return CRYPT_OK if successful
  7335. */
  7336. int (*pimport)(const unsigned char *in,
  7337. unsigned long inlen,
  7338. prng_state *prng);
  7339. /** Self-test the PRNG
  7340. @return CRYPT_OK if successful,
  7341. CRYPT_NOP if self-testing has been disabled
  7342. */
  7343. int (*test)(void);
  7344. };
  7345. \end{verbatim}
  7346. \end{small}
  7347. \subsection{Name}
  7348. The name by which find\_prng() will find the PRNG.
  7349. \subsection{Export Size}
  7350. When an PRNG state is to be exported for future use you specify the space required in this variable.
  7351. \subsection{Start}
  7352. Initialize the PRNG and make it ready to accept entropy.
  7353. \subsection{Entropy Addition}
  7354. Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
  7355. \subsection{Ready}
  7356. This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
  7357. on the specific PRNG used.
  7358. \subsection{Read}
  7359. Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
  7360. if it does as many protocols do not retry reads and will fail on the first try.
  7361. \subsection{Done}
  7362. Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
  7363. \subsection{Exporting and Importing}
  7364. An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume \textit{the same session}
  7365. but should at least maintain the same level of state entropy.
  7366. \mysection{BigNum Math Descriptors}
  7367. The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
  7368. it hasn't proven hard to write \textit{glue} to use math libraries so far. The basic descriptor looks like.
  7369. \begin{small}
  7370. \begin{verbatim}
  7371. /** math descriptor */
  7372. typedef struct {
  7373. /** Name of the math provider */
  7374. char *name;
  7375. /** Bits per digit, amount of bits must fit in an unsigned long */
  7376. int bits_per_digit;
  7377. /* ---- init/deinit functions ---- */
  7378. /** initialize a bignum
  7379. @param a The number to initialize
  7380. @return CRYPT_OK on success
  7381. */
  7382. int (*init)(void **a);
  7383. /** init copy
  7384. @param dst The number to initialize and write to
  7385. @param src The number to copy from
  7386. @return CRYPT_OK on success
  7387. */
  7388. int (*init_copy)(void **dst, void *src);
  7389. /** deinit
  7390. @param a The number to free
  7391. @return CRYPT_OK on success
  7392. */
  7393. void (*deinit)(void *a);
  7394. /* ---- data movement ---- */
  7395. /** negate
  7396. @param src The number to negate
  7397. @param dst The destination
  7398. @return CRYPT_OK on success
  7399. */
  7400. int (*neg)(void *src, void *dst);
  7401. /** copy
  7402. @param src The number to copy from
  7403. @param dst The number to write to
  7404. @return CRYPT_OK on success
  7405. */
  7406. int (*copy)(void *src, void *dst);
  7407. /* ---- trivial low level functions ---- */
  7408. /** set small constant
  7409. @param a Number to write to
  7410. @param n Source upto bits_per_digit (actually meant for very small constants)
  7411. @return CRYPT_OK on success
  7412. */
  7413. int (*set_int)(void *a, unsigned long n);
  7414. /** get small constant
  7415. @param a Small number to read,
  7416. only fetches up to bits_per_digit from the number
  7417. @return The lower bits_per_digit of the integer (unsigned)
  7418. */
  7419. unsigned long (*get_int)(void *a);
  7420. /** get digit n
  7421. @param a The number to read from
  7422. @param n The number of the digit to fetch
  7423. @return The bits_per_digit sized n'th digit of a
  7424. */
  7425. ltc_mp_digit (*get_digit)(void *a, int n);
  7426. /** Get the number of digits that represent the number
  7427. @param a The number to count
  7428. @return The number of digits used to represent the number
  7429. */
  7430. int (*get_digit_count)(void *a);
  7431. /** compare two integers
  7432. @param a The left side integer
  7433. @param b The right side integer
  7434. @return LTC_MP_LT if a < b,
  7435. LTC_MP_GT if a > b and
  7436. LTC_MP_EQ otherwise. (signed comparison)
  7437. */
  7438. int (*compare)(void *a, void *b);
  7439. /** compare against int
  7440. @param a The left side integer
  7441. @param b The right side integer (upto bits_per_digit)
  7442. @return LTC_MP_LT if a < b,
  7443. LTC_MP_GT if a > b and
  7444. LTC_MP_EQ otherwise. (signed comparison)
  7445. */
  7446. int (*compare_d)(void *a, unsigned long n);
  7447. /** Count the number of bits used to represent the integer
  7448. @param a The integer to count
  7449. @return The number of bits required to represent the integer
  7450. */
  7451. int (*count_bits)(void * a);
  7452. /** Count the number of LSB bits which are zero
  7453. @param a The integer to count
  7454. @return The number of contiguous zero LSB bits
  7455. */
  7456. int (*count_lsb_bits)(void *a);
  7457. /** Compute a power of two
  7458. @param a The integer to store the power in
  7459. @param n The power of two you want to store (a = 2^n)
  7460. @return CRYPT_OK on success
  7461. */
  7462. int (*twoexpt)(void *a , int n);
  7463. /* ---- radix conversions ---- */
  7464. /** read ascii string
  7465. @param a The integer to store into
  7466. @param str The string to read
  7467. @param radix The radix the integer has been represented in (2-64)
  7468. @return CRYPT_OK on success
  7469. */
  7470. int (*read_radix)(void *a, const char *str, int radix);
  7471. /** write number to string
  7472. @param a The integer to store
  7473. @param str The destination for the string
  7474. @param radix The radix the integer is to be represented in (2-64)
  7475. @return CRYPT_OK on success
  7476. */
  7477. int (*write_radix)(void *a, char *str, int radix);
  7478. /** get size as unsigned char string
  7479. @param a The integer to get the size (when stored in array of octets)
  7480. @return The length of the integer in octets
  7481. */
  7482. unsigned long (*unsigned_size)(void *a);
  7483. /** store an integer as an array of octets
  7484. @param src The integer to store
  7485. @param dst The buffer to store the integer in
  7486. @return CRYPT_OK on success
  7487. */
  7488. int (*unsigned_write)(void *src, unsigned char *dst);
  7489. /** read an array of octets and store as integer
  7490. @param dst The integer to load
  7491. @param src The array of octets
  7492. @param len The number of octets
  7493. @return CRYPT_OK on success
  7494. */
  7495. int (*unsigned_read)( void *dst,
  7496. unsigned char *src,
  7497. unsigned long len);
  7498. /* ---- basic math ---- */
  7499. /** add two integers
  7500. @param a The first source integer
  7501. @param b The second source integer
  7502. @param c The destination of "a + b"
  7503. @return CRYPT_OK on success
  7504. */
  7505. int (*add)(void *a, void *b, void *c);
  7506. /** add two integers
  7507. @param a The first source integer
  7508. @param b The second source integer
  7509. (single digit of upto bits_per_digit in length)
  7510. @param c The destination of "a + b"
  7511. @return CRYPT_OK on success
  7512. */
  7513. int (*addi)(void *a, unsigned long b, void *c);
  7514. /** subtract two integers
  7515. @param a The first source integer
  7516. @param b The second source integer
  7517. @param c The destination of "a - b"
  7518. @return CRYPT_OK on success
  7519. */
  7520. int (*sub)(void *a, void *b, void *c);
  7521. /** subtract two integers
  7522. @param a The first source integer
  7523. @param b The second source integer
  7524. (single digit of upto bits_per_digit in length)
  7525. @param c The destination of "a - b"
  7526. @return CRYPT_OK on success
  7527. */
  7528. int (*subi)(void *a, unsigned long b, void *c);
  7529. /** multiply two integers
  7530. @param a The first source integer
  7531. @param b The second source integer
  7532. (single digit of upto bits_per_digit in length)
  7533. @param c The destination of "a * b"
  7534. @return CRYPT_OK on success
  7535. */
  7536. int (*mul)(void *a, void *b, void *c);
  7537. /** multiply two integers
  7538. @param a The first source integer
  7539. @param b The second source integer
  7540. (single digit of upto bits_per_digit in length)
  7541. @param c The destination of "a * b"
  7542. @return CRYPT_OK on success
  7543. */
  7544. int (*muli)(void *a, unsigned long b, void *c);
  7545. /** Square an integer
  7546. @param a The integer to square
  7547. @param b The destination
  7548. @return CRYPT_OK on success
  7549. */
  7550. int (*sqr)(void *a, void *b);
  7551. /** Divide an integer
  7552. @param a The dividend
  7553. @param b The divisor
  7554. @param c The quotient (can be NULL to signify don't care)
  7555. @param d The remainder (can be NULL to signify don't care)
  7556. @return CRYPT_OK on success
  7557. */
  7558. int (*mpdiv)(void *a, void *b, void *c, void *d);
  7559. /** divide by two
  7560. @param a The integer to divide (shift right)
  7561. @param b The destination
  7562. @return CRYPT_OK on success
  7563. */
  7564. int (*div_2)(void *a, void *b);
  7565. /** Get remainder (small value)
  7566. @param a The integer to reduce
  7567. @param b The modulus (upto bits_per_digit in length)
  7568. @param c The destination for the residue
  7569. @return CRYPT_OK on success
  7570. */
  7571. int (*modi)(void *a, unsigned long b, unsigned long *c);
  7572. /** gcd
  7573. @param a The first integer
  7574. @param b The second integer
  7575. @param c The destination for (a, b)
  7576. @return CRYPT_OK on success
  7577. */
  7578. int (*gcd)(void *a, void *b, void *c);
  7579. /** lcm
  7580. @param a The first integer
  7581. @param b The second integer
  7582. @param c The destination for [a, b]
  7583. @return CRYPT_OK on success
  7584. */
  7585. int (*lcm)(void *a, void *b, void *c);
  7586. /** Modular multiplication
  7587. @param a The first source
  7588. @param b The second source
  7589. @param c The modulus
  7590. @param d The destination (a*b mod c)
  7591. @return CRYPT_OK on success
  7592. */
  7593. int (*mulmod)(void *a, void *b, void *c, void *d);
  7594. /** Modular squaring
  7595. @param a The first source
  7596. @param b The modulus
  7597. @param c The destination (a*a mod b)
  7598. @return CRYPT_OK on success
  7599. */
  7600. int (*sqrmod)(void *a, void *b, void *c);
  7601. /** Modular inversion
  7602. @param a The value to invert
  7603. @param b The modulus
  7604. @param c The destination (1/a mod b)
  7605. @return CRYPT_OK on success
  7606. */
  7607. int (*invmod)(void *, void *, void *);
  7608. /* ---- reduction ---- */
  7609. /** setup Montgomery
  7610. @param a The modulus
  7611. @param b The destination for the reduction digit
  7612. @return CRYPT_OK on success
  7613. */
  7614. int (*montgomery_setup)(void *a, void **b);
  7615. /** get normalization value
  7616. @param a The destination for the normalization value
  7617. @param b The modulus
  7618. @return CRYPT_OK on success
  7619. */
  7620. int (*montgomery_normalization)(void *a, void *b);
  7621. /** reduce a number
  7622. @param a The number [and dest] to reduce
  7623. @param b The modulus
  7624. @param c The value "b" from montgomery_setup()
  7625. @return CRYPT_OK on success
  7626. */
  7627. int (*montgomery_reduce)(void *a, void *b, void *c);
  7628. /** clean up (frees memory)
  7629. @param a The value "b" from montgomery_setup()
  7630. @return CRYPT_OK on success
  7631. */
  7632. void (*montgomery_deinit)(void *a);
  7633. /* ---- exponentiation ---- */
  7634. /** Modular exponentiation
  7635. @param a The base integer
  7636. @param b The power (can be negative) integer
  7637. @param c The modulus integer
  7638. @param d The destination
  7639. @return CRYPT_OK on success
  7640. */
  7641. int (*exptmod)(void *a, void *b, void *c, void *d);
  7642. /** Primality testing
  7643. @param a The integer to test
  7644. @param b The number of Miller-Rabin tests that shall be executed
  7645. @param c The destination of the result (FP_YES if prime)
  7646. @return CRYPT_OK on success
  7647. */
  7648. int (*isprime)(void *a, int b, int *c);
  7649. /* ---- (optional) ecc point math ---- */
  7650. /** ECC GF(p) point multiplication (from the NIST curves)
  7651. @param k The integer to multiply the point by
  7652. @param G The point to multiply
  7653. @param R The destination for kG
  7654. @param modulus The modulus for the field
  7655. @param map Boolean indicated whether to map back to affine or not
  7656. (can be ignored if you work in affine only)
  7657. @return CRYPT_OK on success
  7658. */
  7659. int (*ecc_ptmul)( void *k,
  7660. ecc_point *G,
  7661. ecc_point *R,
  7662. void *modulus,
  7663. int map);
  7664. /** ECC GF(p) point addition
  7665. @param P The first point
  7666. @param Q The second point
  7667. @param R The destination of P + Q
  7668. @param modulus The modulus
  7669. @param mp The "b" value from montgomery_setup()
  7670. @return CRYPT_OK on success
  7671. */
  7672. int (*ecc_ptadd)(ecc_point *P,
  7673. ecc_point *Q,
  7674. ecc_point *R,
  7675. void *modulus,
  7676. void *mp);
  7677. /** ECC GF(p) point double
  7678. @param P The first point
  7679. @param R The destination of 2P
  7680. @param modulus The modulus
  7681. @param mp The "b" value from montgomery_setup()
  7682. @return CRYPT_OK on success
  7683. */
  7684. int (*ecc_ptdbl)(ecc_point *P,
  7685. ecc_point *R,
  7686. void *modulus,
  7687. void *mp);
  7688. /** ECC mapping from projective to affine,
  7689. currently uses (x,y,z) => (x/z^2, y/z^3, 1)
  7690. @param P The point to map
  7691. @param modulus The modulus
  7692. @param mp The "b" value from montgomery_setup()
  7693. @return CRYPT_OK on success
  7694. @remark The mapping can be different but keep in mind a
  7695. ecc_point only has three integers (x,y,z) so if
  7696. you use a different mapping you have to make it fit.
  7697. */
  7698. int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
  7699. /** Computes kA*A + kB*B = C using Shamir's Trick
  7700. @param A First point to multiply
  7701. @param kA What to multiple A by
  7702. @param B Second point to multiply
  7703. @param kB What to multiple B by
  7704. @param C [out] Destination point (can overlap with A or B)
  7705. @param modulus Modulus for curve
  7706. @return CRYPT_OK on success
  7707. */
  7708. int (*ecc_mul2add)(ecc_point *A, void *kA,
  7709. ecc_point *B, void *kB,
  7710. ecc_point *C,
  7711. void *modulus);
  7712. /* ---- (optional) rsa optimized math (for internal CRT) ---- */
  7713. /** RSA Key Generation
  7714. @param prng An active PRNG state
  7715. @param wprng The index of the PRNG desired
  7716. @param size The size of the key in octets
  7717. @param e The "e" value (public key).
  7718. e==65537 is a good choice
  7719. @param key [out] Destination of a newly created private key pair
  7720. @return CRYPT_OK if successful, upon error all allocated ram is freed
  7721. */
  7722. int (*rsa_keygen)(prng_state *prng,
  7723. int wprng,
  7724. int size,
  7725. long e,
  7726. rsa_key *key);
  7727. /** RSA exponentiation
  7728. @param in The octet array representing the base
  7729. @param inlen The length of the input
  7730. @param out The destination (to be stored in an octet array format)
  7731. @param outlen The length of the output buffer and the resulting size
  7732. (zero padded to the size of the modulus)
  7733. @param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
  7734. @param key The RSA key to use
  7735. @return CRYPT_OK on success
  7736. */
  7737. int (*rsa_me)(const unsigned char *in, unsigned long inlen,
  7738. unsigned char *out, unsigned long *outlen, int which,
  7739. rsa_key *key);
  7740. /* ---- basic math continued ---- */
  7741. /** Modular addition
  7742. @param a The first source
  7743. @param b The second source
  7744. @param c The modulus
  7745. @param d The destination (a + b mod c)
  7746. @return CRYPT_OK on success
  7747. */
  7748. int (*addmod)(void *a, void *b, void *c, void *d);
  7749. /** Modular substraction
  7750. @param a The first source
  7751. @param b The second source
  7752. @param c The modulus
  7753. @param d The destination (a - b mod c)
  7754. @return CRYPT_OK on success
  7755. */
  7756. int (*submod)(void *a, void *b, void *c, void *d);
  7757. /* ---- misc stuff ---- */
  7758. /** Make a pseudo-random mpi
  7759. @param a The mpi to make random
  7760. @param size The desired length
  7761. @return CRYPT_OK on success
  7762. */
  7763. int (*rand)(void *a, int size);
  7764. } ltc_math_descriptor;
  7765. \end{verbatim}
  7766. \end{small}
  7767. Most of the functions are fairly straightforward and do not need documentation. We'll cover the basic conventions of the API and then explain the accelerated functions.
  7768. \subsection{Conventions}
  7769. All \textit{bignums} are accessed through an opaque \textit{void *} data type. You must internally cast the pointer if you need to access members of your bignum structure. During
  7770. the init calls a \textit{void **} will be passed where you allocate your structure and set the pointer then initialize the number to zero. During the deinit calls you must
  7771. free the bignum as well as the structure you allocated to place it in.
  7772. All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $c \leftarrow ab$.
  7773. All functions (except where noted otherwise) return \textbf{CRYPT\_OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
  7774. The digit routines (including functions with the \textit{i} suffix) use a \textit{ltc\_mp\_digit} to represent the digit. If your internal digit is larger than this you must
  7775. then partition your digits. Note that if your digit is smaller than an \textit{ltc\_mp\_digit} that is also acceptable as the \textit{bits\_per\_digit} parameter will specify this.
  7776. \subsubsection{ltc\_mp\_digit}
  7777. \index{ltc\_mp\_digit}
  7778. Depending on the archtitecture \textit{ltc\_mp\_digit} is either a $32$- or $64$-bit long \textit{unsigned} data type.
  7779. \subsection{ECC Functions}
  7780. The ECC system in LibTomCrypt is based off the NIST recommended curves over $GF(p)$ and is used to implement ECDSA and ECDH. The ECC functions work with
  7781. the \textbf{ecc\_point} structure and assumes the points are stored in Jacobian projective format.
  7782. \begin{verbatim}
  7783. /** A point on a ECC curve, stored in Jacobian format such
  7784. that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */
  7785. typedef struct {
  7786. /** The x co-ordinate */
  7787. void *x;
  7788. /** The y co-ordinate */
  7789. void *y;
  7790. /** The z co-ordinate */
  7791. void *z;
  7792. } ecc_point;
  7793. \end{verbatim}
  7794. All ECC functions must use this mapping system. The only exception is when you remap all ECC callbacks which will allow you to have more control
  7795. over how the ECC math will be implemented. Out of the box you only have three parameters per point to use $(x, y, z)$ however, these are just void pointers.
  7796. They could point to anything you want. The only further exception is the export functions which expects the values to be in affine format.
  7797. \subsubsection{Point Multiply}
  7798. This will multiply the point $G$ by the scalar $k$ and store the result in the point $R$. The value should be mapped to affine only if $map$ is set to one.
  7799. \subsubsection{Point Addition}
  7800. This will add the point $P$ to the point $Q$ and store it in the point $R$. The $mp$ parameter is the \textit{b} value from the montgomery\_setup() call. The input points
  7801. may be in either affine (with $z = 1$) or projective format and the output point is always projective.
  7802. \subsubsection{Point Mapping}
  7803. This will map the point $P$ back from projective to affine. The output point $P$ must be of the form $(x, y, 1)$.
  7804. \subsubsection{Shamir's Trick}
  7805. \index{Shamir's Trick}
  7806. \index{ltc\_ecc\_mul2add()}
  7807. To accelerate ECDSA verification the library provides a built--in function called ltc\_ecc\_mul2add(). This performs two point multiplications and an addition in
  7808. roughly the time of one point multiplication. It is called from ecc\_verify\_hash() if an accelerator is not present. The acclerator function must allow the points to
  7809. overlap (e.g., $A \leftarrow k_1A + k_2B$) and must return the final point in affine format.
  7810. \subsection{RSA Functions}
  7811. The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
  7812. private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
  7813. \begin{verbatim}
  7814. /** RSA PKCS style key */
  7815. typedef struct Rsa_key {
  7816. /** Type of key, PK_PRIVATE or PK_PUBLIC */
  7817. int type;
  7818. /** The public exponent */
  7819. void *e;
  7820. /** The private exponent */
  7821. void *d;
  7822. /** The modulus */
  7823. void *N;
  7824. /** The p factor of N */
  7825. void *p;
  7826. /** The q factor of N */
  7827. void *q;
  7828. /** The 1/q mod p CRT param */
  7829. void *qP;
  7830. /** The d mod (p - 1) CRT param */
  7831. void *dP;
  7832. /** The d mod (q - 1) CRT param */
  7833. void *dQ;
  7834. } rsa_key;
  7835. \end{verbatim}
  7836. The call reads the \textit{in} buffer as an unsigned char array in big endian format. Then it performs the exponentiation and stores the output in big endian format
  7837. to the \textit{out} buffer. The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes). For example,
  7838. for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
  7839. Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \#1 v2.1 specification.
  7840. \mysection{Deprecated API functions}
  7841. \subsection{After v1.18.0}
  7842. \index{init\_LTM()} \index{init\_TFM()} \index{init\_GMP()}
  7843. \begin{verbatim}
  7844. void init_LTM(void);
  7845. void init_TFM(void);
  7846. void init_GMP(void);
  7847. \end{verbatim}
  7848. These three MPI init functions have been introduced in version 1.18.0 and have been deprecated in the same version in favor of \textit{crypt\_mp\_init()}.
  7849. \newpage
  7850. \markboth{Index}{Index}
  7851. \input{crypt.ind}
  7852. \end{document}
  7853. % ref: $Format:%D$
  7854. % git commit: $Format:%H$
  7855. % commit time: $Format:%ai$