crypt.tex 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253
  1. \documentclass[a4paper]{book}
  2. \usepackage{hyperref}
  3. \usepackage{makeidx}
  4. \usepackage{amssymb}
  5. \usepackage{color}
  6. \usepackage{alltt}
  7. \usepackage{graphicx}
  8. \usepackage{layout}
  9. \def\union{\cup}
  10. \def\intersect{\cap}
  11. \def\getsrandom{\stackrel{\rm R}{\gets}}
  12. \def\cross{\times}
  13. \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
  14. \def\catn{$\|$}
  15. \def\divides{\hspace{0.3em} | \hspace{0.3em}}
  16. \def\nequiv{\not\equiv}
  17. \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
  18. \def\lcm{{\rm lcm}}
  19. \def\gcd{{\rm gcd}}
  20. \def\log{{\rm log}}
  21. \def\ord{{\rm ord}}
  22. \def\abs{{\mathit abs}}
  23. \def\rep{{\mathit rep}}
  24. \def\mod{{\mathit\ mod\ }}
  25. \renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
  26. \newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
  27. \newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
  28. \def\Or{{\rm\ or\ }}
  29. \def\And{{\rm\ and\ }}
  30. \def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
  31. \def\implies{\Rightarrow}
  32. \def\undefined{{\rm ``undefined"}}
  33. \def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
  34. \let\oldphi\phi
  35. \def\phi{\varphi}
  36. \def\Pr{{\rm Pr}}
  37. \newcommand{\str}[1]{{\mathbf{#1}}}
  38. \def\F{{\mathbb F}}
  39. \def\N{{\mathbb N}}
  40. \def\Z{{\mathbb Z}}
  41. \def\R{{\mathbb R}}
  42. \def\C{{\mathbb C}}
  43. \def\Q{{\mathbb Q}}
  44. \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
  45. \def\gap{\vspace{0.5ex}}
  46. \makeindex
  47. \begin{document}
  48. \title{LibTomCrypt \\ Version 1.01}
  49. \author{Tom St Denis \\
  50. \\
  51. [email protected] \\
  52. http://libtomcrypt.org
  53. }
  54. \maketitle
  55. This text and source code library are both hereby placed in the public domain. This book has been
  56. formatted for A4 paper using the \LaTeX{} {\em book} macro package.
  57. \vspace{10cm}
  58. \begin{flushright}Open Source. Open Academia. Open Minds.
  59. \mbox{ }
  60. Tom St Denis,
  61. Phone: 1-613-836-3160
  62. 111 Banning Rd
  63. Kanata, Ontario
  64. K2L 1C3
  65. Canada
  66. \end{flushright}
  67. \newpage
  68. \tableofcontents
  69. \chapter{Introduction}
  70. \section{What is the LibTomCrypt?}
  71. LibTomCrypt is a portable ISO C cryptographic library that is meant to be a toolset for cryptographers who are
  72. designing a cryptosystem. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
  73. public key cryptography (via PKCS \#1 RSA, DH or ECCDH) and a plethora of support
  74. routines.
  75. The library was designed such that new ciphers/hashes/PRNGs can be added at runtime and the existing API
  76. (and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
  77. block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
  78. also performs extensive parameter error checking to prevent any number of runtime exploits or errors.
  79. \subsection{What the library IS for?}
  80. The library serves as a toolkit for developers who have to solve cryptographic problems. Out of the box LibTomCrypt
  81. does not process SSL or OpenPGP messages, it doesn't read x.591 certificates or write PEM encoded data. It does, however,
  82. provide all of the tools required to build such functionality. LibTomCrypt was designed to be a flexible library that
  83. was not tied to any particular cryptographic problem.
  84. \section{Why did I write it?}
  85. You may be wondering, ``Tom, why did you write a crypto library. I already have one.''. Well the reason falls into
  86. two categories:
  87. \begin{enumerate}
  88. \item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
  89. \item It was (still is) good coding practice.
  90. \end{enumerate}
  91. The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
  92. {\bf own} crypto library and hopefully along the way others will appreciate the work.
  93. With this library all core functions (ciphers, hashes, prngs) have the {\bf exact} same prototype definition. They all load
  94. and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
  95. on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with my library you
  96. know how to use Safer+ or RC6 or Serpent or ... as well. With all of the core functions there are central descriptor tables
  97. that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime. That means your
  98. application can support all ciphers/hashes/prngs without changing the source code.
  99. Not only did I strive to make a consistent and simple API to work with but I also strived to make the library
  100. configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
  101. without having to use configure scripts. This means that the library will work with platforms where development
  102. tools may be limited (e.g. no autoconf).
  103. On top of making the build simple and the API approachable I've also strived for a reasonably high level of
  104. robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
  105. arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
  106. with ``cycles per byte'' timings that are comparable (and often favourable) to other libraries such as OpenSSL and
  107. Crypto++.
  108. \subsection{Modular}
  109. The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes and
  110. pseudo--random number generators (PRNG) are all used within the API through ``descriptor'' tables which
  111. are essentially structures with pointers to functions. While you can still call particular functions
  112. directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
  113. usage of the library.
  114. For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
  115. that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
  116. is write a descriptor and the few support routines required for the device. After that the rest of the
  117. API can make use of it without change. Similiarly imagine a few years down the road when AES2
  118. (\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
  119. with zero modifications to the end applications provided they are written properly.
  120. This flexibility within the library means it can be used with any combination of primitive algorithms and
  121. unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
  122. mode routines for every single cipher. That means every time you add or remove a cipher from the library
  123. you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
  124. are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
  125. the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
  126. can make use of the cipher right away.
  127. \section{License}
  128. All of the source code except for the following files have been written by the author or donated to the project
  129. under a public domain license:
  130. \begin{enumerate}
  131. \item rc2.c
  132. \end{enumerate}
  133. `mpi.c'' was originally written by Michael Fromberger ([email protected]) but has since been replaced with
  134. my LibTomMath library which is public domain.
  135. ``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.
  136. The project is hereby released as public domain.
  137. \section{Patent Disclosure}
  138. The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
  139. of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
  140. They can be removed from a build by simply commenting out the two appropriate lines in ``mycrypt\_custom.h''. The rest
  141. of the ciphers and hashes are patent free or under patents that have since expired.
  142. The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
  143. the ciphers you just can't advertise that you are doing so.
  144. \section{Thanks}
  145. I would like to give thanks to the following people (in no particular order) for helping me develop this project from
  146. early on:
  147. \begin{enumerate}
  148. \item Richard van de Laarschot
  149. \item Richard Heathfield
  150. \item Ajay K. Agrawal
  151. \item Brian Gladman
  152. \item Svante Seleborg
  153. \item Clay Culver
  154. \item Jason Klapste
  155. \item Dobes Vandermeer
  156. \item Daniel Richards
  157. \item Wayne Scott
  158. \item Andrew Tyler
  159. \item Sky Schulz
  160. \item Christopher Imes
  161. \end{enumerate}
  162. There have been quite a few other people as well. Please check the change log to see who else has contributed from
  163. time to time.
  164. \chapter{The Application Programming Interface (API)}
  165. \section{Introduction}
  166. \index{CRYPT\_ERROR} \index{CRYPT\_OK}
  167. In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
  168. that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful or one of the many error codes
  169. if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
  170. commented upon. When a function does return a CRYPT error code it can be translated into a string with
  171. \index{error\_to\_string()}
  172. \begin{verbatim}
  173. const char *error_to_string(int err);
  174. \end{verbatim}
  175. An example of handling an error is:
  176. \begin{verbatim}
  177. void somefunc(void)
  178. {
  179. int err;
  180. /* call a cryptographic function */
  181. if ((err = some_crypto_function(...)) != CRYPT_OK) {
  182. printf("A crypto error occured, %s\n", error_to_string(err));
  183. /* perform error handling */
  184. }
  185. /* continue on if no error occured */
  186. }
  187. \end{verbatim}
  188. There is no initialization routine for the library and for the most part the code is thread safe. The only thread
  189. related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
  190. that is not an issue.
  191. To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``tomcrypt.h'' like so:
  192. \begin{verbatim}
  193. #include <tomcrypt.h>
  194. int main(void) {
  195. return 0;
  196. }
  197. \end{verbatim}
  198. The header file ``tomcrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and
  199. ``ltc\_tommath.h'' (the bignum library routines).
  200. \section{Macros}
  201. There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
  202. 32/64-bit words in little/big endian format. The macros are:
  203. \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
  204. \begin{small}
  205. \begin{center}
  206. \begin{tabular}{|c|c|c|}
  207. \hline STORE32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
  208. \hline STORE64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
  209. \hline LOAD32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
  210. \hline LOAD64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
  211. \hline STORE32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
  212. \hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
  213. \hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
  214. \hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
  215. \hline BSWAP(x) & {\bf unsigned long} x & Swaps byte order (32--bits only) \\
  216. \hline
  217. \end{tabular}
  218. \end{center}
  219. \end{small}
  220. There are 32 and 64-bit cyclic rotations as well:
  221. \index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
  222. \begin{center}
  223. \begin{tabular}{|c|c|c|}
  224. \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 31$ \\
  225. \hline ROLc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 31$ \\
  226. \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 31$ \\
  227. \hline RORc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 31$ \\
  228. \hline && \\
  229. \hline ROL64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 63$ \\
  230. \hline ROL64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 63$ \\
  231. \hline ROR64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 63$ \\
  232. \hline ROR64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 63$ \\
  233. \hline
  234. \end{tabular}
  235. \end{center}
  236. \section{Functions with Variable Length Output}
  237. Certain functions such as (for example) ``rsa\_export()'' give an output that is variable length. To prevent buffer overflows you
  238. must pass it the length of the buffer\footnote{Extensive error checking is not in place but it will be in future releases so it is a good idea to follow through with these guidelines.} where
  239. the output will be stored. For example:
  240. \begin{small}
  241. \begin{verbatim}
  242. #include <tomcrypt.h>
  243. int main(void) {
  244. rsa_key key;
  245. unsigned char buffer[1024];
  246. unsigned long x;
  247. int err;
  248. /* ... Make up the RSA key somehow ... */
  249. /* lets export the key, set x to the size of the output buffer */
  250. x = sizeof(buffer);
  251. if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
  252. printf("Export error: %s\n", error_to_string(err));
  253. return -1;
  254. }
  255. /* if rsa_export() was successful then x will have the size of the output */
  256. printf("RSA exported key takes %d bytes\n", x);
  257. /* ... do something with the buffer */
  258. return 0;
  259. }
  260. \end{verbatim}
  261. \end{small}
  262. In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
  263. indicating a buffer overflow would have occurred. If the function succeeds it stores the length of the output
  264. back into ``x'' so that the calling application will know how many bytes were used.
  265. \section{Functions that need a PRNG}
  266. \index{Pseudo Random Number Generator} \index{PRNG}
  267. Certain functions such as ``rsa\_make\_key()'' require a Pseudo Random Number Generator (PRNG). These functions do not setup
  268. the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
  269. Certain PRNG algorithms do not require a ``prng\_state'' argument (sprng for example). The ``prng\_state'' argument
  270. may be passed as \textbf{NULL} in such situations.
  271. \section{Functions that use Arrays of Octets}
  272. Most functions require inputs that are arrays of the data type ``unsigned char''. Whether it is a symmetric key, IV
  273. for a chaining mode or public key packet it is assumed that regardless of the actual size of ``unsigned char'' only the
  274. lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine
  275. you must pass it in (a pointer to) an array of 32 ``unsigned char'' variables. Certain routines
  276. (such as SAFER+) take special care to work properly on platforms where an ``unsigned char'' is not eight bits.
  277. For the purposes of this library the term ``byte'' will refer to an octet or eight bit word. Typically an array of
  278. type ``byte'' will be synonymous with an array of type ``unsigned char''.
  279. \chapter{Symmetric Block Ciphers}
  280. \section{Core Functions}
  281. LibTomCrypt provides several block ciphers with an ECB block mode interface. It's important to first note that you
  282. should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode
  283. or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
  284. the API to grow in a modular fashion.
  285. \subsection{Key Scheduling}
  286. All ciphers store their scheduled keys in a single data type called ``symmetric\_key''. This allows all ciphers to
  287. have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
  288. allocation and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers provide five visible
  289. functions which are (given that XXX is the name of the cipher):
  290. \index{Cipher Setup}
  291. \begin{verbatim}
  292. int XXX_setup(const unsigned char *key, int keylen, int rounds,
  293. symmetric_key *skey);
  294. \end{verbatim}
  295. The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
  296. The number of rounds can be set to zero to use the default, which is generally a good idea.
  297. If the function returns successfully the variable ``skey'' will have a scheduled key stored in it. It's important to note
  298. that you should only used this scheduled key with the intended cipher. For example, if you call ``blowfish\_setup()'' do not
  299. pass the scheduled key onto ``rc5\_ecb\_encrypt()''. All setup functions do not allocate memory off the heap so when you are
  300. done with a key you can simply discard it (e.g. they can be on the stack).
  301. \subsection{ECB Encryption and Decryption}
  302. To encrypt or decrypt a block in ECB mode there are these two function classes
  303. \index{Cipher Encrypt} \index{Cipher Decrypt}
  304. \begin{verbatim}
  305. void XXX_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
  306. symmetric_key *skey);
  307. void XXX_ecb_decrypt(const unsigned char *ct, unsigned char *pt,
  308. symmetric_key *skey);
  309. \end{verbatim}
  310. These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
  311. which cipher you are using.} and store the result where you want it. It is possible that the input and output buffer are
  312. the same buffer. For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and
  313. ``ct''\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. To test a particular
  314. cipher against test vectors\footnote{As published in their design papers.} call the self-test function
  315. \subsection{Self--Testing}
  316. \index{Cipher Testing}
  317. \begin{verbatim}
  318. int XXX_test(void);
  319. \end{verbatim}
  320. This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
  321. based upon.
  322. \subsection{Key Sizing}
  323. For each cipher there is a function which will help find a desired key size:
  324. \begin{verbatim}
  325. int XXX_keysize(int *keysize);
  326. \end{verbatim}
  327. Essentially it will round the input keysize in ``keysize'' down to the next appropriate key size. This function
  328. return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
  329. \begin{small}
  330. \begin{verbatim}
  331. #include <tomcrypt.h>
  332. int main(void)
  333. {
  334. int keysize, err;
  335. /* now given a 20 byte key what keysize does Twofish want to use? */
  336. keysize = 20;
  337. if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
  338. printf("Error getting key size: %s\n", error_to_string(err));
  339. return -1;
  340. }
  341. printf("Twofish suggested a key size of %d\n", keysize);
  342. return 0;
  343. }
  344. \end{verbatim}
  345. \end{small}
  346. This should indicate a keysize of sixteen bytes is suggested.
  347. \subsection{Cipher Termination}
  348. When you are finished with a cipher you can de--initialize it with the done function.
  349. \begin{verbatim}
  350. void XXX_done(symmetric_key *skey);
  351. \end{verbatim}
  352. For the software based ciphers within LibTomCrypt this function will not do anything. However, user supplied
  353. cipher descriptors may require calls to it for resource management. To be compliant all functions which call a cipher
  354. setup function must also call the respective cipher done function when finished.
  355. \subsection{Simple Encryption Demonstration}
  356. An example snippet that encodes a block with Blowfish in ECB mode is below.
  357. \begin{small}
  358. \begin{verbatim}
  359. #include <tomcrypt.h>
  360. int main(void)
  361. {
  362. unsigned char pt[8], ct[8], key[8];
  363. symmetric_key skey;
  364. int err;
  365. /* ... key is loaded appropriately in ``key'' ... */
  366. /* ... load a block of plaintext in ``pt'' ... */
  367. /* schedule the key */
  368. if ((err = blowfish_setup(key, /* the key we will use */
  369. 8, /* key is 8 bytes (64-bits) long */
  370. 0, /* 0 == use default # of rounds */
  371. &skey) /* where to put the scheduled key */
  372. ) != CRYPT_OK) {
  373. printf("Setup error: %s\n", error_to_string(err));
  374. return -1;
  375. }
  376. /* encrypt the block */
  377. blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
  378. ct, /* store encrypted data here */
  379. &skey); /* our previously scheduled key */
  380. /* now ct holds the encrypted version of pt */
  381. /* decrypt the block */
  382. blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
  383. pt, /* store decrypted data here */
  384. &skey); /* our previously scheduled key */
  385. /* now we have decrypted ct to the original plaintext in pt */
  386. /* Terminate the cipher context */
  387. blowfish_done(&skey);
  388. return 0;
  389. }
  390. \end{verbatim}
  391. \end{small}
  392. \section{Key Sizes and Number of Rounds}
  393. \index{Symmetric Keys}
  394. As a general rule of thumb do not use symmetric keys under 80 bits if you can. Only a few of the ciphers support smaller
  395. keys (mainly for test vectors anyways). Ideally your application should be making at least 256 bit keys. This is not
  396. because you're supposed to be paranoid. It's because if your PRNG has a bias of any sort the more bits the better. For
  397. example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
  398. total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
  399. were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
  400. only 53 bits of entropy.
  401. The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
  402. rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
  403. ciphers are configured such that the default number of rounds provide adequate security for the given block and key
  404. size.
  405. \section{The Cipher Descriptors}
  406. \index{Cipher Descriptor}
  407. To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_descriptor''. An element
  408. of this array has the following format:
  409. \begin{small}
  410. \begin{verbatim}
  411. struct _cipher_descriptor {
  412. char *name;
  413. unsigned char ID;
  414. int min_key_length,
  415. max_key_length,
  416. block_length,
  417. default_rounds;
  418. int (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
  419. void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
  420. void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
  421. int (*test)(void);
  422. void (*done)(symmetric_key *skey);
  423. int (*keysize)(int *keysize);
  424. void (*accel_ecb_encrypt)(const unsigned char *pt,
  425. unsigned char *ct,
  426. unsigned long blocks, symmetric_key *skey);
  427. void (*accel_ecb_decrypt)(const unsigned char *ct,
  428. unsigned char *pt,
  429. unsigned long blocks, symmetric_key *skey);
  430. void (*accel_cbc_encrypt)(const unsigned char *pt,
  431. unsigned char *ct,
  432. unsigned long blocks, unsigned char *IV,
  433. symmetric_key *skey);
  434. void (*accel_cbc_decrypt)(const unsigned char *ct,
  435. unsigned char *pt,
  436. unsigned long blocks, unsigned char *IV,
  437. symmetric_key *skey);
  438. void (*accel_ctr_encrypt)(const unsigned char *pt,
  439. unsigned char *ct,
  440. unsigned long blocks, unsigned char *IV,
  441. int mode, symmetric_key *skey);
  442. void (*accel_ccm_memory)(
  443. const unsigned char *key, unsigned long keylen,
  444. const unsigned char *nonce, unsigned long noncelen,
  445. const unsigned char *header, unsigned long headerlen,
  446. unsigned char *pt, unsigned long ptlen,
  447. unsigned char *ct,
  448. unsigned char *tag, unsigned long *taglen,
  449. int direction);
  450. };
  451. \end{verbatim}
  452. \end{small}
  453. Where ``name'' is the lower case ASCII version of the name. The fields ``min\_key\_length'' and ``max\_key\_length''
  454. are the minimum and maximum key sizes in bytes. The ``block\_length'' member is the block size of the cipher
  455. in bytes. As a good rule of thumb it is assumed that the cipher supports
  456. the min and max key lengths but not always everything in between. The ``default\_rounds'' field is the default number
  457. of rounds that will be used.
  458. The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
  459. marked when ``name'' equals {\bf NULL}.
  460. As of this release the current cipher\_descriptors elements are
  461. \index{Cipher descriptor table}
  462. \begin{small}
  463. \begin{center}
  464. \begin{tabular}{|c|c|c|c|c|c|}
  465. \hline Name & Descriptor Name & Block Size & Key Range & Rounds \\
  466. \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
  467. \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
  468. \hline RC2 & rc2\_desc & 8 & 8 $\ldots$ 128 & 16 \\
  469. \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
  470. \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
  471. \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
  472. \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
  473. & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
  474. \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
  475. \hline DES & des\_desc & 8 & 7 & 16 \\
  476. \hline 3DES (EDE mode) & des3\_desc & 8 & 21 & 16 \\
  477. \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
  478. \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
  479. \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
  480. \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
  481. \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
  482. \hline
  483. \end{tabular}
  484. \end{center}
  485. \end{small}
  486. \subsection{Notes}
  487. \begin{small}
  488. \begin{enumerate}
  489. \item
  490. For AES (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
  491. rijndael\_desc and rijndael\_enc\_desc provide the cipher named ``rijndael''. The descriptors aes\_desc and
  492. aes\_enc\_desc provide the cipher name ``aes''. Functionally both ``rijndael'' and ``aes'' are the same cipher. The
  493. only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with ``enc''
  494. in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
  495. and tables. The decryption and self--test function pointers of both ``encrypt only'' descriptors are set to \textbf{NULL} and
  496. should not be called.
  497. The ``encrypt only'' descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
  498. as EAX, PMAC and OMAC only require the encryption function. So far this ``encrypt only'' functionality has only been implemented for
  499. Rijndael as it makes the most sense for this cipher.
  500. \item
  501. Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
  502. 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
  503. byte string from the real 7/21 byte key.
  504. \item
  505. Note that ``Twofish'' has additional configuration options that take place at build time. These options are found in
  506. the file ``mycrypt\_cfg.h''. The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
  507. to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
  508. key will require less ram but the resulting cipher will be slower. The second option is ``TWOFISH\_TABLES'' which when
  509. 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
  510. by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
  511. speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
  512. Twofish round function.
  513. \index{Twofish build options}
  514. \begin{small}
  515. \begin{center}
  516. \begin{tabular}{|l|l|l|}
  517. \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
  518. \hline undefined & undefined & Very fast, 4.2KB of ram. \\
  519. \hline undefined & defined & Faster keysetup, larger code. \\
  520. \hline defined & undefined & Very slow, 0.2KB of ram. \\
  521. \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
  522. \hline
  523. \end{tabular}
  524. \end{center}
  525. \end{small}
  526. \end{enumerate}
  527. \end{small}
  528. To work with the cipher\_descriptor array there is a function:
  529. \index{find\_cipher()}
  530. \begin{verbatim}
  531. int find_cipher(char *name)
  532. \end{verbatim}
  533. Which will search for a given name in the array. It returns negative one if the cipher is not found, otherwise it returns
  534. the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
  535. \begin{small}
  536. \begin{verbatim}
  537. #include <tomcrypt.h>
  538. int main(void)
  539. {
  540. unsigned char key[8];
  541. symmetric_key skey;
  542. int err;
  543. /* you must register a cipher before you use it */
  544. if (register_cipher(&blowfish_desc)) == -1) {
  545. printf("Unable to register Blowfish cipher.");
  546. return -1;
  547. }
  548. /* generic call to function (assuming the key in key[] was already setup) */
  549. if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) !=
  550. CRYPT_OK) {
  551. printf("Error setting up Blowfish: %s\n", error_to_string(err));
  552. return -1;
  553. }
  554. /* ... use cipher ... */
  555. }
  556. \end{verbatim}
  557. \end{small}
  558. A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function. In order
  559. to use a cipher with the descriptor table you must register it first using:
  560. \index{register\_cipher()}
  561. \begin{verbatim}
  562. int register_cipher(const struct _cipher_descriptor *cipher);
  563. \end{verbatim}
  564. Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
  565. 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
  566. than once it will just return the index of the first copy. To remove a cipher call:
  567. \index{unregister\_cipher()}
  568. \begin{verbatim}
  569. int unregister_cipher(const struct _cipher_descriptor *cipher);
  570. \end{verbatim}
  571. Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}. Consider:
  572. \begin{small}
  573. \begin{verbatim}
  574. #include <tomcrypt.h>
  575. int main(void)
  576. {
  577. int err;
  578. /* register the cipher */
  579. if (register_cipher(&rijndael_desc) == -1) {
  580. printf("Error registering Rijndael\n");
  581. return -1;
  582. }
  583. /* use Rijndael */
  584. /* remove it */
  585. if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
  586. printf("Error removing Rijndael: %s\n", error_to_string(err));
  587. return -1;
  588. }
  589. return 0;
  590. }
  591. \end{verbatim}
  592. \end{small}
  593. This snippet is a small program that registers only Rijndael only.
  594. \section{Symmetric Modes of Operations}
  595. \subsection{Background}
  596. A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
  597. size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
  598. $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
  599. \subsubsection{ECB Mode}
  600. \index{ECB mode}
  601. ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
  602. \begin{equation}
  603. C_i = E_k(P_i)
  604. \end{equation}
  605. This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
  606. than once.
  607. \subsubsection{CBC Mode}
  608. \index{CBC mode}
  609. CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
  610. It is given as:
  611. \begin{equation}
  612. C_i = E_k(P_i \oplus C_{i - 1})
  613. \end{equation}
  614. It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
  615. \subsubsection{CTR Mode}
  616. \index{CTR mode}
  617. CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
  618. treated as a large binary counter the CTR mode is given as:
  619. \begin{eqnarray}
  620. C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
  621. C_i = P_i \oplus E_k(C_{-1})
  622. \end{eqnarray}
  623. Where $W$ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initial vector is random for each message
  624. encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
  625. as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
  626. \subsubsection{CFB Mode}
  627. \index{CFB mode}
  628. CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
  629. \begin{eqnarray}
  630. C_i = P_i \oplus C_{-1} \nonumber \\
  631. C_{-1} = E_k(C_i)
  632. \end{eqnarray}
  633. Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
  634. to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
  635. blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
  636. \subsubsection{OFB Mode}
  637. \index{OFB mode}
  638. OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
  639. \begin{eqnarray}
  640. C_{-1} = E_k(C_{-1}) \nonumber \\
  641. C_i = P_i \oplus C_{-1}
  642. \end{eqnarray}
  643. Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
  644. buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
  645. \subsection{Choice of Mode}
  646. My personal preference is for the CTR mode since it has several key benefits:
  647. \begin{enumerate}
  648. \item No short cycles which is possible in the OFB and CFB modes.
  649. \item Provably as secure as the block cipher being used under a chosen plaintext attack.
  650. \item Technically does not require the decryption routine of the cipher.
  651. \item Allows random access to the plaintext.
  652. \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
  653. \end{enumerate}
  654. The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
  655. accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
  656. block of memory with either of the three modes.
  657. The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore they are less flexible than the
  658. other modes.
  659. \subsection{Initialization}
  660. \index{CBC Mode} \index{CTR Mode}
  661. \index{OFB Mode} \index{CFB Mode}
  662. The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
  663. you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
  664. use that mode. They have identical setup routines (except ECB mode for obvious reasons):
  665. \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
  666. \begin{verbatim}
  667. int XXX_start(int cipher, const unsigned char *IV,
  668. const unsigned char *key, int keylen,
  669. int num_rounds, symmetric_XXX *XXX);
  670. int ecb_start(int cipher, const unsigned char *key, int keylen,
  671. int num_rounds, symmetric_ECB *ecb);
  672. \end{verbatim}
  673. In each case ``cipher'' is the index into the cipher\_descriptor array of the cipher you want to use. The ``IV'' value is
  674. the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
  675. length as the block size\footnote{In otherwords the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
  676. of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
  677. parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call. The final parameter
  678. is a pointer to the structure you want to hold the information for the mode of operation.
  679. Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.
  680. \subsection{Encryption and Decryption}
  681. To actually encrypt or decrypt the following routines are provided:
  682. \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
  683. \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
  684. \begin{verbatim}
  685. int XXX_encrypt(const unsigned char *pt, unsigned char *ct,
  686. unsigned long len, symmetric_YYY *YYY);
  687. int XXX_decrypt(const unsigned char *ct, unsigned char *pt,
  688. unsigned long len, symmetric_YYY *YYY);
  689. \end{verbatim}
  690. Where ``XXX'' is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.
  691. In all cases ``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
  692. chunk sensitive. That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
  693. and end up with the same ciphertext. However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts. All
  694. five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
  695. In the ECB and CBC cases ``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
  696. zeroes or with whatever your protocol requires).
  697. To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
  698. and use the decrypt routine on all of the blocks.
  699. \subsection{IV Manipulation}
  700. To change or read the IV of a previously initialized chaining mode use the following two functions.
  701. \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
  702. \index{ctr\_setiv()} \index{ctr\_getiv()}
  703. \begin{verbatim}
  704. int XXX_getiv(unsigned char *IV, unsigned long *len, symmetric_XXX *XXX);
  705. int XXX_setiv(const unsigned char *IV, unsigned long len, symmetric_XXX *XXX);
  706. \end{verbatim}
  707. The XXX\_getiv() functions will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV
  708. stored in ``len''. The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
  709. of the IV passed in must be the size of the ciphers block size.
  710. The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
  711. \subsection{Stream Termination}
  712. To terminate an open stream call the done function.
  713. \index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
  714. \begin{verbatim}
  715. int XXX_done(symmetric_XXX *XXX);
  716. \end{verbatim}
  717. This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
  718. \subsection{Examples}
  719. \newpage
  720. \begin{small}
  721. \begin{verbatim}
  722. #include <tomcrypt.h>
  723. int main(void)
  724. {
  725. unsigned char key[16], IV[16], buffer[512];
  726. symmetric_CTR ctr;
  727. int x, err;
  728. /* register twofish first */
  729. if (register_cipher(&twofish_desc) == -1) {
  730. printf("Error registering cipher.\n");
  731. return -1;
  732. }
  733. /* somehow fill out key and IV */
  734. /* start up CTR mode */
  735. if ((err = ctr_start(
  736. find_cipher("twofish"), /* index of desired cipher */
  737. IV, /* the initial vector */
  738. key, /* the secret key */
  739. 16, /* length of secret key (16 bytes, 128 bits) */
  740. 0, /* 0 == default # of rounds */
  741. &ctr) /* where to store initialized CTR state */
  742. ) != CRYPT_OK) {
  743. printf("ctr_start error: %s\n", error_to_string(err));
  744. return -1;
  745. }
  746. /* somehow fill buffer than encrypt it */
  747. if ((err = ctr_encrypt( buffer, /* plaintext */
  748. buffer, /* ciphertext */
  749. sizeof(buffer), /* length of data to encrypt */
  750. &ctr) /* previously initialized CTR state */
  751. ) != CRYPT_OK) {
  752. printf("ctr_encrypt error: %s\n", error_to_string(err));
  753. return -1;
  754. }
  755. /* make use of ciphertext... */
  756. /* now we want to decrypt so let's use ctr_setiv */
  757. if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
  758. 16, /* the IV is 16 bytes long */
  759. &ctr) /* the ctr state we wish to modify */
  760. ) != CRYPT_OK) {
  761. printf("ctr_setiv error: %s\n", error_to_string(err));
  762. return -1;
  763. }
  764. if ((err = ctr_decrypt( buffer, /* ciphertext */
  765. buffer, /* plaintext */
  766. sizeof(buffer), /* length of data to encrypt */
  767. &ctr) /* previously initialized CTR state */
  768. ) != CRYPT_OK) {
  769. printf("ctr_decrypt error: %s\n", error_to_string(err));
  770. return -1;
  771. }
  772. /* terminate the stream */
  773. if ((err = ctr_done(&ctr)) != CRYPT_OK) {
  774. printf("ctr_done error: %s\n", error_to_string(err));
  775. return -1;
  776. }
  777. /* clear up and return */
  778. zeromem(key, sizeof(key));
  779. zeromem(&ctr, sizeof(ctr));
  780. return 0;
  781. }
  782. \end{verbatim}
  783. \end{small}
  784. \section{Encrypt and Authenticate Modes}
  785. \subsection{EAX Mode}
  786. LibTomCrypt provides support for a mode called EAX\footnote{See
  787. M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the
  788. way it was intended to be used by the designers. First a short description of what EAX mode is before I explain how to use it.
  789. EAX is a mode that requires a cipher, CTR and OMAC support and provides encryption and authentication\footnote{Note that since EAX only requires OMAC and CTR you may use ``encrypt only'' cipher descriptors with this mode.}.
  790. It is initialized with a random ``nonce'' that can be shared publicly as well as a ``header'' which can be fixed and public as well as a random
  791. secret symmetric key.
  792. The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages). It can
  793. be added at anytime during an EAX stream and is part of the authentication tag. That is, changes in the meta-data can
  794. be detected by changes in the output tag.
  795. The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
  796. called a ``tag'' is only emitted when the message is finished. In the interim though the user can process any arbitrary
  797. sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
  798. of operation.
  799. The mode is initialized with the following function.
  800. \index{eax\_init()}
  801. \begin{verbatim}
  802. int eax_init(eax_state *eax, int cipher,
  803. const unsigned char *key, unsigned long keylen,
  804. const unsigned char *nonce, unsigned long noncelen,
  805. const unsigned char *header, unsigned long headerlen);
  806. \end{verbatim}
  807. Where ``eax'' is the EAX state. ``cipher'' is the index of the desired cipher in the descriptor table.
  808. ``key'' is the shared secret symmetric key of length ``keylen''. ``nonce'' is the random public string of
  809. length ``noncelen''. ``header'' is the random (or fixed or \textbf{NULL}) header for the message of length
  810. ``headerlen''.
  811. When this function completes ``eax'' will be initialized such that you can now either have data decrypted or
  812. encrypted in EAX mode. Note that if ``headerlen'' is zero you may pass ``header'' as \textbf{NULL} to indicate
  813. there is no initial header data.
  814. To encrypt or decrypt data in a streaming mode use the following.
  815. \index{eax\_encrypt()} \index{eax\_decrypt()}
  816. \begin{verbatim}
  817. int eax_encrypt(eax_state *eax, const unsigned char *pt,
  818. unsigned char *ct, unsigned long length);
  819. int eax_decrypt(eax_state *eax, const unsigned char *ct,
  820. unsigned char *pt, unsigned long length);
  821. \end{verbatim}
  822. The function ``eax\_encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in
  823. ``ct''. Note that ``ct'' and ``pt'' may be the same region in memory. This function will also send the ciphertext
  824. through the OMAC function. The function ``eax\_decrypt'' decrypts ``ct'' and stores it in ``pt''. This also allows
  825. ``pt'' and ``ct'' to be the same region in memory.
  826. You cannot both encrypt or decrypt with the same ``eax'' context. For bi-directional communication you
  827. will need to initialize two EAX contexts (preferably with different headers and nonces).
  828. Note that both of these functions allow you to send the data in any granularity but the order is important. While
  829. the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
  830. EAX stream with the following.
  831. \index{eax\_addheader()}
  832. \begin{verbatim}
  833. int eax_addheader(eax_state *eax,
  834. const unsigned char *header, unsigned long length);
  835. \end{verbatim}
  836. This will add the ``length'' bytes from ``header'' to the given ``eax'' stream. Once the message is finished the
  837. ``tag'' (checksum) may be computed with the following function.
  838. \index{eax\_done()}
  839. \begin{verbatim}
  840. int eax_done(eax_state *eax,
  841. unsigned char *tag, unsigned long *taglen);
  842. \end{verbatim}
  843. This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''. The function
  844. then stores how many bytes of the tag were written out back into ``taglen''.
  845. The EAX mode code can be tested to ensure it matches the test vectors by calling the following function.
  846. \index{eax\_test()}
  847. \begin{verbatim}
  848. int eax_test(void);
  849. \end{verbatim}
  850. This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
  851. \begin{verbatim}
  852. #include <tomcrypt.h>
  853. int main(void)
  854. {
  855. int err;
  856. eax_state eax;
  857. unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
  858. unsigned long taglen;
  859. if (register_cipher(&rijndael_desc) == -1) {
  860. printf("Error registering Rijndael");
  861. return EXIT_FAILURE;
  862. }
  863. /* ... make up random nonce and key ... */
  864. /* initialize context */
  865. if ((err = eax_init( &eax, /* the context */
  866. find_cipher("rijndael"), /* cipher we want to use */
  867. nonce, /* our state nonce */
  868. 16, /* none is 16 bytes */
  869. "TestApp", /* example header, identifies this program */
  870. 7) /* length of the header */
  871. ) != CRYPT_OK) {
  872. printf("Error eax_init: %s", error_to_string(err));
  873. return EXIT_FAILURE;
  874. }
  875. /* now encrypt data, say in a loop or whatever */
  876. if ((err = eax_encrypt( &eax, /* eax context */
  877. pt, /* plaintext (source) */
  878. ct, /* ciphertext (destination) */
  879. sizeof(pt) /* size of plaintext */
  880. ) != CRYPT_OK) {
  881. printf("Error eax_encrypt: %s", error_to_string(err));
  882. return EXIT_FAILURE;
  883. }
  884. /* finish message and get authentication tag */
  885. taglen = sizeof(tag);
  886. if ((err = eax_done( &eax, /* eax context */
  887. tag, /* where to put tag */
  888. &taglen /* length of tag space */
  889. ) != CRYPT_OK) {
  890. printf("Error eax_done: %s", error_to_string(err));
  891. return EXIT_FAILURE;
  892. }
  893. /* now we have the authentication tag in "tag" and it's taglen bytes long */
  894. }
  895. \end{verbatim}
  896. You can also perform an entire EAX state on a block of memory in a single function call with the
  897. following functions.
  898. \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
  899. \begin{verbatim}
  900. int eax_encrypt_authenticate_memory(int cipher,
  901. const unsigned char *key, unsigned long keylen,
  902. const unsigned char *nonce, unsigned long noncelen,
  903. const unsigned char *header, unsigned long headerlen,
  904. const unsigned char *pt, unsigned long ptlen,
  905. unsigned char *ct,
  906. unsigned char *tag, unsigned long *taglen);
  907. int eax_decrypt_verify_memory(int cipher,
  908. const unsigned char *key, unsigned long keylen,
  909. const unsigned char *nonce, unsigned long noncelen,
  910. const unsigned char *header, unsigned long headerlen,
  911. const unsigned char *ct, unsigned long ctlen,
  912. unsigned char *pt,
  913. unsigned char *tag, unsigned long taglen,
  914. int *res);
  915. \end{verbatim}
  916. Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
  917. have the same meaning as with those respective functions.
  918. 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
  919. the tag it computed while decrypting the message. If the tags match then it stores a $1$ in ``res'', otherwise it stores a $0$.
  920. \subsection{OCB Mode}
  921. LibTomCrypt provides support for a mode called OCB\footnote{See
  922. P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.}
  923. . OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
  924. but is less flexible. Let's review how to initialize an OCB context.
  925. \index{ocb\_init()}
  926. \begin{verbatim}
  927. int ocb_init(ocb_state *ocb, int cipher,
  928. const unsigned char *key, unsigned long keylen,
  929. const unsigned char *nonce);
  930. \end{verbatim}
  931. This will initialize the ``ocb'' context using cipher descriptor ``cipher''. It will use a ``key'' of length ``keylen''
  932. and the random ``nonce''. Note that ``nonce'' must be a random (public) string the same length as the block ciphers
  933. block size (e.g. 16 bytes for AES).
  934. This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream.
  935. To encrypt or decrypt data use the following.
  936. \index{ocb\_encrypt()} \index{ocb\_decrypt()}
  937. \begin{verbatim}
  938. int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
  939. int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
  940. \end{verbatim}
  941. This will encrypt (or decrypt for the latter) a fixed length of data from ``pt'' to ``ct'' (vice versa for the latter).
  942. They assume that ``pt'' and ``ct'' are the same size as the block cipher's block size. Note that you cannot call
  943. both functions given a single ``ocb'' state. For bi-directional communication you will have to initialize two ``ocb''
  944. states (with different nonces). Also ``pt'' and ``ct'' may point to the same location in memory.
  945. \subsubsection{State Termination}
  946. When you are finished encrypting the message you call the following function to compute the tag.
  947. \index{ocb\_done\_encrypt()}
  948. \begin{verbatim}
  949. int ocb_done_encrypt(ocb_state *ocb,
  950. const unsigned char *pt, unsigned long ptlen,
  951. unsigned char *ct,
  952. unsigned char *tag, unsigned long *taglen);
  953. \end{verbatim}
  954. This will terminate an encrypt stream ``ocb''. If you have trailing bytes of plaintext that will not complete a block
  955. you can pass them here. This will also encrypt the ``ptlen'' bytes in ``pt'' and store them in ``ct''. It will also
  956. store upto ``taglen'' bytes of the tag into ``tag''.
  957. Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen. Also note that if you have
  958. an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
  959. To terminate a decrypt stream and compared the tag you call the following.
  960. \index{ocb\_done\_decrypt()}
  961. \begin{verbatim}
  962. int ocb_done_decrypt(ocb_state *ocb,
  963. const unsigned char *ct, unsigned long ctlen,
  964. unsigned char *pt,
  965. const unsigned char *tag, unsigned long taglen,
  966. int *res);
  967. \end{verbatim}
  968. Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
  969. tag of the message (internally) and then compare it against the ``taglen'' bytes of ``tag'' provided. By default
  970. ``res'' is set to zero. If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
  971. message).
  972. \subsubsection{Packet Functions}
  973. To make life simpler the following two functions are provided for memory bound OCB.
  974. \index{ocb\_encrypt\_authenticate\_memory()}
  975. \begin{verbatim}
  976. int ocb_encrypt_authenticate_memory(int cipher,
  977. const unsigned char *key, unsigned long keylen,
  978. const unsigned char *nonce,
  979. const unsigned char *pt, unsigned long ptlen,
  980. unsigned char *ct,
  981. unsigned char *tag, unsigned long *taglen);
  982. \end{verbatim}
  983. This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''. The length ``ptlen''
  984. can be any arbitrary length.
  985. \index{ocb\_decrypt\_verify\_memory()}
  986. \begin{verbatim}
  987. int ocb_decrypt_verify_memory(int cipher,
  988. const unsigned char *key, unsigned long keylen,
  989. const unsigned char *nonce,
  990. const unsigned char *ct, unsigned long ctlen,
  991. unsigned char *pt,
  992. const unsigned char *tag, unsigned long taglen,
  993. int *res);
  994. \end{verbatim}
  995. Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set
  996. appropriately.
  997. \subsection{CCM Mode}
  998. CCM is a NIST proposal for Encrypt+Authenticate that is centered around using AES (or any 16--byte cipher) as a primitive. Unlike EAX and OCB mode
  999. it is only meant for ``packet'' mode where the length of the input is known in advance. Since it is a packet mode function CCM only has one
  1000. function that performs the protocol.
  1001. \index{ccm\_memory()}
  1002. \begin{verbatim}
  1003. int ccm_memory(int cipher,
  1004. const unsigned char *key, unsigned long keylen,
  1005. const unsigned char *nonce, unsigned long noncelen,
  1006. const unsigned char *header, unsigned long headerlen,
  1007. unsigned char *pt, unsigned long ptlen,
  1008. unsigned char *ct,
  1009. unsigned char *tag, unsigned long *taglen,
  1010. int direction);
  1011. \end{verbatim}
  1012. This performs the ``CCM'' operation on the data. The ``cipher'' variable indicates which cipher in the descriptor table to use. It must have a
  1013. 16--byte block size for CCM. The key is ``key'' with a length of ``keylen'' octets. The nonce or salt is ``nonce'' of
  1014. length ``noncelen'' octets. The header is meta--data you want to send with the message but not have encrypted, it is stored in ``header''
  1015. of length ``headerlen'' octets. The header can be zero octets long (if $headerlen = 0$ then you can pass ``header'' as \textbf{NULL}).
  1016. The plaintext is stored in ``pt'' and the ciphertext in ``ct''. The length of both are expected to be equal and is passed in as ``ptlen''. It is
  1017. allowable that $pt = ct$. The ``direction'' variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or
  1018. decryption (direction $=$ \textbf{CCM\_DECRYPT}) is to be performed.
  1019. As implemented this copy of CCM cannot handle a header or plaintext longer than $2^{32} - 1$ octets long.
  1020. You can test the implementation of CCM with the following function.
  1021. \index{ccm\_test()}
  1022. \begin{verbatim}
  1023. int ccm_test(void);
  1024. \end{verbatim}
  1025. This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors.
  1026. \subsection{GCM Mode}
  1027. Galois counter mode is an IEEE proposal for authenticated encryption. Like EAX and OCB it can be used in a streaming capacity however, unlike EAX it cannot
  1028. accept ``additional authentication data'' (meta--data) after plaintext has been processed. This mode also only works with block ciphers with a sixteen
  1029. byte block.
  1030. A GCM stream is meant to be processed in three modes each one sequential serial. First the initial vector (per session) data is processed. This should be
  1031. unique to every session. Next the the optional additional authentication data is processed and finally the plaintext.
  1032. \subsubsection{Initialization}
  1033. To initialize the GCM context with a secret key call the following function.
  1034. \index{gcm\_init()}
  1035. \begin{verbatim}
  1036. int gcm_init(gcm_state *gcm, int cipher,
  1037. const unsigned char *key, int keylen);
  1038. \end{verbatim}
  1039. This initializes the GCM state ``gcm'' for the given cipher indexed by ``cipher'' with a secret key ``key'' of length ``keylen'' octets. The cipher chosen
  1040. must have a 16--byte block size (e.g. AES).
  1041. \subsubsection{Initial Vector}
  1042. After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector. It should be unique per packet encrypted.
  1043. \index{gcm\_add\_iv()}
  1044. \begin{verbatim}
  1045. int gcm_add_iv(gcm_state *gcm,
  1046. const unsigned char *IV, unsigned long IVlen);
  1047. \end{verbatim}
  1048. This adds the initial vector octets from ``IV'' of length ``IVlen'' to the GCM state ``gcm''. You can call this function as many times as required
  1049. to process the entire IV.
  1050. Note that the GCM protocols provides a ``shortcut'' for 12--byte IVs where no preprocessing is to be done. If you want to minimize per packet latency it's ideal
  1051. to only use 12--byte IVs. You can just increment it like a counter for each packet and the CTR [privacy] will be ensured.
  1052. \subsubsection{Additional Authentication Data}
  1053. After the entire IV has been processed the additional authentication data can be processed. Unlike the IV a packet/session does not require additional
  1054. 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 that once
  1055. you begin adding AAD to the GCM state you cannot return to adding IV data until the state is reset.
  1056. \index{gcm\_add\_aad()}
  1057. \begin{verbatim}
  1058. int gcm_add_aad(gcm_state *gcm,
  1059. const unsigned char *adata, unsigned long adatalen);
  1060. \end{verbatim}
  1061. This adds the additional authentication data ``adata'' of length ``adatalen'' to the GCM state ``gcm''.
  1062. \subsubsection{Plaintext Processing}
  1063. After the AAD has been processed the plaintext (or ciphertext depending on the direction) can be processed.
  1064. \index{gcm\_process()}
  1065. \begin{verbatim}
  1066. int gcm_process(gcm_state *gcm,
  1067. unsigned char *pt, unsigned long ptlen,
  1068. unsigned char *ct,
  1069. int direction);
  1070. \end{verbatim}
  1071. This processes message data where ``pt'' is the plaintext and ``ct'' is the ciphertext. The length of both are equal and stored in ``ptlen''. Depending on the
  1072. mode ``pt'' is the input and ``ct'' is the output (or vice versa). When ``direction'' equals \textbf{GCM\_ENCRYPT} the plaintext is read, encrypted and stored
  1073. in the ciphertext buffer. When ``direction'' equals \textbf{GCM\_DECRYPT} the opposite occurs.
  1074. \subsubsection{State Termination}
  1075. To terminate a GCM state and retrieve the message authentication tag call the following function.
  1076. \index{gcm\_done()}
  1077. \begin{verbatim}
  1078. int gcm_done(gcm_state *gcm,
  1079. unsigned char *tag, unsigned long *taglen);
  1080. \end{verbatim}
  1081. This terminates the GCM state ``gcm'' and stores the tag in ``tag'' of length ``taglen'' octets.
  1082. \subsubsection{State Reset}
  1083. 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
  1084. it is very costly to have to call it repeatedly. To aid in this endeavour the reset function has been provided.
  1085. \index{gcm\_reset()}
  1086. \begin{verbatim}
  1087. int gcm_reset(gcm_state *gcm);
  1088. \end{verbatim}
  1089. This will reset the GCM state ``gcm'' to the state that gcm\_init() left it. The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
  1090. \subsubsection{One--Shot Packet}
  1091. To process a single packet under any given key the following helper function can be used.
  1092. \index{gcm\_memory()}
  1093. \begin{verbatim}
  1094. int gcm_memory( int cipher,
  1095. const unsigned char *key, unsigned long keylen,
  1096. const unsigned char *IV, unsigned long IVlen,
  1097. const unsigned char *adata, unsigned long adatalen,
  1098. unsigned char *pt, unsigned long ptlen,
  1099. unsigned char *ct,
  1100. unsigned char *tag, unsigned long *taglen,
  1101. int direction);
  1102. \end{verbatim}
  1103. 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
  1104. message tag. The definition of the variables is the same as it is for all the manual functions.
  1105. 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.
  1106. \subsubsection{Example Usage}
  1107. The following is an example usage of how to use GCM over multiple packets with a shared secret key.
  1108. \begin{small}
  1109. \begin{verbatim}
  1110. #include <tomcrypt.h>
  1111. int send_packet(const unsigned char *pt, unsigned long ptlen,
  1112. const unsigned char *iv, unsigned long ivlen,
  1113. const unsigned char *aad, unsigned long aadlen,
  1114. gcm_state *gcm)
  1115. {
  1116. int err;
  1117. unsigned long taglen;
  1118. unsigned char tag[16];
  1119. /* reset the state */
  1120. if ((err = gcm_reset(gcm)) != CRYPT_OK) {
  1121. return err;
  1122. }
  1123. /* Add the IV */
  1124. if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
  1125. return err;
  1126. }
  1127. /* Add the AAD (note: aad can be NULL if aadlen == 0) */
  1128. if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
  1129. return err;
  1130. }
  1131. /* process the plaintext */
  1132. if ((err = gcm_add_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
  1133. return err;
  1134. }
  1135. /* Finish up and get the MAC tag */
  1136. taglen = sizeof(tag);
  1137. if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
  1138. return err;
  1139. }
  1140. /* depending on the protocol and how IV is generated you may have to send it too... */
  1141. send(socket, iv, ivlen, 0);
  1142. /* send the aad */
  1143. send(socket, aad, aadlen, 0);
  1144. /* send the ciphertext */
  1145. send(socket, pt, ptlen, 0);
  1146. /* send the tag */
  1147. send(socket, tag, taglen, 0);
  1148. return CRYPT_OK;
  1149. }
  1150. int main(void)
  1151. {
  1152. gcm_state gcm;
  1153. unsigned char key[16], IV[12], pt[PACKET_SIZE];
  1154. int err, x;
  1155. unsigned long ptlen;
  1156. /* somehow fill key/IV with random values */
  1157. /* register AES */
  1158. register_cipher(&aes_desc);
  1159. /* init the GCM state */
  1160. if ((err = gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
  1161. whine_and_pout(err);
  1162. }
  1163. /* handle us some packets */
  1164. for (;;) {
  1165. ptlen = make_packet_we_want_to_send(pt);
  1166. /* use IV as counter (12 byte counter) */
  1167. for (x = 11; x >= 0; x--) {
  1168. if (++IV[x]) {
  1169. break;
  1170. }
  1171. }
  1172. if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm)) != CRYPT_OK) {
  1173. whine_and_pout(err);
  1174. }
  1175. }
  1176. return EXIT_SUCCESS;
  1177. }
  1178. \end{verbatim}
  1179. \end{small}
  1180. \chapter{One-Way Cryptographic Hash Functions}
  1181. \section{Core Functions}
  1182. Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_state''.
  1183. To initialize hash XXX (where XXX is the name) call:
  1184. \index{Hash Functions}
  1185. \begin{verbatim}
  1186. void XXX_init(hash_state *md);
  1187. \end{verbatim}
  1188. This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the
  1189. message being hashed call:
  1190. \begin{verbatim}
  1191. int XXX_process(hash_state *md, const unsigned char *in, unsigned long inlen);
  1192. \end{verbatim}
  1193. 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
  1194. are buffered. The data can be passed in any sized chunks as long as the order of the bytes are the same the message digest
  1195. (hash output) will be the same. For example, this means that:
  1196. \begin{verbatim}
  1197. md5_process(&md, "hello ", 6);
  1198. md5_process(&md, "world", 5);
  1199. \end{verbatim}
  1200. Will produce the same message digest as the single call:
  1201. \index{Message Digest}
  1202. \begin{verbatim}
  1203. md5_process(&md, "hello world", 11);
  1204. \end{verbatim}
  1205. To finally get the message digest (the hash) call:
  1206. \begin{verbatim}
  1207. int XXX_done(hash_state *md,
  1208. unsigned char *out);
  1209. \end{verbatim}
  1210. This function will finish up the hash and store the result in the ``out'' array. You must ensure that ``out'' is long
  1211. enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the ``XXX\_done()'' functions
  1212. will wipe the ``md'' variable before returning automatically.
  1213. To test a hash function call:
  1214. \begin{verbatim}
  1215. int XXX_test(void);
  1216. \end{verbatim}
  1217. This will return {\bf CRYPTO\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
  1218. example snippet that hashes a message with md5 is given below.
  1219. \begin{small}
  1220. \begin{verbatim}
  1221. #include <tomcrypt.h>
  1222. int main(void)
  1223. {
  1224. hash_state md;
  1225. unsigned char *in = "hello world", out[16];
  1226. /* setup the hash */
  1227. md5_init(&md);
  1228. /* add the message */
  1229. md5_process(&md, in, strlen(in));
  1230. /* get the hash in out[0..15] */
  1231. md5_done(&md, out);
  1232. return 0;
  1233. }
  1234. \end{verbatim}
  1235. \end{small}
  1236. \section{Hash Descriptors}
  1237. Like the set of ciphers the set of hashes have descriptors too. They are stored in an array called ``hash\_descriptor'' and
  1238. are defined by:
  1239. \begin{verbatim}
  1240. struct _hash_descriptor {
  1241. char *name;
  1242. unsigned long hashsize; /* digest output size in bytes */
  1243. unsigned long blocksize; /* the block size the hash uses */
  1244. void (*init) (hash_state *hash);
  1245. int (*process)(hash_state *hash,
  1246. const unsigned char *in, unsigned long inlen);
  1247. int (*done) (hash_state *hash, unsigned char *out);
  1248. int (*test) (void);
  1249. };
  1250. \end{verbatim}
  1251. Similarly ``name'' is the name of the hash function in ASCII (all lowercase). ``hashsize'' is the size of the digest output
  1252. in bytes. The remaining fields are pointers to the functions that do the respective tasks. There is a function to
  1253. search the array as well called ``int find\_hash(char *name)''. It returns -1 if the hash is not found, otherwise the
  1254. position in the descriptor table of the hash.
  1255. You can use the table to indirectly call a hash function that is chosen at runtime. For example:
  1256. \begin{small}
  1257. \begin{verbatim}
  1258. #include <tomcrypt.h>
  1259. int main(void)
  1260. {
  1261. unsigned char buffer[100], hash[MAXBLOCKSIZE];
  1262. int idx, x;
  1263. hash_state md;
  1264. /* register hashes .... */
  1265. if (register_hash(&md5_desc) == -1) {
  1266. printf("Error registering MD5.\n");
  1267. return -1;
  1268. }
  1269. /* register other hashes ... */
  1270. /* prompt for name and strip newline */
  1271. printf("Enter hash name: \n");
  1272. fgets(buffer, sizeof(buffer), stdin);
  1273. buffer[strlen(buffer) - 1] = 0;
  1274. /* get hash index */
  1275. idx = find_hash(buffer);
  1276. if (idx == -1) {
  1277. printf("Invalid hash name!\n");
  1278. return -1;
  1279. }
  1280. /* hash input until blank line */
  1281. hash_descriptor[idx].init(&md);
  1282. while (fgets(buffer, sizeof(buffer), stdin) != NULL)
  1283. hash_descriptor[idx].process(&md, buffer, strlen(buffer));
  1284. hash_descriptor[idx].done(&md, hash);
  1285. /* dump to screen */
  1286. for (x = 0; x < hash_descriptor[idx].hashsize; x++)
  1287. printf("%02x ", hash[x]);
  1288. printf("\n");
  1289. return 0;
  1290. }
  1291. \end{verbatim}
  1292. \end{small}
  1293. Note the usage of ``MAXBLOCKSIZE''. In Libtomcrypt no symmetric block, key or hash digest is larger than MAXBLOCKSIZE in
  1294. length. This provides a simple size you can set your automatic arrays to that will not get overrun.
  1295. There are three helper functions as well:
  1296. \index{hash\_memory()} \index{hash\_file()}
  1297. \begin{verbatim}
  1298. int hash_memory(int hash,
  1299. const unsigned char *in, unsigned long inlen,
  1300. unsigned char *out, unsigned long *outlen);
  1301. int hash_file(int hash, const char *fname,
  1302. unsigned char *out, unsigned long *outlen);
  1303. int hash_filehandle(int hash, FILE *in,
  1304. unsigned char *out, unsigned long *outlen);
  1305. \end{verbatim}
  1306. The ``hash'' parameter is the location in the descriptor table of the hash (\textit{e.g. the return of find\_hash()}).
  1307. The ``*outlen'' variable is used to keep track of the output size. You must set it to the size of your output buffer before
  1308. calling the functions. When they complete succesfully they store the length of the message digest back in it. The functions
  1309. are otherwise straightforward. The ``hash\_filehandle'' function assumes that ``in'' is an file handle opened in binary mode.
  1310. It will hash to the end of file and not reset the file position when finished.
  1311. To perform the above hash with md5 the following code could be used:
  1312. \begin{small}
  1313. \begin{verbatim}
  1314. #include <tomcrypt.h>
  1315. int main(void)
  1316. {
  1317. int idx, err;
  1318. unsigned long len;
  1319. unsigned char out[MAXBLOCKSIZE];
  1320. /* register the hash */
  1321. if (register_hash(&md5_desc) == -1) {
  1322. printf("Error registering MD5.\n");
  1323. return -1;
  1324. }
  1325. /* get the index of the hash */
  1326. idx = find_hash("md5");
  1327. /* call the hash */
  1328. len = sizeof(out);
  1329. if ((err = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
  1330. printf("Error hashing data: %s\n", error_to_string(err));
  1331. return -1;
  1332. }
  1333. return 0;
  1334. }
  1335. \end{verbatim}
  1336. \end{small}
  1337. The following hashes are provided as of this release:
  1338. \index{Hash descriptor table}
  1339. \begin{center}
  1340. \begin{tabular}{|c|c|c|}
  1341. \hline Name & Descriptor Name & Size of Message Digest (bytes) \\
  1342. \hline WHIRLPOOL & whirlpool\_desc & 64 \\
  1343. \hline SHA-512 & sha512\_desc & 64 \\
  1344. \hline SHA-384 & sha384\_desc & 48 \\
  1345. \hline SHA-256 & sha256\_desc & 32 \\
  1346. \hline SHA-224 & sha224\_desc & 28 \\
  1347. \hline TIGER-192 & tiger\_desc & 24 \\
  1348. \hline SHA-1 & sha1\_desc & 20 \\
  1349. \hline RIPEMD-160 & rmd160\_desc & 20 \\
  1350. \hline RIPEMD-128 & rmd128\_desc & 16 \\
  1351. \hline MD5 & md5\_desc & 16 \\
  1352. \hline MD4 & md4\_desc & 16 \\
  1353. \hline MD2 & md2\_desc & 16 \\
  1354. \hline
  1355. \end{tabular}
  1356. \end{center}
  1357. Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
  1358. work exactly like those of the cipher registration code. The functions are:
  1359. \index{register\_hash()} \index{unregister\_hash()}
  1360. \begin{verbatim}
  1361. int register_hash(const struct _hash_descriptor *hash);
  1362. int unregister_hash(const struct _hash_descriptor *hash);
  1363. \end{verbatim}
  1364. \section{Cipher Hash Construction}
  1365. \index{Cipher Hash Construction}
  1366. An addition to the suite of hash functions is the ``Cipher Hash Construction'' or ``CHC'' mode. In this mode
  1367. applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
  1368. particular this allows a cryptosystem to be designed using very few moving parts.
  1369. In order to use the CHC system the developer will have to take a few extra steps. First the ``chc\_desc'' hash
  1370. descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
  1371. data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
  1372. via the chc\_register() function.
  1373. \index{chc\_register()}
  1374. \begin{verbatim}
  1375. int chc_register(int cipher);
  1376. \end{verbatim}
  1377. A cipher has to be registered with CHC (and also in the cipher descriptor tables with
  1378. register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
  1379. be bound to the CHC hash at a time. There are additional requirements for the system to work.
  1380. \begin{enumerate}
  1381. \item The cipher must have a block size greater than 64--bits.
  1382. \item The cipher must allow an input key the size of the block size.
  1383. \end{enumerate}
  1384. Example of using CHC with the AES block cipher.
  1385. \begin{verbatim}
  1386. #include <tomcrypt.h>
  1387. int main(void)
  1388. {
  1389. int err;
  1390. /* register cipher and hash */
  1391. if (register_cipher(&aes_enc_desc) == -1) {
  1392. printf("Could not register cipher\n");
  1393. return EXIT_FAILURE;
  1394. }
  1395. if (register_hash(&chc_desc) == -1) {
  1396. printf("Could not register hash\n");
  1397. return EXIT_FAILURE;
  1398. }
  1399. /* start chc with AES */
  1400. if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
  1401. printf("Error binding AES to CHC: %s\n", error_to_string(err));
  1402. }
  1403. /* now you can use chc_hash in any LTC function [aside from pkcs...] */
  1404. /* ... */
  1405. \end{verbatim}
  1406. \section{Notice}
  1407. It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.
  1408. These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
  1409. (e.g. Yarrow).
  1410. The other hashes such as the SHA-1, SHA-2 (that includes SHA-512, SHA-384 and SHA-256) and TIGER-192 are still considered secure
  1411. for all purposes you would normally use a hash for.
  1412. \chapter{Message Authentication Codes}
  1413. \section{HMAC Protocol}
  1414. Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short. An HMAC
  1415. of a message is a keyed authenication code that only the owner of a private symmetric key will be able to verify. The purpose is
  1416. 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
  1417. eavesdropper will not be able to verify the authenticity of a message.
  1418. The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
  1419. 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
  1420. chars. The initialization routine is:
  1421. \index{hmac\_init()}
  1422. \begin{verbatim}
  1423. int hmac_init(hmac_state *hmac, int hash,
  1424. const unsigned char *key, unsigned long keylen);
  1425. \end{verbatim}
  1426. The ``hmac'' parameter is the state for the HMAC code. ``hash'' is the index into the descriptor table of the hash you want
  1427. to use to authenticate the message. ``key'' is the pointer to the array of chars that make up the key. ``keylen'' is the
  1428. 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:
  1429. \index{hmac\_process()}
  1430. \begin{verbatim}
  1431. int hmac_process(hmac_state *hmac,
  1432. const unsigned char *in, unsigned long inlen);
  1433. \end{verbatim}
  1434. ``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process. ``len'' is the
  1435. number of octets to process. Like the hash process routines you can send the data in arbitrarly sized chunks. When you
  1436. are finished with the HMAC process you must call the following function to get the HMAC code:
  1437. \index{hmac\_done()}
  1438. \begin{verbatim}
  1439. int hmac_done(hmac_state *hmac,
  1440. unsigned char *out, unsigned long *outlen);
  1441. \end{verbatim}
  1442. ``hmac'' is the HMAC state you are working with. ``out'' is the array of octets where the HMAC code should be stored. You must
  1443. set ``outlen'' to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
  1444. produced (depending on which hash was picked). If ``outlen'' is less than the size of the message digest (and ultimately
  1445. the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first ``outlen'' bytes).
  1446. There are two utility functions provided to make using HMACs easier todo. They accept the key and information about the
  1447. message (file pointer, address in memory) and produce the HMAC result in one shot. These are useful if you want to avoid
  1448. calling the three step process yourself.
  1449. \index{hmac\_memory()}
  1450. \begin{verbatim}
  1451. int hmac_memory(int hash,
  1452. const unsigned char *key, unsigned long keylen,
  1453. const unsigned char *in, unsigned long inlen,
  1454. unsigned char *out, unsigned long *outlen);
  1455. \end{verbatim}
  1456. This will produce an HMAC code for the array of octets in ``in'' of length ``inlen''. The index into the hash descriptor
  1457. table must be provided in ``hash''. It uses the key from ``key'' with a key length of ``keylen''.
  1458. The result is stored in the array of octets ``out'' and the length in ``outlen''. The value of ``outlen'' must be set
  1459. to the size of the destination buffer before calling this function. Similarly for files there is the following function:
  1460. \index{hmac\_file()}
  1461. \begin{verbatim}
  1462. int hmac_file(int hash, const char *fname,
  1463. const unsigned char *key, unsigned long keylen,
  1464. unsigned char *out, unsigned long *outlen);
  1465. \end{verbatim}
  1466. ``hash'' is the index into the hash descriptor table of the hash you want to use. ``fname'' is the filename to process.
  1467. ``key'' is the array of octets to use as the key of length ``keylen''. ``out'' is the array of octets where the
  1468. result should be stored.
  1469. To test if the HMAC code is working there is the following function:
  1470. \index{hmac\_test()}
  1471. \begin{verbatim}
  1472. int hmac_test(void);
  1473. \end{verbatim}
  1474. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  1475. HMAC system is given below.
  1476. \begin{small}
  1477. \begin{verbatim}
  1478. #include <tomcrypt.h>
  1479. int main(void)
  1480. {
  1481. int idx, err;
  1482. hmac_state hmac;
  1483. unsigned char key[16], dst[MAXBLOCKSIZE];
  1484. unsigned long dstlen;
  1485. /* register SHA-1 */
  1486. if (register_hash(&sha1_desc) == -1) {
  1487. printf("Error registering SHA1\n");
  1488. return -1;
  1489. }
  1490. /* get index of SHA1 in hash descriptor table */
  1491. idx = find_hash("sha1");
  1492. /* we would make up our symmetric key in "key[]" here */
  1493. /* start the HMAC */
  1494. if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
  1495. printf("Error setting up hmac: %s\n", error_to_string(err));
  1496. return -1;
  1497. }
  1498. /* process a few octets */
  1499. if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
  1500. printf("Error processing hmac: %s\n", error_to_string(err));
  1501. return -1;
  1502. }
  1503. /* get result (presumably to use it somehow...) */
  1504. dstlen = sizeof(dst);
  1505. if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
  1506. printf("Error finishing hmac: %s\n", error_to_string(err));
  1507. return -1;
  1508. }
  1509. printf("The hmac is %lu bytes long\n", dstlen);
  1510. /* return */
  1511. return 0;
  1512. }
  1513. \end{verbatim}
  1514. \end{small}
  1515. \section{OMAC Support}
  1516. OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
  1517. algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. From an API
  1518. standpoint the OMAC routines work much like the HMAC routines do. Instead in this case a cipher is used instead of a hash.
  1519. To start an OMAC state you call
  1520. \index{omac\_init()}
  1521. \begin{verbatim}
  1522. int omac_init(omac_state *omac, int cipher,
  1523. const unsigned char *key, unsigned long keylen);
  1524. \end{verbatim}
  1525. The ``omac'' variable is the state for the OMAC algorithm. ``cipher'' is the index into the cipher\_descriptor table
  1526. of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
  1527. wish to use. ``key'' and ``keylen'' are the keys used to authenticate the data.
  1528. To send data through the algorithm call
  1529. \index{omac\_process()}
  1530. \begin{verbatim}
  1531. int omac_process(omac_state *state,
  1532. const unsigned char *in, unsigned long inlen);
  1533. \end{verbatim}
  1534. This will send ``inlen'' bytes from ``in'' through the active OMAC state ``state''. Returns \textbf{CRYPT\_OK} if the
  1535. function succeeds. The function is not sensitive to the granularity of the data. For example,
  1536. \begin{verbatim}
  1537. omac_process(&mystate, "hello", 5);
  1538. omac_process(&mystate, " world", 6);
  1539. \end{verbatim}
  1540. Would produce the same result as,
  1541. \begin{verbatim}
  1542. omac_process(&mystate, "hello world", 11);
  1543. \end{verbatim}
  1544. When you are done processing the message you can call the following to compute the message tag.
  1545. \index{omac\_done()}
  1546. \begin{verbatim}
  1547. int omac_done(omac_state *state,
  1548. unsigned char *out, unsigned long *outlen);
  1549. \end{verbatim}
  1550. Which will terminate the OMAC and output the \textit{tag} (MAC) to ``out''. Note that unlike the HMAC and other code
  1551. ``outlen'' can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
  1552. specification states that the output may be truncated. So if you pass in $outlen = 5$ and use AES as your cipher than
  1553. the output MAC code will only be five bytes long. If ``outlen'' is larger than the default size it is set to the default
  1554. size to show how many bytes were actually used.
  1555. Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
  1556. following function.
  1557. \index{omac\_memory()}
  1558. \begin{verbatim}
  1559. int omac_memory(int cipher,
  1560. const unsigned char *key, unsigned long keylen,
  1561. const unsigned char *in, unsigned long inlen,
  1562. unsigned char *out, unsigned long *outlen);
  1563. \end{verbatim}
  1564. This will compute the OMAC of ``inlen'' bytes of ``in'' using the key ``key'' of length ``keylen'' bytes and the cipher
  1565. specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same
  1566. rules as omac\_done.
  1567. To OMAC a file use
  1568. \index{omac\_file()}
  1569. \begin{verbatim}
  1570. int omac_file(int cipher,
  1571. const unsigned char *key, unsigned long keylen,
  1572. const char *filename,
  1573. unsigned char *out, unsigned long *outlen);
  1574. \end{verbatim}
  1575. Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
  1576. and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with
  1577. the same rules as omac\_done.
  1578. To test if the OMAC code is working there is the following function:
  1579. \index{omac\_test()}
  1580. \begin{verbatim}
  1581. int omac_test(void);
  1582. \end{verbatim}
  1583. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  1584. OMAC system is given below.
  1585. \begin{small}
  1586. \begin{verbatim}
  1587. #include <tomcrypt.h>
  1588. int main(void)
  1589. {
  1590. int idx, err;
  1591. omac_state omac;
  1592. unsigned char key[16], dst[MAXBLOCKSIZE];
  1593. unsigned long dstlen;
  1594. /* register Rijndael */
  1595. if (register_cipher(&rijndael_desc) == -1) {
  1596. printf("Error registering Rijndael\n");
  1597. return -1;
  1598. }
  1599. /* get index of Rijndael in cipher descriptor table */
  1600. idx = find_cipher("rijndael");
  1601. /* we would make up our symmetric key in "key[]" here */
  1602. /* start the OMAC */
  1603. if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
  1604. printf("Error setting up omac: %s\n", error_to_string(err));
  1605. return -1;
  1606. }
  1607. /* process a few octets */
  1608. if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
  1609. printf("Error processing omac: %s\n", error_to_string(err));
  1610. return -1;
  1611. }
  1612. /* get result (presumably to use it somehow...) */
  1613. dstlen = sizeof(dst);
  1614. if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
  1615. printf("Error finishing omac: %s\n", error_to_string(err));
  1616. return -1;
  1617. }
  1618. printf("The omac is %lu bytes long\n", dstlen);
  1619. /* return */
  1620. return 0;
  1621. }
  1622. \end{verbatim}
  1623. \end{small}
  1624. \section{PMAC Support}
  1625. The PMAC\footnote{J.Black, P.Rogaway, ``A Block--Cipher Mode of Operation for Parallelizable Message Authentication''}
  1626. protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
  1627. API as the provided OMAC code.
  1628. A PMAC state is initialized with the following.
  1629. \index{pmac\_init()}
  1630. \begin{verbatim}
  1631. int pmac_init(pmac_state *pmac, int cipher,
  1632. const unsigned char *key, unsigned long keylen);
  1633. \end{verbatim}
  1634. Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes. The chosen cipher
  1635. must have a 64 or 128 bit block size (e.x. AES).
  1636. To MAC data simply send it through the process function.
  1637. \index{pmac\_process()}
  1638. \begin{verbatim}
  1639. int pmac_process(pmac_state *state,
  1640. const unsigned char *in, unsigned long inlen);
  1641. \end{verbatim}
  1642. This will process ``inlen'' bytes of ``in'' in the given ``state''. The function is not sensitive to the granularity of the
  1643. data. For example,
  1644. \begin{verbatim}
  1645. pmac_process(&mystate, "hello", 5);
  1646. pmac_process(&mystate, " world", 6);
  1647. \end{verbatim}
  1648. Would produce the same result as,
  1649. \begin{verbatim}
  1650. pmac_process(&mystate, "hello world", 11);
  1651. \end{verbatim}
  1652. When a complete message has been processed the following function can be called to compute the message tag.
  1653. \index{pmac\_done()}
  1654. \begin{verbatim}
  1655. int pmac_done(pmac_state *state,
  1656. unsigned char *out, unsigned long *outlen);
  1657. \end{verbatim}
  1658. This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''. Note that if ``outlen'' is larger
  1659. than the size of the tag it is set to the amount of bytes stored in ``out''.
  1660. Similar to the PMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
  1661. following function.
  1662. \index{pmac\_memory()}
  1663. \begin{verbatim}
  1664. int pmac_memory(int cipher,
  1665. const unsigned char *key, unsigned long keylen,
  1666. const unsigned char *in, unsigned long inlen,
  1667. unsigned char *out, unsigned long *outlen);
  1668. \end{verbatim}
  1669. This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
  1670. specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with the same
  1671. rules as omac\_done.
  1672. To PMAC a file use
  1673. \index{pmac\_file()}
  1674. \begin{verbatim}
  1675. int pmac_file(int cipher,
  1676. const unsigned char *key, unsigned long keylen,
  1677. const char *filename,
  1678. unsigned char *out, unsigned long *outlen);
  1679. \end{verbatim}
  1680. Which will PMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
  1681. and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table. It will store the MAC in ``out'' with
  1682. the same rules as omac\_done.
  1683. To test if the PMAC code is working there is the following function:
  1684. \index{pmac\_test()}
  1685. \begin{verbatim}
  1686. int pmac_test(void);
  1687. \end{verbatim}
  1688. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
  1689. \section{Pelican MAC}
  1690. Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a ``mixing function''. It achieves a very high
  1691. 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
  1692. as it calls AES directly.
  1693. \index{pelican\_init()}
  1694. \begin{verbatim}
  1695. int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
  1696. \end{verbatim}
  1697. This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
  1698. \index{pelican\_process()}
  1699. \begin{verbatim}
  1700. int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
  1701. \end{verbatim}
  1702. This will process ``inlen'' bytes of ``in'' through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
  1703. routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
  1704. an entire message.
  1705. \index{pelican\_done()}
  1706. \begin{verbatim}
  1707. int pelican_done(pelican_state *pelmac, unsigned char *out);
  1708. \end{verbatim}
  1709. This terminates a Pelican MAC and writes the 16--octet tag to ``out''.
  1710. \subsection{Example}
  1711. \begin{verbatim}
  1712. #include <tomcrypt.h>
  1713. int main(void)
  1714. {
  1715. pelican_state pelstate;
  1716. unsigned char key[32], tag[16];
  1717. int err;
  1718. /* somehow initialize a key */
  1719. /* initialize pelican mac */
  1720. if ((err = pelican_init(&pelstate, /* the state */
  1721. key, /* user key */
  1722. 32 /* key length in octets */
  1723. )) != CRYPT_OK) {
  1724. printf("Error initializing Pelican: %s", error_to_string(err));
  1725. return EXIT_FAILURE;
  1726. }
  1727. /* MAC some data */
  1728. if ((err = pelican_process(&pelstate, /* the state */
  1729. "hello world", /* data to mac */
  1730. 11 /* length of data */
  1731. )) != CRYPT_OK) {
  1732. printf("Error processing Pelican: %s", error_to_string(err));
  1733. return EXIT_FAILURE;
  1734. }
  1735. /* Terminate the MAC */
  1736. if ((err = pelican_done(&pelstate, /* the state */
  1737. tag /* where to store the tag */
  1738. )) != CRYPT_OK) {
  1739. printf("Error terminating Pelican: %s", error_to_string(err));
  1740. return EXIT_FAILURE;
  1741. }
  1742. /* tag[0..15] has the MAC output now */
  1743. return EXIT_SUCCESS;
  1744. }
  1745. \end{verbatim}
  1746. \chapter{Pseudo-Random Number Generators}
  1747. \section{Core Functions}
  1748. The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
  1749. 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)
  1750. key generation. There is a universal structure called ``prng\_state''. To initialize a PRNG call:
  1751. \index{PRNG start}
  1752. \begin{verbatim}
  1753. int XXX_start(prng_state *prng);
  1754. \end{verbatim}
  1755. 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
  1756. entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
  1757. \index{PRNG add\_entropy}
  1758. \begin{verbatim}
  1759. int XXX_add_entropy(const unsigned char *in, unsigned long inlen,
  1760. prng_state *prng);
  1761. \end{verbatim}
  1762. Which returns {\bf CRYPTO\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
  1763. function to put the entropy into action.
  1764. \index{PRNG ready}
  1765. \begin{verbatim}
  1766. int XXX_ready(prng_state *prng);
  1767. \end{verbatim}
  1768. Which returns {\bf CRYPTO\_OK} if it is ready. Finally to actually read bytes call:
  1769. \index{PRNG read}
  1770. \begin{verbatim}
  1771. unsigned long XXX_read(unsigned char *out, unsigned long outlen,
  1772. prng_state *prng);
  1773. \end{verbatim}
  1774. Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
  1775. the following.
  1776. \index{PRNG done}
  1777. \begin{verbatim}
  1778. void XXX_done(prng_state *prng);
  1779. \end{verbatim}
  1780. This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
  1781. so that you can later resume the PRNG call the following.
  1782. \index{PRNG export}
  1783. \begin{verbatim}
  1784. int XXX_export(unsigned char *out, unsigned long *outlen,
  1785. prng_state *prng);
  1786. \end{verbatim}
  1787. This will write a ``PRNG state'' to the buffer ``out'' of length ``outlen'' bytes. The idea of
  1788. the export is meant to be used as a ``seed file''. That is, when the program starts up there will not likely
  1789. be that much entropy available. To import a state to seed a PRNG call the following function.
  1790. \index{PRNG import}
  1791. \begin{verbatim}
  1792. int XXX_import(const unsigned char *in, unsigned long inlen,
  1793. prng_state *prng);
  1794. \end{verbatim}
  1795. This will call the start and add\_entropy functions of the given PRNG. It will use the state in
  1796. ``in'' of length ``inlen'' as the initial seed. You must pass the same seed length as was exported
  1797. by the corresponding export function.
  1798. Note that importing a state will not ``resume'' the PRNG from where it left off. That is, if you export
  1799. a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
  1800. specifically equal the 8 bytes you generated previously.
  1801. When a program is first executed the normal course of operation is
  1802. \begin{enumerate}
  1803. \item Gather entropy from your sources for a given period of time or number of events.
  1804. \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
  1805. \end{enumerate}
  1806. When your program is finished you simply call the export function and save the state to a medium (disk,
  1807. flash memory, etc). The next time your application starts up you can detect the state, feed it to the
  1808. import function and go on your way. It is ideal that (as soon as possible) after startup you export a
  1809. fresh state. This helps in the case that the program aborts or the machine is powered down without
  1810. being given a chance to exit properly.
  1811. Note that even if you have a state to import it is important to add new entropy to the state. However,
  1812. there is less pressure to do so.
  1813. To test a PRNG for operational conformity call the following functions.
  1814. \index{PRNG test}
  1815. \begin{verbatim}
  1816. int XXX_test(void);
  1817. \end{verbatim}
  1818. This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
  1819. \subsection{Remarks}
  1820. It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
  1821. 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
  1822. 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
  1823. checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading.
  1824. \subsection{Example}
  1825. Below is a simple snippet to read 10 bytes from yarrow. Its important to note that this snippet is
  1826. {\bf NOT} secure since the entropy added is not random.
  1827. \begin{verbatim}
  1828. #include <tomcrypt.h>
  1829. int main(void)
  1830. {
  1831. prng_state prng;
  1832. unsigned char buf[10];
  1833. int err;
  1834. /* start it */
  1835. if ((err = yarrow_start(&prng)) != CRYPT_OK) {
  1836. printf("Start error: %s\n", error_to_string(err));
  1837. }
  1838. /* add entropy */
  1839. if ((err = yarrow_add_entropy("hello world", 11, &prng)) != CRYPT_OK) {
  1840. printf("Add_entropy error: %s\n", error_to_string(err));
  1841. }
  1842. /* ready and read */
  1843. if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
  1844. printf("Ready error: %s\n", error_to_string(err));
  1845. }
  1846. printf("Read %lu bytes from yarrow\n", yarrow_read(buf, 10, &prng));
  1847. return 0;
  1848. }
  1849. \end{verbatim}
  1850. \section{PRNG Descriptors}
  1851. \index{PRNG Descriptor}
  1852. PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descriptor''. The format of an element is:
  1853. \begin{verbatim}
  1854. struct _prng_descriptor {
  1855. char *name;
  1856. int export_size; /* size in bytes of exported state */
  1857. int (*start) (prng_state *);
  1858. int (*add_entropy)(const unsigned char *, unsigned long, prng_state *);
  1859. int (*ready) (prng_state *);
  1860. unsigned long (*read)(unsigned char *, unsigned long len, prng_state *);
  1861. void (*done)(prng_state *);
  1862. int (*export)(unsigned char *, unsigned long *, prng_state *);
  1863. int (*import)(const unsigned char *, unsigned long, prng_state *);
  1864. int (*test)(void);
  1865. };
  1866. \end{verbatim}
  1867. There is a ``int find\_prng(char *name)'' function as well. Returns -1 if the PRNG is not found, otherwise it returns
  1868. the position in the prng\_descriptor array.
  1869. Just like the ciphers and hashes you must register your prng before you can use it. The two functions provided work
  1870. exactly as those for the cipher registry functions. They are:
  1871. \begin{verbatim}
  1872. int register_prng(const struct _prng_descriptor *prng);
  1873. int unregister_prng(const struct _prng_descriptor *prng);
  1874. \end{verbatim}
  1875. \subsection{PRNGs Provided}
  1876. \begin{figure}[here]
  1877. \begin{center}
  1878. \begin{small}
  1879. \begin{tabular}{|c|c|l|}
  1880. \hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
  1881. \hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
  1882. \hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended) \\
  1883. \hline RC4 & rc4\_desc & Stream Cipher \\
  1884. \hline SOBER-128 & sober128\_desc & Stream Cipher (also very fast PRNG) \\
  1885. \hline
  1886. \end{tabular}
  1887. \end{small}
  1888. \end{center}
  1889. \caption{List of Provided PRNGs}
  1890. \end{figure}
  1891. \subsubsection{Yarrow}
  1892. Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
  1893. (keyboard, mouse, interrupts, etc) and produce an unbounded string of random bytes.
  1894. \textit{Note:} This PRNG is still secure for most taskings but is no longer recommended. Users
  1895. should use Fortuna instead.
  1896. \subsubsection{Fortuna}
  1897. Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
  1898. usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
  1899. to work with most cipher and hash combos based on which you have chosen to build into the library.} while
  1900. providing more security.
  1901. Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
  1902. and SHA--256 hash function. Technically Fortuna will work with any block cipher that accepts a 256--bit
  1903. key and any hash that produces at least a 256--bit output. However, to make the implementation simpler
  1904. it has been fixed to those choices.
  1905. Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
  1906. added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
  1907. details Fortuna has the ability to recover from state determination attacks where the attacker starts
  1908. to learn information from the PRNGs output about the internal state. Yarrow on the other hand cannot
  1909. recover from that problem until new entropy is added to the pool and put to use through the ready() function.
  1910. \subsubsection{RC4}
  1911. RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You ``key'' it by
  1912. calling add\_entropy() and setup the key by calling ready(). You can only add upto 256 bytes via
  1913. add\_entropy().
  1914. When you read from RC4 the output of the RC4 algorithm is XOR'd against your buffer you provide. In this
  1915. manner you can use rc4\_read() as an encrypt (and decrypt) function.
  1916. You really shouldn't use RC4 anymore. This isn't because RC4 is weak (though biases are known to exist) just
  1917. simply that faster alternatives exist.
  1918. \subsubsection{SOBER-128}
  1919. SOBER-128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4 you ``key'' it by
  1920. calling add\_entropy(). There is no need to call ready() for this PRNG as it does not do anything.
  1921. Note that this cipher has several oddities about how it operates. The first time you call
  1922. add\_entropy() that sets the cipher's key. Every other time you call the same function it sets
  1923. the cipher's IV variable. The IV mechanism allows you to encrypt several messages with the same
  1924. key and not re--use the same key material.
  1925. Unlike Yarrow and Fortuna all of the entropy (and hence security) of this algorithm rests in the data
  1926. you pass it on the first call to add\_entropy(). All buffers sent to add\_entropy() must have a length
  1927. that is a multiple of four bytes.
  1928. Like RC4 the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner you can use
  1929. sober128\_read() as an encrypt (and decrypt) function.
  1930. Since SOBER-128 has a fixed keying scheme and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
  1931. key it from the output of Fortuna (or Yarrow) and use it to encrypt messages. It is also ideal for
  1932. simulations which need a high quality (and fast) stream of bytes.
  1933. \subsubsection{Example Usage}
  1934. \begin{small}
  1935. \begin{verbatim}
  1936. #include <tomcrypt.h>
  1937. int main(void)
  1938. {
  1939. prng_state prng;
  1940. unsigned char buf[32];
  1941. int err;
  1942. if ((err = rc4_start(&prng)) != CRYPT_OK) {
  1943. printf("RC4 init error: %s\n", error_to_string(err));
  1944. exit(-1);
  1945. }
  1946. /* use ``key'' as the key */
  1947. if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
  1948. printf("RC4 add entropy error: %s\n", error_to_string(err));
  1949. exit(-1);
  1950. }
  1951. /* setup RC4 for use */
  1952. if ((err = rc4_ready(&prng)) != CRYPT_OK) {
  1953. printf("RC4 ready error: %s\n", error_to_string(err));
  1954. exit(-1);
  1955. }
  1956. /* encrypt buffer */
  1957. strcpy(buf,"hello world");
  1958. if (rc4_read(buf, 11, &prng) != 11) {
  1959. printf("RC4 read error\n");
  1960. exit(-1);
  1961. }
  1962. return 0;
  1963. }
  1964. \end{verbatim}
  1965. \end{small}
  1966. To decrypt you have to do the exact same steps.
  1967. \section{The Secure RNG}
  1968. \index{Secure RNG}
  1969. An RNG is related to a PRNG except that it doesn't expand a smaller seed to get the data. They generate their random bits
  1970. by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
  1971. PRNG. Computers are deterministic beasts that try hard not to stray from pre-determined paths. That makes gathering
  1972. entropy needed to seed the PRNG a hard task.
  1973. There is one small function that may help on certain platforms:
  1974. \index{rng\_get\_bytes()}
  1975. \begin{verbatim}
  1976. unsigned long rng_get_bytes(unsigned char *buf, unsigned long len,
  1977. void (*callback)(void));
  1978. \end{verbatim}
  1979. Which will try one of three methods of getting random data. The first is to open the popular ``/dev/random'' device which
  1980. on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite. It emulates ``/dev/random'' via the Microsoft CSP.}.
  1981. The second method is to try the Microsoft Cryptographic Service Provider and read the RNG. The third method is an ANSI C
  1982. clock drift method that is also somewhat popular but gives bits of lower entropy. The ``callback'' parameter is a pointer to a function that returns void. Its used when the slower ANSI C RNG must be
  1983. used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of three
  1984. bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you don't want to. The function
  1985. returns the number of bytes actually read from any RNG source. There is a function to help setup a PRNG as well:
  1986. \index{rng\_make\_prng()}
  1987. \begin{verbatim}
  1988. int rng_make_prng(int bits, int wprng, prng_state *prng,
  1989. void (*callback)(void));
  1990. \end{verbatim}
  1991. This will try to setup the prng with a state of at least ``bits'' of entropy. The ``callback'' parameter works much like
  1992. the callback in ``rng\_get\_bytes()''. It is highly recommended that you use this function to setup your PRNGs unless you have a
  1993. platform where the RNG doesn't work well. Example usage of this function is given below.
  1994. \begin{small}
  1995. \begin{verbatim}
  1996. #include <tomcrypt.h>
  1997. int main(void)
  1998. {
  1999. ecc_key mykey;
  2000. prng_state prng;
  2001. int err;
  2002. /* register yarrow */
  2003. if (register_prng(&yarrow_desc) == -1) {
  2004. printf("Error registering Yarrow\n");
  2005. return -1;
  2006. }
  2007. /* setup the PRNG */
  2008. if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
  2009. printf("Error setting up PRNG, %s\n", error_to_string(err));
  2010. return -1;
  2011. }
  2012. /* make a 192-bit ECC key */
  2013. if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) {
  2014. printf("Error making key: %s\n", error_to_string(err));
  2015. return -1;
  2016. }
  2017. return 0;
  2018. }
  2019. \end{verbatim}
  2020. \end{small}
  2021. \subsection{The Secure PRNG Interface}
  2022. It is possible to access the secure RNG through the PRNG interface and in turn use it within dependent functions such
  2023. as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
  2024. requires to be started, that is you need not call the start, add\_entropy or ready functions. For example, consider
  2025. the previous example using this PRNG.
  2026. \begin{small}
  2027. \begin{verbatim}
  2028. #include <tomcrypt.h>
  2029. int main(void)
  2030. {
  2031. ecc_key mykey;
  2032. int err;
  2033. /* register SPRNG */
  2034. if (register_prng(&sprng_desc) == -1) {
  2035. printf("Error registering SPRNG\n");
  2036. return -1;
  2037. }
  2038. /* make a 192-bit ECC key */
  2039. if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) != CRYPT_OK) {
  2040. printf("Error making key: %s\n", error_to_string(err));
  2041. return -1;
  2042. }
  2043. return 0;
  2044. }
  2045. \end{verbatim}
  2046. \end{small}
  2047. \chapter{RSA Public Key Cryptography}
  2048. \section{Introduction}
  2049. RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
  2050. padding algorithms for encryption and signatures. The standard includes ``v1.5'' and ``v2.0'' algorithms.
  2051. To simplify matters a little the v2.0 encryption and signature padding algorithms are called OAEP and PSS
  2052. respectively.
  2053. \section{PKCS \#1 Encryption}
  2054. PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
  2055. the library is concerned we are only dealing with th OAEP padding of the message.
  2056. \subsection{OAEP Encoding}
  2057. \index{pkcs\_1\_oaep\_encode()}
  2058. \begin{alltt}
  2059. int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen,
  2060. const unsigned char *lparam, unsigned long lparamlen,
  2061. unsigned long modulus_bitlen, prng_state *prng,
  2062. int prng_idx, int hash_idx,
  2063. unsigned char *out, unsigned long *outlen);
  2064. \end{alltt}
  2065. This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded. The ``lparam'' variable is an additional system specific
  2066. tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
  2067. ``lparam'' can be set to \textbf{NULL}.
  2068. 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
  2069. ``modulus\_bitlen''. ``hash\_idx'' is the index into the hash descriptor table of the hash desired. PKCS \#1 allows any hash to be
  2070. 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
  2071. sized input message. ``prng\_idx'' and ``prng'' are the random number generator arguments required to randomize the padding process.
  2072. The padded message is stored in ``out'' along with the length in ``outlen''.
  2073. If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for ``msg'' is
  2074. $m - 2h - 2$. For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.
  2075. Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
  2076. rsa\_exptmod() to encrypt it.
  2077. \subsection{OAEP Decoding}
  2078. \index{pkcs\_1\_oaep\_decode()}
  2079. \begin{alltt}
  2080. int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen,
  2081. const unsigned char *lparam, unsigned long lparamlen,
  2082. unsigned long modulus_bitlen, int hash_idx,
  2083. unsigned char *out, unsigned long *outlen,
  2084. int *res);
  2085. \end{alltt}
  2086. This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. ``msg'' is the
  2087. output of pkcs\_1\_oaep\_encode() of length ``msglen''. ``lparam'' is the same system variable passed to the OAEP encoder. If it does not
  2088. match what was used during encoding this function will not decode the packet. ``modulus\_bitlen'' is the size of the RSA modulus in bits
  2089. and must match what was used during encoding. Similarly the ``hash\_idx'' index into the hash descriptor table must match what was used
  2090. during encoding.
  2091. If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen'' and stores a
  2092. $1$ in ``res''. If the packet is invalid it stores $0$ in ``res'' and if the function fails for another reason
  2093. it returns an error code.
  2094. \subsection{PKCS \#1 v1.5 Encoding}
  2095. \index{pkcs\_1\_v15\_es\_encode()}
  2096. \begin{verbatim}
  2097. int pkcs_1_v15_es_encode(const unsigned char *msg, unsigned long msglen,
  2098. unsigned long modulus_bitlen,
  2099. prng_state *prng, int prng_idx,
  2100. unsigned char *out, unsigned long *outlen);
  2101. \end{verbatim}
  2102. This will PKCS v1.5 encode the data in ``msg'' of length ``msglen''. Pass the length (in bits) of your
  2103. RSA modulus in ``modulus\_bitlen''. The encoded data will be stored in ``out'' of length ``outlen''.
  2104. \subsection{PKCS \#1 v1.5 Decoding}
  2105. \index{pkcs\_1\_v15\_es\_decode()}
  2106. \begin{verbatim}
  2107. int pkcs_1_v15_es_decode(const unsigned char *msg, unsigned long msglen,
  2108. unsigned long modulus_bitlen,
  2109. unsigned char *out, unsigned long outlen,
  2110. int *res);
  2111. \end{verbatim}
  2112. This will PKCS v1.5 decode the message in ``msg'' of length ``msglen''. It will store the output in ``out''. Note
  2113. that the length of the output ``outlen'' is a constant. This decoder cannot determine the original message
  2114. length. If the data in ``msg'' is a valid packet then a $1$ is stored in ``res'', otherwise a $0$ is
  2115. stored.
  2116. \section{PKCS \#1 Digital Signatures}
  2117. \subsection{PSS Encoding}
  2118. PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
  2119. \index{pkcs\_1\_pss\_encode()}
  2120. \begin{alltt}
  2121. int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
  2122. unsigned long saltlen, prng_state *prng,
  2123. int prng_idx, int hash_idx,
  2124. unsigned long modulus_bitlen,
  2125. unsigned char *out, unsigned long *outlen);
  2126. \end{alltt}
  2127. This function assumes the message to be PSS encoded has previously been hashed. The input hash ``msghash'' is of length
  2128. ``msghashlen''. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
  2129. ``hash\_idx'' is the index into the hash descriptor table of the hash to use. ``prng\_idx'' and ``prng'' are the random
  2130. number generator information required for the salt.
  2131. Similar to OAEP encoding ``modulus\_bitlen'' is the size of the RSA modulus (in bits). It limits the size of the salt. If $m$ is the length
  2132. of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
  2133. 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().
  2134. \subsection{PSS Decoding}
  2135. To decode a PSS encoded signature block you have to use the following.
  2136. \index{pkcs\_1\_pss\_decode()}
  2137. \begin{alltt}
  2138. int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
  2139. const unsigned char *sig, unsigned long siglen,
  2140. unsigned long saltlen, int hash_idx,
  2141. unsigned long modulus_bitlen, int *res);
  2142. \end{alltt}
  2143. This will decode the PSS encoded message in ``sig'' of length ``siglen'' and compare it to values in ``msghash'' of length
  2144. ``msghashlen''. If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero. Otherwise,
  2145. it is set to zero. The rest of the parameters are as in the PSS encode call.
  2146. It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
  2147. \subsection{PKCS \#1 v1.5 Encoding}
  2148. \index{pkcs\_1\_v15\_sa\_encode()}
  2149. \begin{verbatim}
  2150. int pkcs_1_v15_sa_encode(const unsigned char *msghash, unsigned long msghashlen,
  2151. int hash_idx, unsigned long modulus_bitlen,
  2152. unsigned char *out, unsigned long *outlen);
  2153. \end{verbatim}
  2154. This will PKCS \#1 v1.5 signature encode the message hash ``msghash'' of length ``msghashlen''. You have
  2155. to tell this routine which hash produced the message hash in ``hash\_idx''. The encoded hash is stored
  2156. in ``out'' of length ``outlen''.
  2157. \subsection{PKCS \#1 v1.5 Decoding}
  2158. \index{pkcs\_1\_v15\_sa\_decode()}
  2159. \begin{verbatim}
  2160. int pkcs_1_v15_sa_decode(const unsigned char *msghash, unsigned long msghashlen,
  2161. const unsigned char *sig, unsigned long siglen,
  2162. int hash_idx, unsigned long modulus_bitlen,
  2163. int *res);
  2164. \end{verbatim}
  2165. This will PKCS \#1 v1.5 signature decode the data in ``sig'' of length ``siglen'' and compare the extracted
  2166. hash against ``msghash'' of length ``msghashlen''. You have to tell this routine which hash produced the
  2167. message digest in ``hash\_idx''. If the packet is valid and the hashes match ``res'' is set to $1$. Otherwise,
  2168. it is set to $0$.
  2169. \section{RSA Operations}
  2170. \subsection{Background}
  2171. RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown
  2172. factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
  2173. not strictly equivalent.
  2174. The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or ``Euler totient'' of the
  2175. multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
  2176. $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
  2177. $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
  2178. often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
  2179. A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
  2180. $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
  2181. given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
  2182. $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
  2183. can sign a message by ``decrypting'' it. Others can verify it by ``encrypting'' it.
  2184. Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
  2185. Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
  2186. the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
  2187. The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
  2188. designed for fast exponentiation (requires 16 squarings and one multiplication).
  2189. It is important to pad the input to RSA since it has particular mathematical structure. For instance
  2190. $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
  2191. to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
  2192. together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
  2193. the hash of documents only but also to pad the inputs with data to remove such structure.
  2194. \subsection{RSA Key Generation}
  2195. For RSA routines a single ``rsa\_key'' structure is used. To make a new RSA key call:
  2196. \index{rsa\_make\_key()}
  2197. \begin{verbatim}
  2198. int rsa_make_key(prng_state *prng,
  2199. int wprng, int size,
  2200. long e, rsa_key *key);
  2201. \end{verbatim}
  2202. Where ``wprng'' is the index into the PRNG descriptor array. ``size'' is the size in bytes of the RSA modulus desired.
  2203. ``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537. I suggest you stick with 65537 since its big
  2204. enough to prevent trivial math attacks and not super slow. ``key'' is where the key is placed. All keys must be at
  2205. least 128 bytes and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
  2206. Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call
  2207. ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically
  2208. free the ram allocated itself.
  2209. \index{PK\_PRIVATE} \index{PK\_PUBLIC}
  2210. There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
  2211. RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated
  2212. and has been replaced by the PK\_PRIVATE type.} in the form of a RSAPrivateKey. The second type is a public RSA key
  2213. which only includes the modulus and public exponent. It takes the form of a RSAPublicKey.
  2214. \subsection{RSA Exponentiation}
  2215. To do raw work with the RSA function call:
  2216. \index{rsa\_exptmod()}
  2217. \begin{verbatim}
  2218. int rsa_exptmod(const unsigned char *in, unsigned long inlen,
  2219. unsigned char *out, unsigned long *outlen,
  2220. int which, prng_state *prng, int prng_idx,
  2221. rsa_key *key);
  2222. \end{verbatim}
  2223. This loads the bignum from ``in'' as a big endian word in the format PKCS specifies, raises it to either ``e'' or ``d'' and stores the result
  2224. in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e''
  2225. (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
  2226. Note that the output of his function is zero-padded as per PKCS \#1 specifications. This allows this routine to
  2227. interoprate with PKCS \#1 padding functions properly.
  2228. \subsection{RSA Key Encryption}
  2229. Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
  2230. To facilitate encrypting short keys the following functions have been provided.
  2231. \index{rsa\_encrypt\_key()}
  2232. \begin{verbatim}
  2233. int rsa_encrypt_key(const unsigned char *in, unsigned long inlen,
  2234. unsigned char *out, unsigned long *outlen,
  2235. const unsigned char *lparam, unsigned long lparamlen,
  2236. prng_state *prng, int prng_idx, int hash_idx, rsa_key *key);
  2237. \end{verbatim}
  2238. This function will OAEP pad ``in'' of length inlen bytes then RSA encrypt it and store the ciphertext
  2239. in ``out'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
  2240. to pkcs\_1\_oaep\_encode().
  2241. \index{rsa\_decrypt\_key()}
  2242. \begin{verbatim}
  2243. int rsa_decrypt_key(const unsigned char *in, unsigned long inlen,
  2244. unsigned char *out, unsigned long *outlen,
  2245. const unsigned char *lparam, unsigned long lparamlen,
  2246. prng_state *prng, int prng_idx,
  2247. int hash_idx, int *res,
  2248. rsa_key *key);
  2249. \end{verbatim}
  2250. This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
  2251. ``out'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
  2252. to pkcs\_1\_oaep\_decode().
  2253. If the RSA decrypted data isn't a valid OAEP packet then ``res'' is set to $0$. Otherwise, it is set to $1$.
  2254. \subsection{RSA Hash Signatures}
  2255. Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes). To facilitate this
  2256. process the following functions have been provided.
  2257. \index{rsa\_sign\_hash()}
  2258. \begin{verbatim}
  2259. int rsa_sign_hash(const unsigned char *in, unsigned long inlen,
  2260. unsigned char *out, unsigned long *outlen,
  2261. prng_state *prng, int prng_idx,
  2262. int hash_idx, unsigned long saltlen,
  2263. rsa_key *key);
  2264. \end{verbatim}
  2265. This will PSS encode the message hash ``in'' of length ``inlen''. Next the PSS encoded message will be RSA ``signed'' and
  2266. the output is stored in ``out'' of length ``outlen''.
  2267. \index{rsa\_verify\_hash()}
  2268. \begin{verbatim}
  2269. int rsa_verify_hash(const unsigned char *sig, unsigned long siglen,
  2270. const unsigned char *msghash, unsigned long msghashlen,
  2271. prng_state *prng, int prng_idx,
  2272. int hash_idx, unsigned long saltlen,
  2273. int *stat, rsa_key *key);
  2274. \end{verbatim}
  2275. This will RSA ``verify'' the signature in ``sig'' of length ``siglen''. Next the RSA decoded data is PSS decoded
  2276. and the extracted hash is compared against the message hash ``msghash'' of length ``msghashlen''.
  2277. If the RSA decoded data is not a valid PSS message or if the PSS decoded hash does not match the ``msghash''
  2278. the value ``res'' is set to $0$. Otherwise, if the function succeeds and signature is valid ``res'' is set
  2279. to $1$.
  2280. \begin{verbatim}
  2281. #include <tomcrypt.h>
  2282. int main(void)
  2283. {
  2284. int err, hash_idx, prng_idx, res;
  2285. unsigned long l1, l2;
  2286. unsigned char pt[16], pt2[16], out[1024];
  2287. rsa_key key;
  2288. /* register prng/hash */
  2289. if (register_prng(&sprng_desc) == -1) {
  2290. printf("Error registering sprng");
  2291. return EXIT_FAILURE;
  2292. }
  2293. if (register_hash(&sha1_desc) == -1) {
  2294. printf("Error registering sha1");
  2295. return EXIT_FAILURE;
  2296. }
  2297. hash_idx = find_hash("sha1");
  2298. prng_idx = find_prng("sprng");
  2299. /* make an RSA-1024 key */
  2300. if ((err = rsa_make_key(NULL, /* PRNG state */
  2301. prng_idx, /* PRNG idx */
  2302. 1024/8, /* 1024-bit key */
  2303. 65537, /* we like e=65537 */
  2304. &key) /* where to store the key */
  2305. ) != CRYPT_OK) {
  2306. printf("rsa_make_key %s", error_to_string(err));
  2307. return EXIT_FAILURE;
  2308. }
  2309. /* fill in pt[] with a key we want to send ... */
  2310. l1 = sizeof(out);
  2311. if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
  2312. 16, /* data is 16 bytes long */
  2313. out, /* where to store ciphertext */
  2314. &l1, /* length of ciphertext */
  2315. "TestApp", /* our lparam for this program */
  2316. 7, /* lparam is 7 bytes long */
  2317. NULL, /* PRNG state */
  2318. prng_idx, /* prng idx */
  2319. hash_idx, /* hash idx */
  2320. &key) /* our RSA key */
  2321. ) != CRYPT_OK) {
  2322. printf("rsa_encrypt_key %s", error_to_string(err));
  2323. return EXIT_FAILURE;
  2324. }
  2325. /* now let's decrypt the encrypted key */
  2326. l2 = sizeof(pt2);
  2327. if ((err = rsa_decrypt_key(out, /* encrypted data */
  2328. l1, /* length of ciphertext */
  2329. pt2, /* where to put plaintext */
  2330. &l2, /* plaintext length */
  2331. "TestApp", /* lparam for this program */
  2332. 7, /* lparam is 7 bytes long */
  2333. NULL, /* PRNG state */
  2334. prng_idx, /* prng idx */
  2335. hash_idx, /* hash idx */
  2336. &res, /* validity of data */
  2337. &key) /* our RSA key */
  2338. ) != CRYPT_OK) {
  2339. printf("rsa_decrypt_key %s", error_to_string(err));
  2340. return EXIT_FAILURE;
  2341. }
  2342. /* if all went well pt == pt2, l2 == 16, res == 1 */
  2343. }
  2344. \end{verbatim}
  2345. \chapter{Diffie-Hellman Key Exchange}
  2346. \section{Background}
  2347. Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
  2348. of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
  2349. generates a large sub-group of prime order (for unique values of $x$).
  2350. 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
  2351. ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
  2352. 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
  2353. a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
  2354. From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
  2355. $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
  2356. $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
  2357. the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
  2358. symmetric cipher.
  2359. It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
  2360. discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
  2361. modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
  2362. $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
  2363. To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
  2364. the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
  2365. smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
  2366. \section{Core Functions}
  2367. This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
  2368. provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
  2369. called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first routine is to
  2370. make a Diffie-Hellman private key pair:
  2371. \index{dh\_make\_key()}
  2372. \begin{verbatim}
  2373. int dh_make_key(prng_state *prng, int wprng,
  2374. int keysize, dh_key *key);
  2375. \end{verbatim}
  2376. The ``keysize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 512 bytes which correspond
  2377. to key sizes of 768 to 4096 bits. The smaller the key the faster it is to use however it will be less secure. When
  2378. specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
  2379. above 512 it will return an error. So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass
  2380. ``keysize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
  2381. to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
  2382. $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
  2383. leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
  2384. hard.
  2385. The next two routines are for exporting/importing Diffie-Hellman keys in a binary format. This is useful for transport
  2386. over communication mediums.
  2387. \index{dh\_export()} \index{dh\_import()}
  2388. \begin{verbatim}
  2389. int dh_export(unsigned char *out, unsigned long *outlen,
  2390. int type, dh_key *key);
  2391. int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
  2392. \end{verbatim}
  2393. These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
  2394. Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails. You can free a
  2395. ``dh\_key'' using:
  2396. \begin{verbatim}
  2397. void dh_free(dh_key *key);
  2398. \end{verbatim}
  2399. After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
  2400. with the other user using:
  2401. \index{dh\_shared\_secret()}
  2402. \begin{verbatim}
  2403. int dh_shared_secret(dh_key *private_key,
  2404. dh_key *public_key,
  2405. unsigned char *out, unsigned long *outlen);
  2406. \end{verbatim}
  2407. 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
  2408. 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
  2409. 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
  2410. key:
  2411. \index{dh\_get\_size()}
  2412. \begin{verbatim}
  2413. int dh_get_size(dh_key *key);
  2414. \end{verbatim}
  2415. This returns the size in bytes of the modulus chosen for that key.
  2416. \subsection{Remarks on Usage}
  2417. Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
  2418. 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.}:
  2419. \newpage
  2420. \begin{small}
  2421. \begin{verbatim}
  2422. int establish_secure_socket(int sock, int mode, unsigned char *key,
  2423. prng_state *prng, int wprng)
  2424. {
  2425. unsigned char buf[4096], buf2[4096];
  2426. unsigned long x, len;
  2427. int res, err, inlen;
  2428. dh_key mykey, theirkey;
  2429. /* make up our private key */
  2430. if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK) {
  2431. return err;
  2432. }
  2433. /* export our key as public */
  2434. x = sizeof(buf);
  2435. if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
  2436. res = err;
  2437. goto done2;
  2438. }
  2439. if (mode == 0) {
  2440. /* mode 0 so we send first */
  2441. if (send(sock, buf, x, 0) != x) {
  2442. res = CRYPT_ERROR;
  2443. goto done2;
  2444. }
  2445. /* get their key */
  2446. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  2447. res = CRYPT_ERROR;
  2448. goto done2;
  2449. }
  2450. } else {
  2451. /* mode >0 so we send second */
  2452. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  2453. res = CRYPT_ERROR;
  2454. goto done2;
  2455. }
  2456. if (send(sock, buf, x, 0) != x) {
  2457. res = CRYPT_ERROR;
  2458. goto done2;
  2459. }
  2460. }
  2461. if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
  2462. res = err;
  2463. goto done2;
  2464. }
  2465. /* make shared secret */
  2466. x = sizeof(buf);
  2467. if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
  2468. res = err;
  2469. goto done;
  2470. }
  2471. /* hash it */
  2472. len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
  2473. if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
  2474. res = err;
  2475. goto done;
  2476. }
  2477. /* clean up and return */
  2478. res = CRYPT_OK;
  2479. done:
  2480. dh_free(&theirkey);
  2481. done2:
  2482. dh_free(&mykey);
  2483. zeromem(buf, sizeof(buf));
  2484. zeromem(buf2, sizeof(buf2));
  2485. return res;
  2486. }
  2487. \end{verbatim}
  2488. \end{small}
  2489. \newpage
  2490. \subsection{Remarks on The Snippet}
  2491. When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
  2492. passed to ``establish\_secure\_socket()''.
  2493. \section{Other Diffie-Hellman Functions}
  2494. In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
  2495. available:
  2496. \index{dh\_test()}
  2497. \begin{verbatim}
  2498. int dh_test(void);
  2499. \end{verbatim}
  2500. This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct. There is one last helper
  2501. function:
  2502. \index{dh\_sizes()}
  2503. \begin{verbatim}
  2504. void dh_sizes(int *low, int *high);
  2505. \end{verbatim}
  2506. Which stores the smallest and largest key sizes support into the two variables.
  2507. \section{DH Packet}
  2508. Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
  2509. algorithms.
  2510. \index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
  2511. \begin{verbatim}
  2512. int dh_encrypt_key(const unsigned char *in, unsigned long inlen,
  2513. unsigned char *out, unsigned long *len,
  2514. prng_state *prng, int wprng, int hash,
  2515. dh_key *key);
  2516. int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
  2517. unsigned char *out, unsigned long *outlen,
  2518. dh_key *key);
  2519. \end{verbatim}
  2520. Where ``in'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
  2521. and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
  2522. required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
  2523. as the symmetric key you are trying to share.
  2524. Similar to the RSA system you can sign and verify a hash of a message.
  2525. \index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
  2526. \begin{verbatim}
  2527. int dh_sign_hash(const unsigned char *in, unsigned long inlen,
  2528. unsigned char *out, unsigned long *outlen,
  2529. prng_state *prng, int wprng, dh_key *key);
  2530. int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
  2531. const unsigned char *hash, unsigned long hashlen,
  2532. int *stat, dh_key *key);
  2533. \end{verbatim}
  2534. The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.
  2535. The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''. It sets ``stat''
  2536. to non-zero if the signature passes or zero if it fails.
  2537. \chapter{Elliptic Curve Cryptography}
  2538. \section{Background}
  2539. The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
  2540. Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
  2541. to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
  2542. of the order of the base point in time. That means if you use a base point of order $2^{192}$ (which would represent a
  2543. 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
  2544. The curves in this library are taken from the following website:
  2545. \begin{verbatim}
  2546. http://csrc.nist.gov/cryptval/dss.htm
  2547. \end{verbatim}
  2548. They are all curves over the integers modulo a prime. The curves have the basic equation that is:
  2549. \begin{equation}
  2550. y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
  2551. \end{equation}
  2552. The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
  2553. provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
  2554. range in order from $\approx 2^{192}$ points to $\approx 2^{521}$. According to the source document any key size greater
  2555. than or equal to 256-bits is sufficient for long term security.
  2556. \section{Core Functions}
  2557. Like the DH routines there is a key structure ``ecc\_key'' used by the functions. There is a function to make a key:
  2558. \index{ecc\_make\_key()}
  2559. \begin{verbatim}
  2560. int ecc_make_key(prng_state *prng, int wprng,
  2561. int keysize, ecc_key *key);
  2562. \end{verbatim}
  2563. The ``keysize'' is the size of the modulus in bytes desired. Currently directly supported values are 20, 24, 28, 32, 48 and 65 bytes which
  2564. correspond to key sizes of 160, 192, 224, 256, 384 and 521 bits respectively. If you pass a key size that is between any key size
  2565. it will round the keysize up to the next available one. The rest of the parameters work like they do in the ``dh\_make\_key()'' function.
  2566. To free the ram allocated by a key call:
  2567. \index{ecc\_free()}
  2568. \begin{verbatim}
  2569. void ecc_free(ecc_key *key);
  2570. \end{verbatim}
  2571. To import and export a key there are:
  2572. \index{ecc\_export()}
  2573. \index{ecc\_import()}
  2574. \begin{verbatim}
  2575. int ecc_export(unsigned char *out, unsigned long *outlen,
  2576. int type, ecc_key *key);
  2577. int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
  2578. \end{verbatim}
  2579. These two work exactly like there DH counterparts. Finally when you share your public key you can make a shared secret
  2580. with:
  2581. \index{ecc\_shared\_secret()}
  2582. \begin{verbatim}
  2583. int ecc_shared_secret(ecc_key *private_key,
  2584. ecc_key *public_key,
  2585. unsigned char *out, unsigned long *outlen);
  2586. \end{verbatim}
  2587. Which works exactly like the DH counterpart, the ``private\_key'' is your own key and ``public\_key'' is the key the other
  2588. user sent you. Note that this function stores both $x$ and $y$ co-ordinates of the shared
  2589. elliptic point. You should hash the output to get a shared key in a more compact and useful form (most of the entropy is
  2590. in $x$ anyways). Both keys have to be the same size for this to work, to help there is a function to get the size in bytes
  2591. of a key.
  2592. \index{ecc\_get\_size()}
  2593. \begin{verbatim}
  2594. int ecc_get_size(ecc_key *key);
  2595. \end{verbatim}
  2596. To test the ECC routines and to get the minimum and maximum key sizes there are these two functions:
  2597. \index{ecc\_test()}
  2598. \begin{verbatim}
  2599. int ecc_test(void);
  2600. void ecc_sizes(int *low, int *high);
  2601. \end{verbatim}
  2602. Which both work like their DH counterparts.
  2603. \section{ECC Packet}
  2604. Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
  2605. algorithms.
  2606. \index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
  2607. \begin{verbatim}
  2608. int ecc_encrypt_key(const unsigned char *in, unsigned long inlen,
  2609. unsigned char *out, unsigned long *outlen,
  2610. prng_state *prng, int wprng, int hash,
  2611. ecc_key *key);
  2612. int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
  2613. unsigned char *out, unsigned long *outlen,
  2614. ecc_key *key);
  2615. \end{verbatim}
  2616. Where ``in'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
  2617. and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required
  2618. data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large
  2619. as the symmetric key you are trying to share.
  2620. There are also functions to sign and verify the hash of a message.
  2621. \index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
  2622. \begin{verbatim}
  2623. int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
  2624. unsigned char *out, unsigned long *outlen,
  2625. prng_state *prng, int wprng, ecc_key *key);
  2626. int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
  2627. const unsigned char *hash, unsigned long hashlen,
  2628. int *stat, ecc_key *key);
  2629. \end{verbatim}
  2630. The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a ECC packet in ``out''.
  2631. The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''. It sets ``stat''
  2632. to non-zero if the signature passes or zero if it fails.
  2633. \section{ECC Keysizes}
  2634. With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems. The math will still work
  2635. and in effect the signature will still work. With ECC keys the strength of the signature is limited by the size of
  2636. the hash or the size of they key, whichever is smaller. For example, if you sign with SHA256 and a ECC-160 key in effect
  2637. you have 160-bits of security (e.g. as if you signed with SHA-1).
  2638. The library will not warn you if you make this mistake so it is important to check yourself before using the
  2639. signatures.
  2640. \chapter{Digital Signature Algorithm}
  2641. \section{Introduction}
  2642. The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
  2643. reduce the bandwidth of a signature. For example, to have ``80-bits of security'' with ElGamal you need a group of
  2644. order at least 1024-bits. With DSA you need a group of order at least 160-bits. By comparison the ElGamal signature
  2645. would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.
  2646. The API for the DSA is essentially the same as the other PK algorithms. Except in the case of DSA no encryption or
  2647. decryption routines are provided.
  2648. \section{Key Generation}
  2649. To make a DSA key you must call the following function
  2650. \begin{verbatim}
  2651. int dsa_make_key(prng_state *prng, int wprng,
  2652. int group_size, int modulus_size,
  2653. dsa_key *key);
  2654. \end{verbatim}
  2655. The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor. ``group\_size'' and
  2656. ``modulus\_size'' control the difficulty of forging a signature. Both parameters are in bytes. The larger the
  2657. ``group\_size'' the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
  2658. $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
  2659. \begin{center}
  2660. \begin{tabular}{|c|c|c|}
  2661. \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
  2662. \hline 80 & 20 & 128 \\
  2663. \hline 120 & 30 & 256 \\
  2664. \hline 140 & 35 & 384 \\
  2665. \hline 160 & 40 & 512 \\
  2666. \hline
  2667. \end{tabular}
  2668. \end{center}
  2669. When you are finished with a DSA key you can call the following function to free the memory used.
  2670. \index{dsa\_free()}
  2671. \begin{verbatim}
  2672. void dsa_free(dsa_key *key);
  2673. \end{verbatim}
  2674. \section{Key Verification}
  2675. Each DSA key is composed of the following variables.
  2676. \begin{enumerate}
  2677. \item $q$ a small prime of magnitude $256^{group\_size}$.
  2678. \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
  2679. \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
  2680. value. For this library they start at $h = 2$ and step until $g$ is not $1$.
  2681. \item $x$ a random secret (the secret key) in the range $1 < x < q$
  2682. \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
  2683. \end{enumerate}
  2684. A DSA key is considered valid if it passes all of the following tests.
  2685. \begin{enumerate}
  2686. \item $q$ must be prime.
  2687. \item $p$ must be prime.
  2688. \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
  2689. \item $g$ must be less than $p$.
  2690. \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
  2691. \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  2692. \item $1 < y < p - 1$
  2693. \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  2694. \end{enumerate}
  2695. Tests one and two ensure that the values will at least form a field which is required for the signatures to
  2696. function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
  2697. forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
  2698. ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
  2699. is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
  2700. that $y$ belongs to a multiplicative sub-group of order $q$.
  2701. The following function will perform these tests.
  2702. \index{dsa\_verify\_key()}
  2703. \begin{verbatim}
  2704. int dsa_verify_key(dsa_key *key, int *stat);
  2705. \end{verbatim}
  2706. This will test ``key'' and store the result in ``stat''. If the result is $stat = 0$ the DSA key failed one of the tests
  2707. 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).
  2708. \section{Signatures}
  2709. To generate a DSA signature call the following function
  2710. \index{dsa\_sign\_hash()}
  2711. \begin{verbatim}
  2712. int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
  2713. unsigned char *out, unsigned long *outlen,
  2714. prng_state *prng, int wprng, dsa_key *key);
  2715. \end{verbatim}
  2716. Which will sign the data in ``in'' of length ``inlen'' bytes. The signature is stored in ``out'' and the size
  2717. of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing
  2718. is stored and the function returns an error code. The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
  2719. To verify a hash created with that function use the following function
  2720. \index{dsa\_verify\_hash()}
  2721. \begin{verbatim}
  2722. int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
  2723. const unsigned char *hash, unsigned long inlen,
  2724. int *stat, dsa_key *key);
  2725. \end{verbatim}
  2726. Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.
  2727. It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.
  2728. \section{Import and Export}
  2729. To export a DSA key so that it can be transported use the following function
  2730. \index{dsa\_export()}
  2731. \begin{verbatim}
  2732. int dsa_export(unsigned char *out, unsigned long *outlen,
  2733. int type,
  2734. dsa_key *key);
  2735. \end{verbatim}
  2736. This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
  2737. initialized to the maximum buffer size). The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
  2738. depending on whether you want to export a private or public copy of the DSA key.
  2739. To import an exported DSA key use the following function
  2740. \index{dsa\_import()}
  2741. \begin{verbatim}
  2742. int dsa_import(const unsigned char *in, unsigned long inlen,
  2743. dsa_key *key);
  2744. \end{verbatim}
  2745. This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function
  2746. will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
  2747. \chapter{Standards Support}
  2748. \section{DER Support}
  2749. DER or ``Distinguished Encoding Rules'' is a subset of the ASN.1 encoding rules that is fully deterministic and
  2750. ideal for cryptography. In particular ASN.1 specifies an INTEGER type for storing arbitrary sized integers. DER
  2751. further limits the ASN.1 specifications to a deterministic encoding.
  2752. \subsection{Storing INTEGER types}
  2753. \index{der\_encode\_integer()}
  2754. \begin{alltt}
  2755. int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
  2756. \end{alltt}
  2757. This will store the integer in ``num'' to the output buffer ``out'' of length ``outlen''. It only stores
  2758. non--negative numbers. It stores the number of octets used back in ``outlen''.
  2759. \subsection{Reading INTEGER types}
  2760. \index{der\_decode\_integer()}
  2761. \begin{alltt}
  2762. int der_decode_integer(const unsigned char *in, unsigned long *inlen, mp_int *num);
  2763. \end{alltt}
  2764. This will decode the DER encoded INTEGER in ``in'' of length ``inlen'' and store the resulting integer
  2765. in ``num''. It will store the bytes read in ``inlen'' which is handy if you have to parse multiple
  2766. data items out of a binary packet.
  2767. \subsection{INTEGER length}
  2768. \index{der\_length\_integer()}
  2769. \begin{alltt}
  2770. int der_length_integer(mp_int *num, unsigned long *len);
  2771. \end{alltt}
  2772. This will determine the length of the DER encoding of the integer ``num'' and store it in ``len''.
  2773. \subsection{Multiple INTEGER types}
  2774. To simplify the DER encoding/decoding there are two functions two handle multple types at once.
  2775. \index{der\_put\_multi\_integer()}
  2776. \index{der\_get\_multi\_integer()}
  2777. \begin{alltt}
  2778. int der_put_multi_integer(unsigned char *dst, unsigned long *outlen, mp_int *num, ...);
  2779. int der_get_multi_integer(const unsigned char *src, unsigned long *inlen, mp_int *num, ...);
  2780. \end{alltt}
  2781. These will handle multiple encodings/decodings at once. They work like their single operand counterparts
  2782. except they handle a \textbf{NULL} terminated list of operands.
  2783. \begin{verbatim}
  2784. #include <tomcrypt.h>
  2785. int main(void)
  2786. {
  2787. mp_int a, b, c, d;
  2788. unsigned char buffer[1000];
  2789. unsigned long len;
  2790. int err;
  2791. /* init a,b,c,d with some values ... */
  2792. /* ok we want to store them now... */
  2793. len = sizeof(buffer);
  2794. if ((err = der_put_multi_integer(buffer, &len,
  2795. &a, &b, &c, &d, NULL)) != CRYPT_OK) {
  2796. // error
  2797. }
  2798. printf("I stored %lu bytes in buf\n", len);
  2799. /* ok say we want to get them back for fun */
  2800. /* len set previously...otherwise set it to the size of the packet */
  2801. if ((err = der_get_multi_integer(buffer, &len,
  2802. &a, &b, &c, &d, NULL)) != CRYPT_OK) {
  2803. // error
  2804. }
  2805. printf("I read %lu bytes from buf\n", len);
  2806. }
  2807. \end{verbatim}
  2808. \section{Password Based Cryptography}
  2809. \subsection{PKCS \#5}
  2810. In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
  2811. is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
  2812. for completeness. Algorithm Two is a bit more modern and more flexible to work with.
  2813. \subsection{Algorithm One}
  2814. 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
  2815. people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
  2816. algorithm and produces an output no longer than the output of the hash.
  2817. \index{pkcs\_5\_alg1()}
  2818. \begin{alltt}
  2819. int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
  2820. const unsigned char *salt,
  2821. int iteration_count, int hash_idx,
  2822. unsigned char *out, unsigned long *outlen)
  2823. \end{alltt}
  2824. Where ``password'' is the users password. Since the algorithm allows binary passwords you must also specify the length in ``password\_len''.
  2825. The ``salt'' is a fixed size 8--byte array which should be random for each user and session. The ``iteration\_count'' is the delay desired
  2826. on the password. The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table.
  2827. The output of length upto ``outlen'' is stored in ``out''. If ``outlen'' is initially larger than the size of the hash functions output
  2828. it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in ``out''.
  2829. \subsection{Algorithm Two}
  2830. Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the
  2831. hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
  2832. from a single password and invokation of this algorithm.
  2833. \index{pkcs\_5\_alg2()}
  2834. \begin{alltt}
  2835. int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
  2836. const unsigned char *salt, unsigned long salt_len,
  2837. int iteration_count, int hash_idx,
  2838. unsigned char *out, unsigned long *outlen)
  2839. \end{alltt}
  2840. Where ``password'' is the users password. Since the algorithm allows binary passwords you must also specify the length in ``password\_len''.
  2841. The ``salt'' is an array of size ``salt\_len''. It should be random for each user and session. The ``iteration\_count'' is the delay desired
  2842. on the password. The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table. The output of length upto
  2843. ``outlen'' is stored in ``out''.
  2844. \begin{alltt}
  2845. /* demo to show how to make session state material from a password */
  2846. #include <tomcrypt.h>
  2847. int main(void)
  2848. \{
  2849. unsigned char password[100], salt[100],
  2850. cipher_key[16], cipher_iv[16],
  2851. mac_key[16], outbuf[48];
  2852. int err, hash_idx;
  2853. unsigned long outlen, password_len, salt_len;
  2854. /* register hash and get it's idx .... */
  2855. /* get users password and make up a salt ... */
  2856. /* create the material (100 iterations in algorithm) */
  2857. outlen = sizeof(outbuf);
  2858. if ((err = pkcs_5_alg2(password, password_len, salt, salt_len,
  2859. 100, hash_idx, outbuf, &outlen)) != CRYPT_OK) \{
  2860. /* error handle */
  2861. \}
  2862. /* now extract it */
  2863. memcpy(cipher_key, outbuf, 16);
  2864. memcpy(cipher_iv, outbuf+16, 16);
  2865. memcpy(mac_key, outbuf+32, 16);
  2866. /* use material (recall to store the salt in the output) */
  2867. \}
  2868. \end{alltt}
  2869. \chapter{Miscellaneous}
  2870. \section{Base64 Encoding and Decoding}
  2871. The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it
  2872. encodes but the format used does not comply to any known standard. The characters used in the mappings are:
  2873. \begin{verbatim}
  2874. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
  2875. \end{verbatim}
  2876. Those characters should are supported in virtually any 7-bit ASCII system which means they can be used for transport over
  2877. common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
  2878. where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
  2879. original input. After the first four characters is the rest of the message.
  2880. Often it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
  2881. put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
  2882. break up the first four characters.
  2883. To encode a binary string in base64 call:
  2884. \index{base64\_encode()} \index{base64\_decode()}
  2885. \begin{verbatim}
  2886. int base64_encode(const unsigned char *in, unsigned long len,
  2887. unsigned char *out, unsigned long *outlen);
  2888. \end{verbatim}
  2889. Where ``in'' is the binary string and ``out'' is where the ASCII output is placed. You must set the value of ``outlen'' prior
  2890. to calling this function and it sets the length of the base64 output in ``outlen'' when it is done. To decode a base64
  2891. string call:
  2892. \begin{verbatim}
  2893. int base64_decode(const unsigned char *in, unsigned long len,
  2894. unsigned char *out, unsigned long *outlen);
  2895. \end{verbatim}
  2896. \section{The Multiple Precision Integer Library (MPI)}
  2897. The library comes with a copy of LibTomMath which is a multiple precision integer library written by the
  2898. author of LibTomCrypt. LibTomMath is a trivial to use ANSI C compatible large integer library which is free
  2899. for all uses and is distributed freely.
  2900. At the heart of all the functions is the data type ``mp\_int'' (defined in tommath.h). This data type is what
  2901. will hold all large integers. In order to use an mp\_int one must initialize it first, for example:
  2902. \begin{verbatim}
  2903. #include <tomcrypt.h> /* tomcrypt.h includes mpi.h automatically */
  2904. int main(void)
  2905. {
  2906. mp_int bignum;
  2907. /* initialize it */
  2908. mp_init(&bignum);
  2909. return 0;
  2910. }
  2911. \end{verbatim}
  2912. If you are unfamiliar with the syntax of C the \& symbol is used to pass the address of ``bignum'' to the function. All
  2913. LibTomMath functions require the address of the parameters. To free the memory of a mp\_int use (for example):
  2914. \begin{verbatim}
  2915. mp_clear(&bignum);
  2916. \end{verbatim}
  2917. The functions also have the basic form of one of the following:
  2918. \begin{verbatim}
  2919. mp_XXX(mp_int *a);
  2920. mp_XXX(mp_int *a, mp_int *b, mp_int *c);
  2921. mp_XXX(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  2922. \end{verbatim}
  2923. Where they perform some operation and store the result in the mp\_int variable passed on the far right.
  2924. For example, to compute $c = a + b \mbox{ }(\mbox{mod }m)$ you would call:
  2925. \begin{verbatim}
  2926. mp_addmod(&a, &b, &m, &c);
  2927. \end{verbatim}
  2928. \subsection{Binary Forms of ``mp\_int'' Variables}
  2929. Often it is required to store a ``mp\_int'' in binary form for transport (e.g. exporting a key, packet
  2930. encryption, etc.). LibTomMath includes two functions to help when exporting numbers:
  2931. \begin{verbatim}
  2932. int mp_raw_size(mp_int *num);
  2933. mp_toraw(&num, buf);
  2934. \end{verbatim}
  2935. The former function gives the size in bytes of the raw format and the latter function actually stores the raw data. All
  2936. ``mp\_int'' numbers are stored in big endian form (like PKCS demands) with the first byte being the sign of the number. The
  2937. ``rsa\_exptmod()'' function differs slightly since it will take the input in the form exactly as PKCS demands (without the
  2938. leading sign byte). All other functions include the sign byte (since its much simpler just to include it). The sign byte
  2939. must be zero for positive numbers and non-zero for negative numbers. For example,
  2940. the sequence:
  2941. \begin{verbatim}
  2942. 00 FF 30 04
  2943. \end{verbatim}
  2944. Represents the integer $255 \cdot 256^2 + 48 \cdot 256^1 + 4 \cdot 256^0$ or 16,723,972.
  2945. To read a binary string back into a ``mp\_int'' call:
  2946. \begin{verbatim}
  2947. mp_read_raw(mp_int *num, unsigned char *str, int len);
  2948. \end{verbatim}
  2949. Where ``num'' is where to store it, ``str'' is the binary string (including the leading sign byte) and ``len'' is the
  2950. length of the binary string.
  2951. \subsection{Primality Testing}
  2952. \index{Primality Testing}
  2953. The library includes primality testing and random prime functions as well. The primality tester will perform the test in
  2954. two phases. First it will perform trial division by the first few primes. Second it will perform eight rounds of the
  2955. Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
  2956. composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
  2957. the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
  2958. $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
  2959. When making random primes the trial division step is in fact an optimized implementation of ``Implementation of Fast RSA Key Generation on Smart Cards''\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
  2960. In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candiate
  2961. is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
  2962. math operations. As a result the routine can scan ahead to the next number required for testing with very little work
  2963. involved.
  2964. 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
  2965. instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
  2966. 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
  2967. 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
  2968. 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
  2969. not equal to $(p - 1)(rs - 1)$.
  2970. These are not technically part of the LibTomMath library but this is the best place to document them.
  2971. To test if a ``mp\_int'' is prime call:
  2972. \begin{verbatim}
  2973. int is_prime(mp_int *N, int *result);
  2974. \end{verbatim}
  2975. This puts a one in ``result'' if the number is probably prime, otherwise it places a zero in it. It is assumed that if
  2976. it returns an error that the value in ``result'' is undefined. To make
  2977. a random prime call:
  2978. \begin{verbatim}
  2979. int rand_prime(mp_int *N, unsigned long len, prng_state *prng, int wprng);
  2980. \end{verbatim}
  2981. Where ``len'' is the size of the prime in bytes ($2 \le len \le 256$). You can set ``len'' to the negative size you want
  2982. 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
  2983. ``len = -128'' to the function. Upon success it will return {\bf CRYPT\_OK} and ``N'' will contain an integer which
  2984. is very likely prime.
  2985. \chapter{Programming Guidelines}
  2986. \section{Secure Pseudo Random Number Generators}
  2987. Probably the singal most vulnerable point of any cryptosystem is the PRNG. Without one generating and protecting secrets
  2988. would be impossible. The requirement that one be setup correctly is vitally important and to address this point the library
  2989. does provide two RNG sources that will address the largest amount of end users as possible. The ``sprng'' PRNG provided
  2990. provides and easy to access source of entropy for any application on a *NIX or Windows computer.
  2991. However, when the end user is not on one of these platforms the application developer must address the issue of finding
  2992. entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
  2993. a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
  2994. \section{Preventing Trivial Errors}
  2995. Two simple ways to prevent trivial errors is to prevent overflows and to check the return values. All of the functions
  2996. which output variable length strings will require you to pass the length of the destination. If the size of your output
  2997. buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
  2998. Also virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors as simple
  2999. typos or such can cause algorithms to fail to work as desired.
  3000. \section{Registering Your Algorithms}
  3001. To avoid linking and other runtime errors it is important to register the ciphers, hashes and PRNGs you intend to use
  3002. before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
  3003. A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
  3004. having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
  3005. write the few functions required plus a descriptor. After registering your PRNG all of the library functions that
  3006. need a PRNG can instantly take advantage of it.
  3007. \section{Key Sizes}
  3008. \subsection{Symmetric Ciphers}
  3009. For symmetric ciphers use as large as of a key as possible. For the most part ``bits are cheap'' so using a 256-bit key
  3010. is not a hard thing todo.
  3011. \subsection{Assymetric Ciphers}
  3012. 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
  3013. $n$ is estimated to be
  3014. \begin{equation}
  3015. e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
  3016. \end{equation}
  3017. Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
  3018. is:
  3019. \begin{center}
  3020. \begin{tabular}{|c|c|}
  3021. \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
  3022. \hline 512 & 63.92 \\
  3023. \hline 768 & 76.50 \\
  3024. \hline 1024 & 86.76 \\
  3025. \hline 1536 & 103.37 \\
  3026. \hline 2048 & 116.88 \\
  3027. \hline 2560 & 128.47 \\
  3028. \hline 3072 & 138.73 \\
  3029. \hline 4096 & 156.49 \\
  3030. \hline
  3031. \end{tabular}
  3032. \end{center}
  3033. The work factor for ECC keys is much higher since the best attack is still fully exponentional. Given a key of magnitude
  3034. $n$ it requires $\sqrt n$ work. The following table sumarizes the work required:
  3035. \begin{center}
  3036. \begin{tabular}{|c|c|}
  3037. \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
  3038. \hline 160 & 80 \\
  3039. \hline 192 & 96 \\
  3040. \hline 224 & 112 \\
  3041. \hline 256 & 128 \\
  3042. \hline 384 & 192 \\
  3043. \hline 521 & 260.5 \\
  3044. \hline
  3045. \end{tabular}
  3046. \end{center}
  3047. Using the above tables the following suggestions for key sizes seems appropriate:
  3048. \begin{center}
  3049. \begin{tabular}{|c|c|c|}
  3050. \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
  3051. \hline Short term (less than a year) & 1024 & 160 \\
  3052. \hline Short term (less than five years) & 1536 & 192 \\
  3053. \hline Long Term (less than ten years) & 2560 & 256 \\
  3054. \hline
  3055. \end{tabular}
  3056. \end{center}
  3057. \section{Thread Safety}
  3058. The library is not thread safe but several simple precautions can be taken to avoid any problems. The registry functions
  3059. such as register\_cipher() are not thread safe no matter what you do. Its best to call them from your programs initializtion
  3060. code before threads are initiated.
  3061. The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
  3062. thread has its own state variables then they will not affect each other. This is fairly simple with symmetric ciphers
  3063. and hashes. However, the keyring and PRNG support is something the threads will want to share. The simplest workaround
  3064. is create semaphores or mutexes around calls to those functions.
  3065. Since C does not have standard semaphores this support is not native to Libtomcrypt. Even a C based semaphore is not entire
  3066. possible as some compilers may ignore the ``volatile'' keyword or have multiple processors. Provide your host application
  3067. is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread
  3068. safety issues within the library.
  3069. \chapter{Configuring and Building the Library}
  3070. \section{Introduction}
  3071. The library is fairly flexible about how it can be built, used and generally distributed. Additions are being made with
  3072. each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
  3073. the build process to make a smaller library. This is particularly useful for shared libraries.
  3074. \section{Building a Static Library}
  3075. The library can be built as a static library which is generally the simplest and most portable method of
  3076. building the library. With a CC or GCC equipped platform you can issue the following
  3077. \begin{alltt}
  3078. make install_lib
  3079. \end{alltt}
  3080. Which will build the library and install it in /usr/lib (as well as the headers in /usr/include). The destination
  3081. directory of the library and headers can be changed by editing ``makefile''. The variable LIBNAME controls
  3082. where the library is to be installed and INCNAME controls where the headers are to be installed. A developer can
  3083. then use the library by including ``tomcrypt.h'' in their program and linking against ``libtomcrypt.a''.
  3084. A static library can also be built with the Intel C Compiler (ICC) by issuing the following
  3085. \begin{alltt}
  3086. make -f makefile.icc install
  3087. \end{alltt}
  3088. This will also build ``libtomcrypt.a'' except that it will use ICC. Additionally Microsoft's Visual C 6.00 can be used
  3089. by issuing
  3090. \begin{alltt}
  3091. nmake -f makefile.msvc
  3092. \end{alltt}
  3093. You will have to manually copy ``tomcrypt.lib'' and the headers to your MSVC lib/inc directories.
  3094. \subsection{MPI Control}
  3095. If you already have LibTomMath installed you can safely remove it from the build. By commenting the line
  3096. in the appropriate makefile which starts with
  3097. \begin{alltt}
  3098. MPIOBJECT=mpi
  3099. \end{alltt}
  3100. Simply place a \# at the start and re-build the library. To properly link applications you will have to also
  3101. link in LibTomMath. Removing MPI has the benefit of cutting down the library size as well potentially have access
  3102. to the latest mpi.
  3103. \section{Building a Shared Library}
  3104. LibTomCrypt can also be built as a shared library (.so, .dll, etc...). With non-Windows platforms the assumption
  3105. of the presence of gcc and ``libtool'' has been made. These are fairly common on Unix/Linux/BSD platforms. To
  3106. build a .so shared library issue
  3107. \begin{alltt}
  3108. make -f makefile.shared
  3109. \end{alltt}
  3110. This will use libtool and gcc to build a shared library ``libtomcrypt.la'' as well as a static library ``libtomcrypt.a''
  3111. and install them into /usr/lib (and the headers into /usr/include). To link your application you should use the
  3112. libtool program in ``--mode=link''.
  3113. \section{mycrypt\_cfg.h}
  3114. The file ``mycrypt\_cfg.h'' is what lets you control various high level macros which control the behaviour
  3115. of the library.
  3116. \subsubsection{ARGTYPE}
  3117. This lets you control how the \_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
  3118. NULL. There are three settings for ARGTYPE. When set to 0 it will have the default behaviour of printing a message to
  3119. stderr and raising a SIGABRT signal. This is provided so all platforms that use libtomcrypt can have an error that functions
  3120. similarly. When set to 1 it will simply pass on to the assert() macro. When set to 2 it will resolve to a empty macro
  3121. and no error checking will be performed.
  3122. \subsubsection{Endianess}
  3123. There are five macros related to endianess issues. For little endian platforms define, ENDIAN\_LITTLE. For big endian
  3124. platforms define ENDIAN\_BIG. Similarly when the default word size of an ``unsigned long'' is 32-bits define ENDIAN\_32BITWORD
  3125. or define ENDIAN\_64BITWORD when its 64-bits. If you do not define any of them the library will automatically use ENDIAN\_NEUTRAL
  3126. which will work on all platforms.
  3127. Currently LibTomCrypt will detect x86-32 and x86-64 running GCC as well as x86-32 running MSVC.
  3128. \section{The Configure Script}
  3129. There are also options you can specify from the configure script or ``mycrypt\_custom.h''.
  3130. \subsection{X memory routines}
  3131. At the top of mycrypt\_custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to
  3132. the name of the respective functions. This lets you substitute in your own memory routines. If you substitute in
  3133. your own functions they must behave like the standard C library functions in terms of what they expect as input and
  3134. output. By default the library uses the standard C routines.
  3135. \subsection{X clock routines}
  3136. The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
  3137. the default clock() used with a replacement. By default the standard C library clock() function is used.
  3138. \subsection{NO\_FILE}
  3139. During the build if NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
  3140. functions and instead simply return CRYPT\_NOP. This should help resolve any linker errors stemming from a lack of
  3141. file I/O on embedded platforms.
  3142. \subsection{CLEAN\_STACK}
  3143. When this functions is defined the functions that store key material on the stack will clean up afterwards.
  3144. Assumes that you have no memory paging with the stack.
  3145. \subsection{LTC\_TEST}
  3146. When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.
  3147. When this has been undefined the tests are removed and if called will return CRYPT\_NOP.
  3148. \subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
  3149. There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
  3150. self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
  3151. dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
  3152. cipher and a hash function.
  3153. \subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
  3154. Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
  3155. to allow some tradeoffs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
  3156. requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
  3157. defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
  3158. tables at a cost of 4KB of memory. The cipher will be much faster as a result.
  3159. When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
  3160. useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
  3161. will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
  3162. it will not speed up the encryption or decryption functions.
  3163. \subsection{GCM\_TABLES}
  3164. When defined GCM will use a 64KB table (per GCM state) which will greatly lower up the per--packet latency.
  3165. It also increases the initialization time.
  3166. \subsection{SMALL\_CODE}
  3167. When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
  3168. These variants are slower but can save quite a bit of code space.
  3169. \subsection{LTC\_FAST}
  3170. This mode (autodetected with x86\_32,x86\_64 platforms with GCC or MSVC) configures various routines such as ctr\_encrypt() or
  3171. cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
  3172. cutting down the overhead of the respective functions.
  3173. This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
  3174. it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_FAST
  3175. is not ``portable'' since unaligned accesses are not covered by the ISO C specifications.
  3176. In practice however, you can use it on pretty much any platform (even MIPS) with care.
  3177. By design the ``fast'' mode functions won't get unaligned on their own. For instance, if you call ctr\_encrypt() right after calling
  3178. ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only. However, if you
  3179. call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
  3180. cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
  3181. whole word XOR operations. These operations will be unaligned.
  3182. The simplest precaution is to make sure you process all data in power of two blocks and handle ``remainder'' at the end. e.g. If you are
  3183. 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.
  3184. If you do plan on using the ``LTC\_FAST'' mode you have to also define a ``LTC\_FAST\_TYPE'' macro which resolves to an optimal sized
  3185. data type you can perform integer operations with. Ideally it should be four or eight bytes since it must properly divide the size
  3186. 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
  3187. use this mode. So sad.
  3188. \section{MPI Tweaks}
  3189. \subsection{RSA Only Tweak}
  3190. If you plan on only using RSA with moduli in the range of 1024 to 2560 bits you can enable a series of tweaks
  3191. to reduce the library size. Follow these steps
  3192. \begin{enumerate}
  3193. \item Undefine MDSA, MECC and MDH from mycrypt\_custom.h
  3194. \item Undefine LTM\_ALL from tommath\_superclass.h
  3195. \item Define SC\_RSA\_1 from tommath\_superclass.h
  3196. \item Rebuild the library.
  3197. \end{enumerate}
  3198. \chapter{Optimizations}
  3199. \section{Introduction}
  3200. The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash or PRNG and dependent API will not require
  3201. updating. This has the nice benefit that I can add ciphers not have to re--write large portions of the API. For the most part LibTomCrypt has also been written
  3202. 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
  3203. about the platform, etc...
  3204. That works well for most cases but there are times where time is of the essence. This API also allows optimized routines to be dropped in--place of the existing
  3205. portable routines. For instance, hand optimized assembler versions of AES could be provided and any existing function that uses the cipher could automatically use
  3206. the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
  3207. At the heart of this flexibility is the ``descriptor'' system. A descriptor is essentially just a C ``struct'' which describes the algorithm and provides pointers
  3208. to functions that do the work. For a given class of operation (e.g. cipher, hash, prng) the functions have identical prototypes which makes development simple. In most
  3209. dependent routines all a developer has to do is register\_XXX() the descriptor and they're set.
  3210. \section{Ciphers}
  3211. The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
  3212. \begin{small}
  3213. \begin{verbatim}
  3214. struct ltc_cipher_descriptor {
  3215. /** name of cipher */
  3216. char *name;
  3217. /** internal ID */
  3218. unsigned char ID;
  3219. /** min keysize (octets) */
  3220. int min_key_length,
  3221. /** max keysize (octets) */
  3222. max_key_length,
  3223. /** block size (octets) */
  3224. block_length,
  3225. /** default number of rounds */
  3226. default_rounds;
  3227. /** Setup the cipher
  3228. @param key The input symmetric key
  3229. @param keylen The length of the input key (octets)
  3230. @param num_rounds The requested number of rounds (0==default)
  3231. @param skey [out] The destination of the scheduled key
  3232. @return CRYPT_OK if successful
  3233. */
  3234. int (*setup)(const unsigned char *key, int keylen,
  3235. int num_rounds, symmetric_key *skey);
  3236. /** Encrypt a block
  3237. @param pt The plaintext
  3238. @param ct [out] The ciphertext
  3239. @param skey The scheduled key
  3240. */
  3241. void (*ecb_encrypt)(const unsigned char *pt,
  3242. unsigned char *ct, symmetric_key *skey);
  3243. /** Decrypt a block
  3244. @param ct The ciphertext
  3245. @param pt [out] The plaintext
  3246. @param skey The scheduled key
  3247. */
  3248. void (*ecb_decrypt)(const unsigned char *ct,
  3249. unsigned char *pt, symmetric_key *skey);
  3250. /** Test the block cipher
  3251. @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
  3252. */
  3253. int (*test)(void);
  3254. /** Determine a key size
  3255. @param keysize [in/out] The size of the key desired and the suggested size
  3256. @return CRYPT_OK if successful
  3257. */
  3258. int (*keysize)(int *keysize);
  3259. /** Accelerators **/
  3260. /** Accelerated ECB encryption
  3261. @param pt Plaintext
  3262. @param ct Ciphertext
  3263. @param blocks The number of complete blocks to process
  3264. @param skey The scheduled key context
  3265. */
  3266. void (*accel_ecb_encrypt)(const unsigned char *pt,
  3267. unsigned char *ct, unsigned long blocks,
  3268. symmetric_key *skey);
  3269. /** Accelerated ECB decryption
  3270. @param pt Plaintext
  3271. @param ct Ciphertext
  3272. @param blocks The number of complete blocks to process
  3273. @param skey The scheduled key context
  3274. */
  3275. void (*accel_ecb_decrypt)(const unsigned char *ct,
  3276. unsigned char *pt, unsigned long blocks,
  3277. symmetric_key *skey);
  3278. /** Accelerated CBC encryption
  3279. @param pt Plaintext
  3280. @param ct Ciphertext
  3281. @param blocks The number of complete blocks to process
  3282. @param IV The initial value (input/output)
  3283. @param skey The scheduled key context
  3284. */
  3285. void (*accel_cbc_encrypt)(const unsigned char *pt,
  3286. unsigned char *ct, unsigned long blocks,
  3287. unsigned char *IV, symmetric_key *skey);
  3288. /** Accelerated CBC decryption
  3289. @param pt Plaintext
  3290. @param ct Ciphertext
  3291. @param blocks The number of complete blocks to process
  3292. @param IV The initial value (input/output)
  3293. @param skey The scheduled key context
  3294. */
  3295. void (*accel_cbc_decrypt)(const unsigned char *ct,
  3296. unsigned char *pt, unsigned long blocks,
  3297. unsigned char *IV, symmetric_key *skey);
  3298. /** Accelerated CTR encryption
  3299. @param pt Plaintext
  3300. @param ct Ciphertext
  3301. @param blocks The number of complete blocks to process
  3302. @param IV The initial value (input/output)
  3303. @param mode little or big endian counter (mode=0 or mode=1)
  3304. @param skey The scheduled key context
  3305. */
  3306. void (*accel_ctr_encrypt)(const unsigned char *pt,
  3307. unsigned char *ct, unsigned long blocks,
  3308. unsigned char *IV, int mode, symmetric_key *skey);
  3309. /** Accelerated CCM packet (one-shot)
  3310. @param key The secret key to use
  3311. @param keylen The length of the secret key (octets)
  3312. @param nonce The session nonce [use once]
  3313. @param noncelen The length of the nonce
  3314. @param header The header for the session
  3315. @param headerlen The length of the header (octets)
  3316. @param pt [out] The plaintext
  3317. @param ptlen The length of the plaintext (octets)
  3318. @param ct [out] The ciphertext
  3319. @param tag [out] The destination tag
  3320. @param taglen [in/out] The max size and resulting size of the authentication tag
  3321. @param direction Encrypt or Decrypt direction (0 or 1)
  3322. @return CRYPT_OK if successful
  3323. */
  3324. void (*accel_ccm_memory)(
  3325. const unsigned char *key, unsigned long keylen,
  3326. const unsigned char *nonce, unsigned long noncelen,
  3327. const unsigned char *header, unsigned long headerlen,
  3328. unsigned char *pt, unsigned long ptlen,
  3329. unsigned char *ct,
  3330. unsigned char *tag, unsigned long *taglen,
  3331. int direction);
  3332. /** Accelerated GCM packet (one shot)
  3333. @param key The secret key
  3334. @param keylen The length of the secret key
  3335. @param IV The initial vector
  3336. @param IVlen The length of the initial vector
  3337. @param adata The additional authentication data (header)
  3338. @param adatalen The length of the adata
  3339. @param pt The plaintext
  3340. @param ptlen The length of the plaintext (ciphertext length is the same)
  3341. @param ct The ciphertext
  3342. @param tag [out] The MAC tag
  3343. @param taglen [in/out] The MAC tag length
  3344. @param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
  3345. */
  3346. void (*accel_gcm_memory)(
  3347. const unsigned char *key, unsigned long keylen,
  3348. const unsigned char *IV, unsigned long IVlen,
  3349. const unsigned char *adata, unsigned long adatalen,
  3350. unsigned char *pt, unsigned long ptlen,
  3351. unsigned char *ct,
  3352. unsigned char *tag, unsigned long *taglen,
  3353. int direction);
  3354. };
  3355. \end{verbatim}
  3356. \end{small}
  3357. \subsection{Name}
  3358. The ``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
  3359. tables.
  3360. \subsection{Internal ID}
  3361. This is a single byte Internal ID you can use to distingish ciphers from each other.
  3362. \subsection{Key Lengths}
  3363. The minimum key length is ``min\_key\_length'' and is measured in octets. Similarly the maximum key length is ``max\_key\_length''. They can be equal
  3364. and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
  3365. \subsection{Block Length}
  3366. The size of the ciphers plaintext or ciphertext is ``block\_length'' and is measured in octets.
  3367. \subsection{Rounds}
  3368. Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is ``default\_rounds''.
  3369. \subsection{Setup}
  3370. To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets ``key'' of length ``keylen'' octets. The user
  3371. can specify the number of rounds they want through ``num\_rounds'' where $num\_rounds = 0$ means use the default. The destination of a scheduled key is stored
  3372. in ``skey''.
  3373. This is where things get tricky. Currently there is no provision to allocate memory during initialization since there is no ``cipher done'' function. So you have
  3374. to either use an existing member of the symmetric\_key union or alias your own structure over top of it provided symmetric\_key is not smaller.
  3375. \subsection{Single block ECB}
  3376. 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
  3377. must make sure you do not overwrite the output before you are finished with the input.
  3378. \subsection{Testing}
  3379. The test() function is used to self--test the ``device''. It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly.
  3380. \subsection{Key Sizing}
  3381. 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
  3382. 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
  3383. 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
  3384. cannot be mapped to a valid key size for the cipher.
  3385. \subsection{Acceleration}
  3386. 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
  3387. it is not supported. In those cases the software fallbacks are used (using the single ECB block routines).
  3388. \subsubsection{Accelerated ECB}
  3389. 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
  3390. through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The ``blocks'' count is the number of complete blocks to process.
  3391. \subsubsection{Accelerated CBC}
  3392. These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
  3393. The ``blocks'' value is the number of complete blocks to process. The ``IV'' is the CBC initial vector. It is an input upon calling this function and must be
  3394. updated by the function before returning.
  3395. \subsubsection{Accelerated CTR}
  3396. This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
  3397. The ``blocks'' value is the number of complete blocks to process. The ``IV'' is the CTR counter vector. It is an input upon calling this function and must be
  3398. updated by the function before returning. The ``mode'' value indicates whether the counter is big ($mode = 1$) or little ($mode = 0$) endian.
  3399. 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
  3400. called if the following conditions are met.
  3401. \begin{enumerate}
  3402. \item The accelerator is present
  3403. \item The CTR pad is empty
  3404. \item The remaining length of the input to process is greater than or equal to the block size.
  3405. \end{enumerate}
  3406. The ``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
  3407. 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
  3408. buffer provided) before encrypting it to create the pad.
  3409. The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
  3410. \subsubsection{Accelerated CCM}
  3411. This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. Note that the setup() function will not
  3412. be called prior to this. This function must handle scheduling the key provided on its own.
  3413. \subsubsection{Accelerated GCM}
  3414. 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
  3415. be called prior to this. This function must handle scheduling the key provided on its own.
  3416. \section{One--Way Hashes}
  3417. The hash functions are accessed through the ltc\_hash\_descriptor structure.
  3418. \begin{small}
  3419. \begin{verbatim}
  3420. struct ltc_hash_descriptor {
  3421. /** name of hash */
  3422. char *name;
  3423. /** internal ID */
  3424. unsigned char ID;
  3425. /** Size of digest in octets */
  3426. unsigned long hashsize;
  3427. /** Input block size in octets */
  3428. unsigned long blocksize;
  3429. /** ASN.1 DER identifier */
  3430. unsigned char DER[64];
  3431. /** Length of DER encoding */
  3432. unsigned long DERlen;
  3433. /** Init a hash state
  3434. @param hash The hash to initialize
  3435. @return CRYPT_OK if successful
  3436. */
  3437. int (*init)(hash_state *hash);
  3438. /** Process a block of data
  3439. @param hash The hash state
  3440. @param in The data to hash
  3441. @param inlen The length of the data (octets)
  3442. @return CRYPT_OK if successful
  3443. */
  3444. int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
  3445. /** Produce the digest and store it
  3446. @param hash The hash state
  3447. @param out [out] The destination of the digest
  3448. @return CRYPT_OK if successful
  3449. */
  3450. int (*done)(hash_state *hash, unsigned char *out);
  3451. /** Self-test
  3452. @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
  3453. */
  3454. int (*test)(void);
  3455. };
  3456. \end{verbatim}
  3457. \end{small}
  3458. \subsection{Name}
  3459. This is the name the hash is known by and what find\_hash() will look for.
  3460. \subsection{Internal ID}
  3461. This is the internal ID byte used to distinguish the hash from other hashes.
  3462. \subsection{Digest Size}
  3463. The ``hashsize'' variable indicates the length of the output in octets.
  3464. \subsection{Block Size}
  3465. The `blocksize'' variable indicates the length of input (in octets) that the hash processes in a given
  3466. invokation.
  3467. \subsection{DER Identifier}
  3468. This is the DER identifier (including the SEQUENCE header). This is used solely for PKCS \#1 style signatures.
  3469. \subsection{Initialization}
  3470. The init function initializes the hash and prepares it to process message bytes.
  3471. \subsection{Process}
  3472. This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
  3473. guaranteed to be a multiple of the block size in length.
  3474. \subsection{Done}
  3475. The done function terminates the hash and returns the message digest.
  3476. \subsection{Acceleration}
  3477. A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
  3478. \section{Pseudo--Random Number Generators}
  3479. The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
  3480. \begin{small}
  3481. \begin{verbatim}
  3482. struct ltc_prng_descriptor {
  3483. /** Name of the PRNG */
  3484. char *name;
  3485. /** size in bytes of exported state */
  3486. int export_size;
  3487. /** Start a PRNG state
  3488. @param prng [out] The state to initialize
  3489. @return CRYPT_OK if successful
  3490. */
  3491. int (*start)(prng_state *prng);
  3492. /** Add entropy to the PRNG
  3493. @param in The entropy
  3494. @param inlen Length of the entropy (octets)\
  3495. @param prng The PRNG state
  3496. @return CRYPT_OK if successful
  3497. */
  3498. int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
  3499. /** Ready a PRNG state to read from
  3500. @param prng The PRNG state to ready
  3501. @return CRYPT_OK if successful
  3502. */
  3503. int (*ready)(prng_state *prng);
  3504. /** Read from the PRNG
  3505. @param out [out] Where to store the data
  3506. @param outlen Length of data desired (octets)
  3507. @param prng The PRNG state to read from
  3508. @return Number of octets read
  3509. */
  3510. unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
  3511. /** Terminate a PRNG state
  3512. @param prng The PRNG state to terminate
  3513. @return CRYPT_OK if successful
  3514. */
  3515. int (*done)(prng_state *prng);
  3516. /** Export a PRNG state
  3517. @param out [out] The destination for the state
  3518. @param outlen [in/out] The max size and resulting size of the PRNG state
  3519. @param prng The PRNG to export
  3520. @return CRYPT_OK if successful
  3521. */
  3522. int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
  3523. /** Import a PRNG state
  3524. @param in The data to import
  3525. @param inlen The length of the data to import (octets)
  3526. @param prng The PRNG to initialize/import
  3527. @return CRYPT_OK if successful
  3528. */
  3529. int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
  3530. /** Self-test the PRNG
  3531. @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
  3532. */
  3533. int (*test)(void);
  3534. };
  3535. \end{verbatim}
  3536. \end{small}
  3537. \subsection{Name}
  3538. The name by which find\_prng() will find the PRNG.
  3539. \subsection{Export Size}
  3540. When an PRNG state is to be exported for future use you specify the space required in this variable.
  3541. \subsection{Start}
  3542. Initialize the PRNG and make it ready to accept entropy.
  3543. \subsection{Entropy Addition}
  3544. Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
  3545. \subsection{Ready}
  3546. This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
  3547. on the specific PRNG used.
  3548. \subsection{Read}
  3549. Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
  3550. if it does as many protocols do not retry reads and will fail on the first try.
  3551. \subsection{Done}
  3552. Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
  3553. \subsection{Exporting and Importing}
  3554. An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume ``the same session''
  3555. but should at least maintain the same level of state entropy.
  3556. \input{crypt.ind}
  3557. \end{document}