I2C toy code
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

7327 rindas
320 KiB

  1. \documentclass[synpaper]{book}
  2. \usepackage[dvips]{geometry}
  3. \usepackage{hyperref}
  4. \usepackage{makeidx}
  5. \usepackage{amssymb}
  6. \usepackage{color}
  7. \usepackage{alltt}
  8. \usepackage{graphicx}
  9. \usepackage{layout}
  10. \usepackage{fancyhdr}
  11. \def\union{\cup}
  12. \def\intersect{\cap}
  13. \def\getsrandom{\stackrel{\rm R}{\gets}}
  14. \def\cross{\times}
  15. \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
  16. \def\catn{$\|$}
  17. \def\divides{\hspace{0.3em} | \hspace{0.3em}}
  18. \def\nequiv{\not\equiv}
  19. \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
  20. \def\lcm{{\rm lcm}}
  21. \def\gcd{{\rm gcd}}
  22. \def\log{{\rm log}}
  23. \def\ord{{\rm ord}}
  24. \def\abs{{\mathit abs}}
  25. \def\rep{{\mathit rep}}
  26. \def\mod{{\mathit\ mod\ }}
  27. \renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
  28. \newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
  29. \newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
  30. \def\Or{{\rm\ or\ }}
  31. \def\And{{\rm\ and\ }}
  32. \def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
  33. \def\implies{\Rightarrow}
  34. \def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
  35. \let\oldphi\phi
  36. \def\phi{\varphi}
  37. \def\Pr{{\rm Pr}}
  38. \newcommand{\str}[1]{{\mathbf{#1}}}
  39. \def\F{{\mathbb F}}
  40. \def\N{{\mathbb N}}
  41. \def\Z{{\mathbb Z}}
  42. \def\R{{\mathbb R}}
  43. \def\C{{\mathbb C}}
  44. \def\Q{{\mathbb Q}}
  45. \definecolor{DGray}{gray}{0.5}
  46. \newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
  47. \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
  48. \def\gap{\vspace{0.5ex}}
  49. \makeindex
  50. \newcommand{\mysection}[1] % Re-define the chaptering command to use
  51. { % THESE headers.
  52. \section{#1}
  53. \markboth{\textsf{www.libtom.net}}{\thesection ~ {#1}}
  54. }
  55. \newcommand{\mystarsection}[1] % Re-define the chaptering command to use
  56. { % THESE headers.
  57. \section*{#1}
  58. \markboth{\textsf{www.libtom.net}}{{#1}}
  59. }
  60. \pagestyle{empty}
  61. \begin{document}
  62. \frontmatter
  63. \pagestyle{empty}
  64. ~
  65. \vspace{2in}
  66. ~
  67. \begin{center}
  68. \begin{Huge}LibTomCrypt\end{Huge}
  69. ~
  70. \begin{large}Developer Manual\end{large}
  71. ~
  72. \vspace{15mm}
  73. \begin{tabular}{c}
  74. LibTom Projects
  75. \end{tabular}
  76. \end{center}
  77. \vfil
  78. \newpage
  79. This document is part of the LibTomCrypt package and is hereby released into the public domain.
  80. ~
  81. Open Source. Open Academia. Open Minds.
  82. ~
  83. \begin{flushright}
  84. LibTom Projects
  85. ~
  86. \& originally
  87. ~
  88. Tom St Denis
  89. ~
  90. Ottawa, Ontario
  91. ~
  92. Canada
  93. ~
  94. \vfil
  95. \end{flushright}
  96. \newpage
  97. \tableofcontents
  98. \listoffigures
  99. \pagestyle{myheadings}
  100. \mainmatter
  101. \chapter{Introduction}
  102. \mysection{What is the LibTomCrypt?}
  103. LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
  104. designing cryptosystems. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
  105. public key cryptography (via PKCS \#1 RSA, DH or ECCDH), and a plethora of support routines.
  106. The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
  107. (and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
  108. block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
  109. also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
  110. \subsection{What the library IS for?}
  111. The library serves as a toolkit for developers who have to solve cryptographic problems. Out of the box LibTomCrypt
  112. does not process SSL or OpenPGP messages, it doesn't read X.509 certificates, or write PEM encoded data. It does, however,
  113. provide all of the tools required to build such functionality. LibTomCrypt was designed to be a flexible library that
  114. was not tied to any particular cryptographic problem.
  115. \mysection{Why did I write it?}
  116. You may be wondering, \textit{Tom, why did you write a crypto library. I already have one.} Well the reason falls into
  117. two categories:
  118. \begin{enumerate}
  119. \item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
  120. \item It was (still is) good coding practice.
  121. \end{enumerate}
  122. The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
  123. {\bf own} crypto library and hopefully along the way others will appreciate the work.
  124. With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
  125. and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
  126. on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
  127. know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
  128. that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time. That means your
  129. application can support all ciphers/hashes/prngs/bignum without changing the source code.
  130. Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
  131. configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
  132. without having to use configure scripts. This means that the library will work with platforms where development
  133. tools may be limited (e.g. no autoconf).
  134. On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
  135. robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
  136. arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
  137. with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
  138. Crypto++.
  139. \subsection{Modular}
  140. The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
  141. pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
  142. are essentially structures with pointers to functions. While you can still call particular functions
  143. directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
  144. usage of the library.
  145. For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
  146. that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
  147. is write a descriptor and the few support routines required for the device. After that the rest of the
  148. API can make use of it without change. Similarly imagine a few years down the road when AES2
  149. (\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
  150. with zero modifications to the end applications provided they are written properly.
  151. This flexibility within the library means it can be used with any combination of primitive algorithms and
  152. unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
  153. mode routines for every single cipher. That means every time you add or remove a cipher from the library
  154. you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
  155. are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
  156. the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
  157. can make use of the cipher right away.
  158. \mysection{License}
  159. The project is hereby released as public domain.
  160. \mysection{Patent Disclosure}
  161. The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
  162. of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
  163. They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}. The rest
  164. of the ciphers and hashes are patent free or under patents that have since expired.
  165. The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
  166. the ciphers you just can't advertise that you are doing so.
  167. \mysection{Thanks}
  168. I would like to give thanks to the following people (in no particular order) for helping me develop this project from
  169. early on:
  170. \begin{enumerate}
  171. \item Richard van de Laarschot
  172. \item Richard Heathfield
  173. \item Ajay K. Agrawal
  174. \item Brian Gladman
  175. \item Svante Seleborg
  176. \item Clay Culver
  177. \item Jason Klapste
  178. \item Dobes Vandermeer
  179. \item Daniel Richards
  180. \item Wayne Scott
  181. \item Andrew Tyler
  182. \item Sky Schulz
  183. \item Christopher Imes
  184. \end{enumerate}
  185. There have been quite a few other people as well. Please check the change log to see who else has contributed from
  186. time to time.
  187. \chapter{The Application Programming Interface (API)}
  188. \mysection{Introduction}
  189. \index{CRYPT\_ERROR} \index{CRYPT\_OK}
  190. In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
  191. that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
  192. if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
  193. commented upon. When a function does return a CRYPT error code it can be translated into a string with
  194. \index{error\_to\_string()}
  195. \begin{verbatim}
  196. const char *error_to_string(int err);
  197. \end{verbatim}
  198. An example of handling an error is:
  199. \begin{small}
  200. \begin{verbatim}
  201. void somefunc(void)
  202. {
  203. int err;
  204. /* call a cryptographic function */
  205. if ((err = some_crypto_function(...)) != CRYPT_OK) {
  206. printf("A crypto error occurred, %s\n", error_to_string(err));
  207. /* perform error handling */
  208. }
  209. /* continue on if no error occurred */
  210. }
  211. \end{verbatim}
  212. \end{small}
  213. There is no initialization routine for the library and for the most part the code is thread safe. The only thread
  214. related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
  215. that is not an issue.
  216. To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
  217. \begin{small}
  218. \begin{verbatim}
  219. #include <tomcrypt.h>
  220. int main(void) {
  221. return 0;
  222. }
  223. \end{verbatim}
  224. \end{small}
  225. The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
  226. \mysection{Macros}
  227. There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
  228. 32/64-bit words in little/big endian format. The macros are:
  229. \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
  230. \newpage
  231. \begin{figure}[hpbt]
  232. \begin{small}
  233. \begin{center}
  234. \begin{tabular}{|c|c|c|}
  235. \hline STORE32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
  236. \hline STORE64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
  237. \hline LOAD32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
  238. \hline LOAD64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
  239. \hline STORE32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
  240. \hline STORE64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
  241. \hline LOAD32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
  242. \hline LOAD64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
  243. \hline BSWAP(x) & {\bf ulong32} x & Swap bytes \\
  244. \hline
  245. \end{tabular}
  246. \caption{Load And Store Macros}
  247. \end{center}
  248. \end{small}
  249. \end{figure}
  250. There are 32 and 64-bit cyclic rotations as well:
  251. \index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
  252. \begin{figure}[hpbt]
  253. \begin{small}
  254. \begin{center}
  255. \begin{tabular}{|c|c|c|}
  256. \hline ROL(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x << y, 0 \le y \le 31$ \\
  257. \hline ROLc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x << y, 0 \le y \le 31$ \\
  258. \hline ROR(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x >> y, 0 \le y \le 31$ \\
  259. \hline RORc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x >> y, 0 \le y \le 31$ \\
  260. \hline && \\
  261. \hline ROL64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x << y, 0 \le y \le 63$ \\
  262. \hline ROL64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x << y, 0 \le y \le 63$ \\
  263. \hline ROR64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x >> y, 0 \le y \le 63$ \\
  264. \hline ROR64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x >> y, 0 \le y \le 63$ \\
  265. \hline
  266. \end{tabular}
  267. \caption{Rotate Macros}
  268. \end{center}
  269. \end{small}
  270. \end{figure}
  271. \mysection{Functions with Variable Length Output}
  272. Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length. To prevent buffer overflows you
  273. must pass it the length of the buffer where the output will be stored. For example:
  274. \index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
  275. \begin{small}
  276. \begin{verbatim}
  277. #include <tomcrypt.h>
  278. int main(void) {
  279. rsa_key key;
  280. unsigned char buffer[1024];
  281. unsigned long x;
  282. int err;
  283. /* ... Make up the RSA key somehow ... */
  284. /* lets export the key, set x to the size of the
  285. * output buffer */
  286. x = sizeof(buffer);
  287. if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
  288. printf("Export error: %s\n", error_to_string(err));
  289. return -1;
  290. }
  291. /* if rsa_export() was successful then x will have
  292. * the size of the output */
  293. printf("RSA exported key takes %d bytes\n", x);
  294. /* ... do something with the buffer */
  295. return 0;
  296. }
  297. \end{verbatim}
  298. \end{small}
  299. In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
  300. indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
  301. \textit{x} so that the calling application will know how many bytes were used.
  302. As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
  303. support this so please check the source before you rely on it doing that.
  304. \mysection{Functions that need a PRNG}
  305. \index{Pseudo Random Number Generator} \index{PRNG}
  306. Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG). These functions do not setup
  307. the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
  308. Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example). The \textit{prng\_state} argument
  309. may be passed as \textbf{NULL} in such situations.
  310. \index{register\_prng()} \index{rsa\_make\_key()}
  311. \begin{small}
  312. \begin{verbatim}
  313. #include <tomcrypt.h>
  314. int main(void) {
  315. rsa_key key;
  316. int err;
  317. /* register the system RNG */
  318. register_prng(&sprng_desc)
  319. /* make a 1024-bit RSA key with the system RNG */
  320. if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key))
  321. != CRYPT_OK) {
  322. printf("make_key error: %s\n", error_to_string(err));
  323. return -1;
  324. }
  325. /* use the key ... */
  326. return 0;
  327. }
  328. \end{verbatim}
  329. \end{small}
  330. \mysection{Functions that use Arrays of Octets}
  331. Most functions require inputs that are arrays of the data type \textit{unsigned char}. Whether it is a symmetric key, IV
  332. for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
  333. lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
  334. must pass in (a pointer to) an array of 32 \textit{unsigned char} variables. Certain routines (such as SAFER+) take
  335. special care to work properly on platforms where an \textit{unsigned char} is not eight bits.
  336. For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word. Typically an array of
  337. type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}
  338. \chapter{Symmetric Block Ciphers}
  339. \mysection{Core Functions}
  340. LibTomCrypt provides several block ciphers with an ECB block mode interface. It is important to first note that you
  341. should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
  342. or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
  343. the API to grow in a modular fashion.
  344. \subsection{Key Scheduling}
  345. All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}. This allows all ciphers to
  346. have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
  347. allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers must provide six visible
  348. functions which are (given that XXX is the name of the cipher) the following:
  349. \index{Cipher Setup}
  350. \begin{verbatim}
  351. int XXX_setup(const unsigned char *key,
  352. int keylen,
  353. int rounds,
  354. symmetric_key *skey);
  355. \end{verbatim}
  356. The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
  357. The number of rounds can be set to zero to use the default, which is generally a good idea.
  358. If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it. It's important to note
  359. that you should only used this scheduled key with the intended cipher. For example, if you call \textit{blowfish\_setup()} do not
  360. pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}. All built--in setup functions do not allocate memory off the heap so
  361. when you are done with a key you can simply discard it (e.g. they can be on the stack). However, to maintain proper coding
  362. practices you should always call the respective XXX\_done() function. This allows for quicker porting to applications with
  363. externally supplied plugins.
  364. \subsection{ECB Encryption and Decryption}
  365. To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
  366. \index{Cipher Encrypt} \index{Cipher Decrypt}
  367. \begin{verbatim}
  368. int XXX_ecb_encrypt(const unsigned char *pt,
  369. unsigned char *ct,
  370. symmetric_key *skey);
  371. int XXX_ecb_decrypt(const unsigned char *ct,
  372. unsigned char *pt,
  373. symmetric_key *skey);
  374. \end{verbatim}
  375. These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
  376. which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.). It is possible that the input and output buffer are
  377. the same buffer. For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
  378. \textit{ct}\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
  379. return \textbf{CRYPT\_OK} on success. To test a particular cipher against test vectors\footnote{As published in their design papers.}
  380. call the following self-test function.
  381. \subsection{Self--Testing}
  382. \index{Cipher Testing}
  383. \begin{verbatim}
  384. int XXX_test(void);
  385. \end{verbatim}
  386. This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
  387. based upon.
  388. \subsection{Key Sizing}
  389. For each cipher there is a function which will help find a desired key size. It is specified as follows:
  390. \index{Key Sizing}
  391. \begin{verbatim}
  392. int XXX_keysize(int *keysize);
  393. \end{verbatim}
  394. Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size. This function
  395. will return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
  396. \begin{small}
  397. \begin{verbatim}
  398. #include <tomcrypt.h>
  399. int main(void)
  400. {
  401. int keysize, err;
  402. /* now given a 20 byte key what keysize does Twofish want to use? */
  403. keysize = 20;
  404. if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
  405. printf("Error getting key size: %s\n", error_to_string(err));
  406. return -1;
  407. }
  408. printf("Twofish suggested a key size of %d\n", keysize);
  409. return 0;
  410. }
  411. \end{verbatim}
  412. \end{small}
  413. This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}
  414. \subsection{Cipher Termination}
  415. When you are finished with a cipher you can de--initialize it with the done function.
  416. \begin{verbatim}
  417. void XXX_done(symmetric_key *skey);
  418. \end{verbatim}
  419. For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
  420. cipher descriptors may require to be called for resource management purposes. To be compliant, all functions which call a cipher
  421. setup function must also call the respective cipher done function when finished.
  422. \subsection{Simple Encryption Demonstration}
  423. An example snippet that encodes a block with Blowfish in ECB mode.
  424. \index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
  425. \begin{small}
  426. \begin{verbatim}
  427. #include <tomcrypt.h>
  428. int main(void)
  429. {
  430. unsigned char pt[8], ct[8], key[8];
  431. symmetric_key skey;
  432. int err;
  433. /* ... key is loaded appropriately in key ... */
  434. /* ... load a block of plaintext in pt ... */
  435. /* schedule the key */
  436. if ((err = blowfish_setup(key, /* the key we will use */
  437. 8, /* key is 8 bytes (64-bits) long */
  438. 0, /* 0 == use default # of rounds */
  439. &skey) /* where to put the scheduled key */
  440. ) != CRYPT_OK) {
  441. printf("Setup error: %s\n", error_to_string(err));
  442. return -1;
  443. }
  444. /* encrypt the block */
  445. blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
  446. ct, /* store encrypted data here */
  447. &skey); /* our previously scheduled key */
  448. /* now ct holds the encrypted version of pt */
  449. /* decrypt the block */
  450. blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
  451. pt, /* store decrypted data here */
  452. &skey); /* our previously scheduled key */
  453. /* now we have decrypted ct to the original plaintext in pt */
  454. /* Terminate the cipher context */
  455. blowfish_done(&skey);
  456. return 0;
  457. }
  458. \end{verbatim}
  459. \end{small}
  460. \mysection{Key Sizes and Number of Rounds}
  461. \index{Symmetric Keys}
  462. As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it. Only a few of the ciphers support smaller
  463. keys (mainly for test vectors anyways). Ideally, your application should be making at least 256 bit keys. This is not
  464. because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
  465. example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
  466. total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
  467. were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
  468. only 53 bits of entropy.
  469. The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
  470. rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
  471. ciphers are configured such that the default number of rounds provide adequate security for the given block and key
  472. size.
  473. \mysection{The Cipher Descriptors}
  474. \index{Cipher Descriptor}
  475. To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}. An element
  476. of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
  477. \begin{small}
  478. \begin{verbatim}
  479. struct _cipher_descriptor {
  480. /** name of cipher */
  481. char *name;
  482. /** internal ID */
  483. unsigned char ID;
  484. /** min keysize (octets) */
  485. int min_key_length,
  486. /** max keysize (octets) */
  487. max_key_length,
  488. /** block size (octets) */
  489. block_length,
  490. /** default number of rounds */
  491. default_rounds;
  492. ...<snip>...
  493. };
  494. \end{verbatim}
  495. \end{small}
  496. Where \textit{name} is the lower case ASCII version of the name. The fields \textit{min\_key\_length} and \textit{max\_key\_length}
  497. are the minimum and maximum key sizes in bytes. The \textit{block\_length} member is the block size of the cipher
  498. in bytes. As a good rule of thumb it is assumed that the cipher supports
  499. the min and max key lengths but not always everything in between. The \textit{default\_rounds} field is the default number
  500. of rounds that will be used.
  501. For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
  502. and if missing will be emulated in software.
  503. The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
  504. marked when \textit{name} equals {\bf NULL}.
  505. As of this release the current cipher\_descriptors elements are the following:
  506. \vfil
  507. \index{Cipher descriptor table}
  508. \index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
  509. \index{des\_desc} \index{des3\_desc} \index{noekeon\_desc} \index{skipjack\_desc} \index{anubis\_desc} \index{khazad\_desc} \index{kseed\_desc} \index{kasumi\_desc} \index{camellia\_desc} \index{aes\_enc\_desc}
  510. \begin{figure}[hpbt]
  511. \begin{small}
  512. \begin{center}
  513. \begin{tabular}{|c|c|c|c|c|c|}
  514. \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} \\
  515. \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
  516. \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
  517. \hline RC2 & rc2\_desc & 8 & 5 $\ldots$ 128 & 16 \\
  518. \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
  519. \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
  520. \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
  521. \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
  522. & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
  523. \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
  524. \hline DES & des\_desc & 8 & 8 & 16 \\
  525. \hline 3DES (EDE mode) & des3\_desc & 8 & 16, 24 & 16 \\
  526. \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
  527. \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
  528. \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
  529. \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
  530. \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
  531. \hline SEED & kseed\_desc & 16 & 16 & 16 \\
  532. \hline KASUMI & kasumi\_desc & 8 & 16 & 8 \\
  533. \hline Camellia & camellia\_desc & 16 & 16, 24, 32 & 18, 24 \\
  534. \hline
  535. \end{tabular}
  536. \end{center}
  537. \end{small}
  538. \caption{Built--In Software Ciphers}
  539. \end{figure}
  540. \subsection{Notes}
  541. \begin{small}
  542. \begin{enumerate}
  543. \item
  544. For AES, (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
  545. rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}. The descriptors aes\_desc and
  546. aes\_enc\_desc provide the cipher name \textit{aes}. Functionally both \textit{rijndael} and \textit{aes} are the same cipher. The
  547. only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with \textit{enc}
  548. in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
  549. and tables. The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
  550. should not be called.
  551. The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
  552. as EAX, PMAC and OMAC only require the encryption function. So far this \textit{encrypt only} functionality has only been implemented for
  553. Rijndael as it makes the most sense for this cipher.
  554. \item
  555. Note that for \textit{DES} and \textit{3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
  556. 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
  557. byte string from the real 7/21 byte key.
  558. For \textit{3DES} exists a two-key mode, that can be initialized by calling the setup function with a \textit{keylen} of 16. This results in the re-usage of key \textit{K1} as key \textit{K3}. This mode has been specified as \textit{Keying Option 2} in FIPS 46-3.
  559. \item
  560. Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time. These options are found in
  561. the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
  562. to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
  563. key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
  564. 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
  565. by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
  566. speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
  567. Twofish round function.
  568. \begin{figure}[hpbt]
  569. \index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
  570. \begin{small}
  571. \begin{center}
  572. \begin{tabular}{|l|l|l|}
  573. \hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
  574. \hline undefined & undefined & Very fast, 4.2KB of ram. \\
  575. \hline undefined & defined & Faster key setup, larger code. \\
  576. \hline defined & undefined & Very slow, 0.2KB of ram. \\
  577. \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
  578. \hline
  579. \end{tabular}
  580. \end{center}
  581. \end{small}
  582. \caption{Twofish Build Options}
  583. \label{fig:twofishopts}
  584. \end{figure}
  585. \end{enumerate}
  586. \end{small}
  587. To work with the cipher\_descriptor array there is a function:
  588. \index{find\_cipher()}
  589. \begin{verbatim}
  590. int find_cipher(char *name)
  591. \end{verbatim}
  592. Which will search for a given name in the array. It returns $-1$ if the cipher is not found, otherwise it returns
  593. the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
  594. \begin{small}
  595. \index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
  596. \begin{verbatim}
  597. #include <tomcrypt.h>
  598. int main(void)
  599. {
  600. unsigned char key[8];
  601. symmetric_key skey;
  602. int err;
  603. /* you must register a cipher before you use it */
  604. if (register_cipher(&blowfish_desc)) == -1) {
  605. printf("Unable to register Blowfish cipher.");
  606. return -1;
  607. }
  608. /* generic call to function (assuming the key
  609. * in key[] was already setup) */
  610. if ((err =
  611. cipher_descriptor[find_cipher("blowfish")].
  612. setup(key, 8, 0, &skey)) != CRYPT_OK) {
  613. printf("Error setting up Blowfish: %s\n", error_to_string(err));
  614. return -1;
  615. }
  616. /* ... use cipher ... */
  617. }
  618. \end{verbatim}
  619. \end{small}
  620. A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function. In order
  621. to use a cipher with the descriptor table you must register it first using:
  622. \index{register\_cipher()}
  623. \begin{verbatim}
  624. int register_cipher(const struct _cipher_descriptor *cipher);
  625. \end{verbatim}
  626. Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
  627. 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
  628. than once it will just return the index of the first copy. To remove a cipher call:
  629. \index{unregister\_cipher()}
  630. \begin{verbatim}
  631. int unregister_cipher(const struct _cipher_descriptor *cipher);
  632. \end{verbatim}
  633. Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
  634. \begin{small}
  635. \begin{verbatim}
  636. #include <tomcrypt.h>
  637. int main(void)
  638. {
  639. int err;
  640. /* register the cipher */
  641. if (register_cipher(&rijndael_desc) == -1) {
  642. printf("Error registering Rijndael\n");
  643. return -1;
  644. }
  645. /* use Rijndael */
  646. /* remove it */
  647. if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
  648. printf("Error removing Rijndael: %s\n", error_to_string(err));
  649. return -1;
  650. }
  651. return 0;
  652. }
  653. \end{verbatim}
  654. \end{small}
  655. This snippet is a small program that registers Rijndael.
  656. \mysection{Symmetric Modes of Operations}
  657. \subsection{Background}
  658. A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
  659. size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
  660. $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
  661. \subsubsection{ECB Mode}
  662. \index{ECB mode}
  663. ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
  664. \begin{equation}
  665. C_i = E_k(P_i)
  666. \end{equation}
  667. This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
  668. than once.
  669. \subsubsection{CBC Mode}
  670. \index{CBC mode}
  671. CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
  672. It is given as:
  673. \begin{equation}
  674. C_i = E_k(P_i \oplus C_{i - 1})
  675. \end{equation}
  676. It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
  677. \subsubsection{CTR Mode}
  678. \index{CTR mode}
  679. CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
  680. treated as a large binary counter the CTR mode is given as:
  681. \begin{eqnarray}
  682. C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
  683. C_i = P_i \oplus E_k(C_{-1})
  684. \end{eqnarray}
  685. 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
  686. encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
  687. as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
  688. \subsubsection{CFB Mode}
  689. \index{CFB mode}
  690. CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
  691. \begin{eqnarray}
  692. C_i = P_i \oplus C_{-1} \nonumber \\
  693. C_{-1} = E_k(C_i)
  694. \end{eqnarray}
  695. Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
  696. to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
  697. blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
  698. \subsubsection{OFB Mode}
  699. \index{OFB mode}
  700. OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
  701. \begin{eqnarray}
  702. C_{-1} = E_k(C_{-1}) \nonumber \\
  703. C_i = P_i \oplus C_{-1}
  704. \end{eqnarray}
  705. Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
  706. buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
  707. \subsection{Choice of Mode}
  708. My personal preference is for the CTR mode since it has several key benefits:
  709. \begin{enumerate}
  710. \item No short cycles which is possible in the OFB and CFB modes.
  711. \item Provably as secure as the block cipher being used under a chosen plaintext attack.
  712. \item Technically does not require the decryption routine of the cipher.
  713. \item Allows random access to the plaintext.
  714. \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
  715. \end{enumerate}
  716. The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
  717. accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
  718. block of memory with either of the three modes.
  719. The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
  720. other modes.
  721. \subsection{Ciphertext Stealing}
  722. \index{Ciphertext stealing}
  723. Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
  724. by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
  725. support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.
  726. The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
  727. \subsection{Initialization}
  728. \index{CBC Mode} \index{CTR Mode}
  729. \index{OFB Mode} \index{CFB Mode}
  730. The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
  731. you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
  732. use that mode. They have identical setup routines (except CTR and ECB mode):
  733. \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
  734. \begin{verbatim}
  735. int XXX_start( int cipher,
  736. const unsigned char *IV,
  737. const unsigned char *key,
  738. int keylen,
  739. int num_rounds,
  740. symmetric_XXX *XXX);
  741. int ctr_start( int cipher,
  742. const unsigned char *IV,
  743. const unsigned char *key,
  744. int keylen,
  745. int num_rounds,
  746. int ctr_mode,
  747. symmetric_CTR *ctr);
  748. int ecb_start( int cipher,
  749. const unsigned char *key,
  750. int keylen,
  751. int num_rounds,
  752. symmetric_ECB *ecb);
  753. \end{verbatim}
  754. In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use. The \textit{IV} value is
  755. the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
  756. length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
  757. of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
  758. parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call. The final parameter
  759. is a pointer to the structure you want to hold the information for the mode of operation.
  760. The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.
  761. \subsubsection{CTR Mode}
  762. In the case of CTR mode there is an additional parameter \textit{ctr\_mode} which specifies the mode that the counter is to be used in.
  763. If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
  764. \textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value. As of v1.15 the RFC 3686 style of
  765. increment then encrypt is also supported. By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
  766. the counter before encrypting it for the first time.
  767. As of V1.17, the library supports variable length counters for CTR mode. The (optional) counter length is specified by OR'ing the octet
  768. length of the counter against the \textit{ctr\_mode} parameter. The default, zero, indicates that a full block length counter will be used. This also
  769. ensures backwards compatibility with software that uses older versions of the library.
  770. \begin{small}
  771. \begin{verbatim}
  772. symmetric_CTR ctr;
  773. int err;
  774. unsigned char IV[16], key[16];
  775. /* use a 32-bit little endian counter */
  776. if ((err = ctr_start(find_cipher("aes"),
  777. IV, key, 16, 0,
  778. CTR_COUNTER_LITTLE_ENDIAN | 4,
  779. &ctr)) != CRYPT_OK) {
  780. handle_error(err);
  781. }
  782. \end{verbatim}
  783. \end{small}
  784. Changing the counter size has little (really no) effect on the performance of the CTR chaining mode. It is provided for compatibility
  785. with other software (and hardware) which have smaller fixed sized counters.
  786. \subsection{Encryption and Decryption}
  787. To actually encrypt or decrypt the following routines are provided:
  788. \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
  789. \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
  790. \begin{verbatim}
  791. int XXX_encrypt(const unsigned char *pt,
  792. unsigned char *ct,
  793. unsigned long len,
  794. symmetric_YYY *YYY);
  795. int XXX_decrypt(const unsigned char *ct,
  796. unsigned char *pt,
  797. unsigned long len,
  798. symmetric_YYY *YYY);
  799. \end{verbatim}
  800. Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.
  801. In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
  802. chunk sensitive. That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
  803. and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
  804. five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
  805. In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size. In the CBC case, you must manually pad the end of your message (either with
  806. zeroes or with whatever your protocol requires).
  807. To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
  808. \subsection{IV Manipulation}
  809. To change or read the IV of a previously initialized chaining mode use the following two functions.
  810. \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
  811. \index{ctr\_setiv()} \index{ctr\_getiv()}
  812. \begin{verbatim}
  813. int XXX_getiv(unsigned char *IV,
  814. unsigned long *len,
  815. symmetric_XXX *XXX);
  816. int XXX_setiv(const unsigned char *IV,
  817. unsigned long len,
  818. symmetric_XXX *XXX);
  819. \end{verbatim}
  820. The XXX\_getiv() functions will read the IV out of the chaining mode and store it into \textit{IV} along with the length of the IV
  821. stored in \textit{len}. The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
  822. of the IV passed in must be the size of the ciphers block size.
  823. The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
  824. What the \textit{setiv} function will do depends on the mode being changed. In CBC mode, the new IV replaces the existing IV as if it
  825. were the last ciphertext block. In CFB mode, the IV is encrypted as if it were the prior encrypted pad. In CTR mode, the IV is encrypted without
  826. first incrementing it (regardless of the LTC\_RFC\_3686 flag presence). In F8 mode, the IV is encrypted and becomes the new pad. It does not change
  827. the salted IV, and is only meant to allow seeking within a session. In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
  828. seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
  829. \subsection{Stream Termination}
  830. To terminate an open stream call the done function.
  831. \index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
  832. \begin{verbatim}
  833. int XXX_done(symmetric_XXX *XXX);
  834. \end{verbatim}
  835. This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
  836. \newpage
  837. \subsection{Examples}
  838. \begin{small}
  839. \begin{verbatim}
  840. #include <tomcrypt.h>
  841. int main(void)
  842. {
  843. unsigned char key[16], IV[16], buffer[512];
  844. symmetric_CTR ctr;
  845. int x, err;
  846. /* register twofish first */
  847. if (register_cipher(&twofish_desc) == -1) {
  848. printf("Error registering cipher.\n");
  849. return -1;
  850. }
  851. /* somehow fill out key and IV */
  852. /* start up CTR mode */
  853. if ((err = ctr_start(
  854. find_cipher("twofish"), /* index of desired cipher */
  855. IV, /* the initial vector */
  856. key, /* the secret key */
  857. 16, /* length of secret key (16 bytes) */
  858. 0, /* 0 == default # of rounds */
  859. CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
  860. &ctr) /* where to store the CTR state */
  861. ) != CRYPT_OK) {
  862. printf("ctr_start error: %s\n", error_to_string(err));
  863. return -1;
  864. }
  865. /* somehow fill buffer than encrypt it */
  866. if ((err = ctr_encrypt( buffer, /* plaintext */
  867. buffer, /* ciphertext */
  868. sizeof(buffer), /* length of plaintext pt */
  869. &ctr) /* CTR state */
  870. ) != CRYPT_OK) {
  871. printf("ctr_encrypt error: %s\n", error_to_string(err));
  872. return -1;
  873. }
  874. /* make use of ciphertext... */
  875. /* now we want to decrypt so let's use ctr_setiv */
  876. if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
  877. 16, /* the IV is 16 bytes long */
  878. &ctr) /* the ctr state we wish to modify */
  879. ) != CRYPT_OK) {
  880. printf("ctr_setiv error: %s\n", error_to_string(err));
  881. return -1;
  882. }
  883. if ((err = ctr_decrypt( buffer, /* ciphertext */
  884. buffer, /* plaintext */
  885. sizeof(buffer), /* length of plaintext */
  886. &ctr) /* CTR state */
  887. ) != CRYPT_OK) {
  888. printf("ctr_decrypt error: %s\n", error_to_string(err));
  889. return -1;
  890. }
  891. /* terminate the stream */
  892. if ((err = ctr_done(&ctr)) != CRYPT_OK) {
  893. printf("ctr_done error: %s\n", error_to_string(err));
  894. return -1;
  895. }
  896. /* clear up and return */
  897. zeromem(key, sizeof(key));
  898. zeromem(&ctr, sizeof(ctr));
  899. return 0;
  900. }
  901. \end{verbatim}
  902. \end{small}
  903. \subsection{LRW Mode}
  904. LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media. It is meant to have efficient seeking and overcome the
  905. security problems of ECB mode while not increasing the storage requirements. It is used much like any other chaining mode except with two key differences.
  906. The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long). The second key
  907. $K_2$ is the \textit{tweak} key and is always 16 octets long. The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.
  908. To initialize LRW mode use:
  909. \index{lrw\_start()}
  910. \begin{verbatim}
  911. int lrw_start( int cipher,
  912. const unsigned char *IV,
  913. const unsigned char *key,
  914. int keylen,
  915. const unsigned char *tweak,
  916. int num_rounds,
  917. symmetric_LRW *lrw);
  918. \end{verbatim}
  919. This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$ \textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$ \textit{tweak}.
  920. While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit{cipher}. The
  921. number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.
  922. To process data use the following functions:
  923. \index{lrw\_encrypt()} \index{lrw\_decrypt()}
  924. \begin{verbatim}
  925. int lrw_encrypt(const unsigned char *pt,
  926. unsigned char *ct,
  927. unsigned long len,
  928. symmetric_LRW *lrw);
  929. int lrw_decrypt(const unsigned char *ct,
  930. unsigned char *pt,
  931. unsigned long len,
  932. symmetric_LRW *lrw);
  933. \end{verbatim}
  934. These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa). The length is specified by \textit{len} in octets but must be a multiple
  935. of 16. The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.
  936. To manipulate the IV use the following functions:
  937. \index{lrw\_getiv()} \index{lrw\_setiv()}
  938. \begin{verbatim}
  939. int lrw_getiv(unsigned char *IV,
  940. unsigned long *len,
  941. symmetric_LRW *lrw);
  942. int lrw_setiv(const unsigned char *IV,
  943. unsigned long len,
  944. symmetric_LRW *lrw);
  945. \end{verbatim}
  946. These will get or set the 16--octet IV. Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation. It requires
  947. updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
  948. To terminate the LRW state use the following:
  949. \index{lrw\_done()}
  950. \begin{verbatim}
  951. int lrw_done(symmetric_LRW *lrw);
  952. \end{verbatim}
  953. \subsection{XTS Mode}
  954. As of v1.17, LibTomCrypt supports XTS mode with code donated by Elliptic Semiconductor Inc.\footnote{www.ellipticsemi.com}.
  955. XTS is a chaining mode for 128--bit block ciphers, recommended by IEEE (P1619)
  956. for disk encryption. It is meant to be an encryption mode with random access to the message data without compromising privacy. It requires two private keys (of equal
  957. length) to perform the encryption process. Each encryption invocation includes a sector number or unique identifier specified as a 128--bit string.
  958. To initialize XTS mode use the following function call:
  959. \index{xts\_start()}
  960. \begin{verbatim}
  961. int xts_start( int cipher,
  962. const unsigned char *key1,
  963. const unsigned char *key2,
  964. unsigned long keylen,
  965. int num_rounds,
  966. symmetric_xts *xts)
  967. \end{verbatim}
  968. This will start the XTS mode with the two keys pointed to by \textit{key1} and \textit{key2} of length \textit{keylen} octets each.
  969. To encrypt or decrypt a sector use the following calls:
  970. \index{xts\_encrypt()} \index{xts\_decrypt()}
  971. \begin{verbatim}
  972. int xts_encrypt(
  973. const unsigned char *pt, unsigned long ptlen,
  974. unsigned char *ct,
  975. const unsigned char *tweak,
  976. symmetric_xts *xts);
  977. int xts_decrypt(
  978. const unsigned char *ct, unsigned long ptlen,
  979. unsigned char *pt,
  980. const unsigned char *tweak,
  981. symmetric_xts *xts);
  982. \end{verbatim}
  983. The first will encrypt the plaintext pointed to by \textit{pt} of length \textit{ptlen} octets, and store the ciphertext in the array pointed to by
  984. \textit{ct}. It uses the 128--bit tweak pointed to by \textit{tweak} to encrypt the block. The decrypt function performs the opposite operation. Both
  985. functions support ciphertext stealing (blocks that are not multiples of 16 bytes).
  986. The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.
  987. To terminate the XTS state call the following function:
  988. \index{xts\_done()}
  989. \begin{verbatim}
  990. void xts_done(symmetric_xts *xts);
  991. \end{verbatim}
  992. \subsection{F8 Mode}
  993. \index{F8 Mode}
  994. The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers. It behaves much like CTR mode in that it XORs a keystream
  995. against the plaintext to encrypt. F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}. We
  996. initialize F8 mode with the following function call:
  997. \index{f8\_start()}
  998. \begin{verbatim}
  999. int f8_start( int cipher,
  1000. const unsigned char *IV,
  1001. const unsigned char *key,
  1002. int keylen,
  1003. const unsigned char *salt_key,
  1004. int skeylen,
  1005. int num_rounds,
  1006. symmetric_F8 *f8);
  1007. \end{verbatim}
  1008. This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter. It uses the \textit{salt\_key} as IV encryption key
  1009. (\textit{m} in the RFC 3711). The salt\_key can be shorter than the secret key but it should not be longer.
  1010. To encrypt or decrypt data we use the following two functions:
  1011. \index{f8\_encrypt()} \index{f8\_decrypt()}
  1012. \begin{verbatim}
  1013. int f8_encrypt(const unsigned char *pt,
  1014. unsigned char *ct,
  1015. unsigned long len,
  1016. symmetric_F8 *f8);
  1017. int f8_decrypt(const unsigned char *ct,
  1018. unsigned char *pt,
  1019. unsigned long len,
  1020. symmetric_F8 *f8);
  1021. \end{verbatim}
  1022. These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified. The length is specified in bytes and does not have to be a multiple
  1023. of the ciphers block size.
  1024. To change or retrieve the current counter IV value use the following functions:
  1025. \index{f8\_getiv()} \index{f8\_setiv()}
  1026. \begin{verbatim}
  1027. int f8_getiv(unsigned char *IV,
  1028. unsigned long *len,
  1029. symmetric_F8 *f8);
  1030. int f8_setiv(const unsigned char *IV,
  1031. unsigned long len,
  1032. symmetric_F8 *f8);
  1033. \end{verbatim}
  1034. These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start(). The purpose of these two functions is to be
  1035. able to seek within a current session only. If you want to change the session IV you will have to call f8\_done() and then start a new state with
  1036. f8\_start().
  1037. To terminate an F8 state call the following function:
  1038. \index{f8\_done()}
  1039. \begin{verbatim}
  1040. int f8_done(symmetric_F8 *f8);
  1041. \end{verbatim}
  1042. \vfil
  1043. \mysection{Encrypt and Authenticate Modes}
  1044. \subsection{EAX Mode}
  1045. LibTomCrypt provides support for a mode called EAX\footnote{See
  1046. M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
  1047. by the designers. First, a short description of what EAX mode is before we explain how to use it. EAX is a mode that requires a cipher,
  1048. CTR and OMAC support and provides encryption and
  1049. authentication\footnote{Note that since EAX only requires OMAC and CTR you may use \textit{encrypt only} cipher descriptors with this mode.}.
  1050. It is initialized with a random \textit{nonce} that can be shared publicly, a \textit{header} which can be fixed and public, and a random secret symmetric key.
  1051. The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages). It can
  1052. be added at anytime during an EAX stream, and is part of the authentication tag. That is, changes in the meta-data can be detected by changes in the output tag.
  1053. The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
  1054. called a \textit{tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
  1055. sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
  1056. of operation.
  1057. The mode is initialized with the following function.
  1058. \index{eax\_init()}
  1059. \begin{verbatim}
  1060. int eax_init( eax_state *eax,
  1061. int cipher,
  1062. const unsigned char *key,
  1063. unsigned long keylen,
  1064. const unsigned char *nonce,
  1065. unsigned long noncelen,
  1066. const unsigned char *header,
  1067. unsigned long headerlen);
  1068. \end{verbatim}
  1069. Where \textit{eax} is the EAX state. The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.
  1070. The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets. The \textit{nonce} parameter is the
  1071. random public string of length \textit{noncelen} octets. The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the
  1072. message of length \textit{headerlen} octets.
  1073. When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or
  1074. encrypted in EAX mode. Note: if \textit{headerlen} is zero you may pass \textit{header} as \textbf{NULL} to indicate there is no initial header data.
  1075. To encrypt or decrypt data in a streaming mode use the following.
  1076. \index{eax\_encrypt()} \index{eax\_decrypt()}
  1077. \begin{verbatim}
  1078. int eax_encrypt( eax_state *eax,
  1079. const unsigned char *pt,
  1080. unsigned char *ct,
  1081. unsigned long length);
  1082. int eax_decrypt( eax_state *eax,
  1083. const unsigned char *ct,
  1084. unsigned char *pt,
  1085. unsigned long length);
  1086. \end{verbatim}
  1087. The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
  1088. \textit{ct}. Note: \textit{ct} and \textit{pt} may be the same region in memory. This function will also send the ciphertext
  1089. through the OMAC function. The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}. This also allows
  1090. \textit{pt} and \textit{ct} to be the same region in memory.
  1091. You cannot both encrypt or decrypt with the same \textit{eax} context. For bi--directional communication you will need to initialize
  1092. two EAX contexts (preferably with different headers and nonces).
  1093. Note: both of these functions allow you to send the data in any granularity but the order is important. While
  1094. the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
  1095. EAX stream with the following.
  1096. \index{eax\_addheader()}
  1097. \begin{verbatim}
  1098. int eax_addheader( eax_state *eax,
  1099. const unsigned char *header,
  1100. unsigned long length);
  1101. \end{verbatim}
  1102. This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header. Once the message is finished, the
  1103. \textit{tag} (checksum) may be computed with the following function:
  1104. \index{eax\_done()}
  1105. \begin{verbatim}
  1106. int eax_done( eax_state *eax,
  1107. unsigned char *tag,
  1108. unsigned long *taglen);
  1109. \end{verbatim}
  1110. This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}. The function
  1111. then stores how many bytes of the tag were written out back in to \textit{taglen}.
  1112. The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
  1113. \index{eax\_test()}
  1114. \begin{verbatim}
  1115. int eax_test(void);
  1116. \end{verbatim}
  1117. This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
  1118. \begin{verbatim}
  1119. #include <tomcrypt.h>
  1120. int main(void)
  1121. {
  1122. int err;
  1123. eax_state eax;
  1124. unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
  1125. unsigned long taglen;
  1126. if (register_cipher(&rijndael_desc) == -1) {
  1127. printf("Error registering Rijndael");
  1128. return EXIT_FAILURE;
  1129. }
  1130. /* ... make up random nonce and key ... */
  1131. /* initialize context */
  1132. if ((err = eax_init( &eax, /* context */
  1133. find_cipher("rijndael"), /* cipher id */
  1134. nonce, /* the nonce */
  1135. 16, /* nonce is 16 bytes */
  1136. "TestApp", /* example header */
  1137. 7) /* header length */
  1138. ) != CRYPT_OK) {
  1139. printf("Error eax_init: %s", error_to_string(err));
  1140. return EXIT_FAILURE;
  1141. }
  1142. /* now encrypt data, say in a loop or whatever */
  1143. if ((err = eax_encrypt( &eax, /* eax context */
  1144. pt, /* plaintext (source) */
  1145. ct, /* ciphertext (destination) */
  1146. sizeof(pt) /* size of plaintext */
  1147. ) != CRYPT_OK) {
  1148. printf("Error eax_encrypt: %s", error_to_string(err));
  1149. return EXIT_FAILURE;
  1150. }
  1151. /* finish message and get authentication tag */
  1152. taglen = sizeof(tag);
  1153. if ((err = eax_done( &eax, /* eax context */
  1154. tag, /* where to put tag */
  1155. &taglen /* length of tag space */
  1156. ) != CRYPT_OK) {
  1157. printf("Error eax_done: %s", error_to_string(err));
  1158. return EXIT_FAILURE;
  1159. }
  1160. /* now we have the authentication tag in "tag" and
  1161. * it's taglen bytes long */
  1162. }
  1163. \end{verbatim}
  1164. You can also perform an entire EAX state on a block of memory in a single function call with the
  1165. following functions.
  1166. \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
  1167. \begin{verbatim}
  1168. int eax_encrypt_authenticate_memory(
  1169. int cipher,
  1170. const unsigned char *key, unsigned long keylen,
  1171. const unsigned char *nonce, unsigned long noncelen,
  1172. const unsigned char *header, unsigned long headerlen,
  1173. const unsigned char *pt, unsigned long ptlen,
  1174. unsigned char *ct,
  1175. unsigned char *tag, unsigned long *taglen);
  1176. int eax_decrypt_verify_memory(
  1177. int cipher,
  1178. const unsigned char *key, unsigned long keylen,
  1179. const unsigned char *nonce, unsigned long noncelen,
  1180. const unsigned char *header, unsigned long headerlen,
  1181. const unsigned char *ct, unsigned long ctlen,
  1182. unsigned char *pt,
  1183. unsigned char *tag, unsigned long taglen,
  1184. int *res);
  1185. \end{verbatim}
  1186. Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
  1187. have the same meaning as with those respective functions.
  1188. 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
  1189. the tag it computed while decrypting the message. If the tags match then it stores a $1$ in \textit{res}, otherwise it stores a $0$.
  1190. \subsection{OCB Mode}
  1191. LibTomCrypt provides support for a mode called OCB\footnote{See
  1192. P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit{OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption}.}
  1193. . OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
  1194. but is less flexible. Let's review how to initialize an OCB context.
  1195. \index{ocb\_init()}
  1196. \begin{verbatim}
  1197. int ocb_init( ocb_state *ocb,
  1198. int cipher,
  1199. const unsigned char *key,
  1200. unsigned long keylen,
  1201. const unsigned char *nonce);
  1202. \end{verbatim}
  1203. This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
  1204. and the random \textit{nonce}. Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
  1205. block size (e.g. 16 bytes for AES).
  1206. This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
  1207. To encrypt or decrypt data use the following.
  1208. \index{ocb\_encrypt()} \index{ocb\_decrypt()}
  1209. \begin{verbatim}
  1210. int ocb_encrypt( ocb_state *ocb,
  1211. const unsigned char *pt,
  1212. unsigned char *ct);
  1213. int ocb_decrypt( ocb_state *ocb,
  1214. const unsigned char *ct,
  1215. unsigned char *pt);
  1216. \end{verbatim}
  1217. This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
  1218. They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
  1219. both functions given a single \textit{ocb} state. For bi-directional communication you will have to initialize two \textit{ocb}
  1220. states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
  1221. \subsubsection{State Termination}
  1222. When you are finished encrypting the message you call the following function to compute the tag.
  1223. \index{ocb\_done\_encrypt()}
  1224. \begin{verbatim}
  1225. int ocb_done_encrypt( ocb_state *ocb,
  1226. const unsigned char *pt,
  1227. unsigned long ptlen,
  1228. unsigned char *ct,
  1229. unsigned char *tag,
  1230. unsigned long *taglen);
  1231. \end{verbatim}
  1232. This will terminate an encrypt stream \textit{ocb}. If you have trailing bytes of plaintext that will not complete a block
  1233. you can pass them here. This will also encrypt the \textit{ptlen} bytes in \textit{pt} and store them in \textit{ct}. It will also
  1234. store up to \textit{taglen} bytes of the tag into \textit{tag}.
  1235. Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen. Also note that if you have
  1236. an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
  1237. To terminate a decrypt stream and compared the tag you call the following.
  1238. \index{ocb\_done\_decrypt()}
  1239. \begin{verbatim}
  1240. int ocb_done_decrypt( ocb_state *ocb,
  1241. const unsigned char *ct,
  1242. unsigned long ctlen,
  1243. unsigned char *pt,
  1244. const unsigned char *tag,
  1245. unsigned long taglen,
  1246. int *res);
  1247. \end{verbatim}
  1248. Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
  1249. tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided. By default
  1250. \textit{res} is set to zero. If all \textit{taglen} bytes of \textit{tag} can be verified then \textit{res} is set to one (authenticated
  1251. message).
  1252. \subsubsection{Packet Functions}
  1253. To make life simpler the following two functions are provided for memory bound OCB.
  1254. %\index{ocb\_encrypt\_authenticate\_memory()}
  1255. \begin{verbatim}
  1256. int ocb_encrypt_authenticate_memory(
  1257. int cipher,
  1258. const unsigned char *key, unsigned long keylen,
  1259. const unsigned char *nonce,
  1260. const unsigned char *pt, unsigned long ptlen,
  1261. unsigned char *ct,
  1262. unsigned char *tag, unsigned long *taglen);
  1263. \end{verbatim}
  1264. This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
  1265. can be any arbitrary length.
  1266. \index{ocb\_decrypt\_verify\_memory()}
  1267. \begin{verbatim}
  1268. int ocb_decrypt_verify_memory(
  1269. int cipher,
  1270. const unsigned char *key, unsigned long keylen,
  1271. const unsigned char *nonce,
  1272. const unsigned char *ct, unsigned long ctlen,
  1273. unsigned char *pt,
  1274. const unsigned char *tag, unsigned long taglen,
  1275. int *res);
  1276. \end{verbatim}
  1277. Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
  1278. appropriately.
  1279. \subsection{CCM Mode}
  1280. CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.
  1281. \subsubsection{Initialization}
  1282. To initialize the CCM context with a secret key call the following function.
  1283. \index{ccm\_init()}
  1284. \begin{verbatim}
  1285. int ccm_init( ccm_state *ccm,
  1286. int cipher,
  1287. const unsigned char *key,
  1288. int keylen,
  1289. int ptlen,
  1290. int taglen,
  1291. int aadlen);
  1292. \end{verbatim}
  1293. This initializes the CCM state \textit{ccm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
  1294. chosen must have a 16--byte block size (e.g., AES).
  1295. Unlike EAX and OCB mode, CCM is only meant for \textit{packet} mode where the length of the input is known in advance. This is why the length of the stream
  1296. to authenticate is given as \textit{ptlen}.
  1297. With CCM, a header is meta--data you want to send with the message but not have encrypted. The header len is given in the init
  1298. as \textit{aadlen}.
  1299. \subsubsection{Nonce Vector}
  1300. 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.
  1301. \index{ccm\_add\_nonce()}
  1302. \begin{verbatim}
  1303. int ccm_add_nonce( ccm_state *ccm,
  1304. const unsigned char *nonce,
  1305. unsigned long noncelen);
  1306. \end{verbatim}
  1307. This adds the nonce (a.k.a. salt) \textit{nonce} of length \textit{noncelen} octets to the CCM state \textit{ccm}. Note that this function must be called
  1308. once and only once.
  1309. \subsubsection{Additional Authentication Data}
  1310. The header is meta--data you want to send with the message but not have encrypted, it must be stored in \textit{adata} of length \textit{adatalen} octets.
  1311. \index{ccm\_add\_aad()}
  1312. \begin{verbatim}
  1313. int ccm_add_aad( ccm_state *ccm,
  1314. const unsigned char *adata,
  1315. unsigned long adatalen);
  1316. \end{verbatim}
  1317. This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the CCM state \textit{ccm}.
  1318. \subsubsection{Plaintext Processing}
  1319. After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
  1320. \index{ccm\_process()}
  1321. \begin{verbatim}
  1322. int ccm_process(ccm_state *ccm,
  1323. unsigned char *pt,
  1324. unsigned long ptlen,
  1325. unsigned char *ct,
  1326. int direction);
  1327. \end{verbatim}
  1328. This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
  1329. the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{CCM\_ENCRYPT} the plaintext is read,
  1330. encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{CCM\_DECRYPT} the opposite occurs.
  1331. \subsubsection{State Termination}
  1332. To terminate a CCM state and retrieve the message authentication tag call the following function.
  1333. \index{ccm\_done()}
  1334. \begin{verbatim}
  1335. int ccm_done( ccm_state *ccm,
  1336. unsigned char *tag,
  1337. unsigned long *taglen);
  1338. \end{verbatim}
  1339. This terminates the CCM state \textit{ccm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
  1340. \subsubsection{State Reset}
  1341. The call to ccm\_init() will perform considerable pre--computation and if you're going to be dealing with a lot of packets
  1342. it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function is provided.
  1343. \index{ccm\_reset()}
  1344. \begin{verbatim}
  1345. int ccm_reset(ccm_state *ccm);
  1346. \end{verbatim}
  1347. This will reset the CCM state \textit{ccm} to the state that ccm\_init() left it. The user would then call ccm\_add\_nonce(), ccm\_add\_aad(), etc.
  1348. \subsubsection{One--Shot Packet}
  1349. To process a single packet under any given key the following helper function can be used.
  1350. \index{ccm\_memory()}
  1351. \begin{verbatim}
  1352. int ccm_memory(
  1353. int cipher,
  1354. const unsigned char *key, unsigned long keylen,
  1355. symmetric_key *uskey,
  1356. const unsigned char *nonce, unsigned long noncelen,
  1357. const unsigned char *header, unsigned long headerlen,
  1358. unsigned char *pt, unsigned long ptlen,
  1359. unsigned char *ct,
  1360. unsigned char *tag, unsigned long *taglen,
  1361. int direction);
  1362. \end{verbatim}
  1363. This will initialize the CCM state with the given key, nonce and AAD value then proceed to encrypt or decrypt the message text and store the final
  1364. message tag. The definition of the variables is the same as it is for all the manual functions.
  1365. 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.
  1366. \subsubsection{Example Usage}
  1367. The following is an example usage of how to use CCM over multiple packets with a shared secret key.
  1368. \begin{small}
  1369. \begin{verbatim}
  1370. #include <tomcrypt.h>
  1371. int send_packet(const unsigned char *pt, unsigned long ptlen,
  1372. const unsigned char *nonce, unsigned long noncelen,
  1373. const unsigned char *aad, unsigned long aadlen,
  1374. ccm_state *ccm)
  1375. {
  1376. int err;
  1377. unsigned long taglen;
  1378. unsigned char tag[16];
  1379. /* reset the state */
  1380. if ((err = ccm_reset(ccm)) != CRYPT_OK) {
  1381. return err;
  1382. }
  1383. /* Add the nonce */
  1384. if ((err = ccm_add_nonce(ccm, nonce, noncelen)) != CRYPT_OK) {
  1385. return err;
  1386. }
  1387. /* Add the AAD (note: aad can be NULL if aadlen == 0) */
  1388. if ((err = ccm_add_aad(ccm, aad, aadlen)) != CRYPT_OK) {
  1389. return err;
  1390. }
  1391. /* process the plaintext */
  1392. if ((err =
  1393. ccm_process(ccm, pt, ptlen, pt, CCM_ENCRYPT)) != CRYPT_OK) {
  1394. return err;
  1395. }
  1396. /* Finish up and get the MAC tag */
  1397. taglen = sizeof(tag);
  1398. if ((err = ccm_done(ccm, tag, &taglen)) != CRYPT_OK) {
  1399. return err;
  1400. }
  1401. /* ... send a header describing the lengths ... */
  1402. /* depending on the protocol and how nonce is
  1403. * generated you may have to send it too... */
  1404. send(socket, nonce, noncelen, 0);
  1405. /* send the aad */
  1406. send(socket, aad, aadlen, 0);
  1407. /* send the ciphertext */
  1408. send(socket, pt, ptlen, 0);
  1409. /* send the tag */
  1410. send(socket, tag, taglen, 0);
  1411. return CRYPT_OK;
  1412. }
  1413. int main(void)
  1414. {
  1415. ccm_state ccm;
  1416. unsigned char key[16], NONCE[12], pt[PACKET_SIZE];
  1417. int err, x;
  1418. unsigned long ptlen;
  1419. /* somehow fill key/NONCE with random values */
  1420. /* register AES */
  1421. register_cipher(&aes_desc);
  1422. /* init the CCM state */
  1423. if ((err =
  1424. ccm_init(&ccm, find_cipher("aes"), key, 16, PACKET_SIZE, 16, size(NONCE))) != CRYPT_OK) {
  1425. whine_and_pout(err);
  1426. }
  1427. /* handle us some packets */
  1428. for (;;) {
  1429. ptlen = make_packet_we_want_to_send(pt);
  1430. /* use NONCE as counter (12 byte counter) */
  1431. for (x = 11; x >= 0; x--) {
  1432. if (++NONCE[x]) {
  1433. break;
  1434. }
  1435. }
  1436. if ((err = send_packet(pt, ptlen, NONCE, 12, NULL, 0, &ccm))
  1437. != CRYPT_OK) {
  1438. whine_and_pout(err);
  1439. }
  1440. }
  1441. return EXIT_SUCCESS;
  1442. }
  1443. \end{verbatim}
  1444. \end{small}
  1445. \subsection{GCM Mode}
  1446. Galois counter mode is an IEEE proposal for authenticated encryption (also it is a planned NIST standard). Like EAX and OCB mode, it can be used in a streaming capacity
  1447. however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed. This mode also only works with
  1448. block ciphers with a 16--byte block.
  1449. A GCM stream is meant to be processed in three modes, one after another. First, the initial vector (per session) data is processed. This should be
  1450. unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
  1451. \subsubsection{Initialization}
  1452. To initialize the GCM context with a secret key call the following function.
  1453. \index{gcm\_init()}
  1454. \begin{verbatim}
  1455. int gcm_init( gcm_state *gcm,
  1456. int cipher,
  1457. const unsigned char *key,
  1458. int keylen);
  1459. \end{verbatim}
  1460. This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
  1461. chosen must have a 16--byte block size (e.g., AES).
  1462. \subsubsection{Initial Vector}
  1463. 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.
  1464. \index{gcm\_add\_iv()}
  1465. \begin{verbatim}
  1466. int gcm_add_iv( gcm_state *gcm,
  1467. const unsigned char *IV,
  1468. unsigned long IVlen);
  1469. \end{verbatim}
  1470. This adds the initial vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}. You can call this function as many times as required
  1471. to process the entire IV.
  1472. Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done. If you want to minimize per packet latency it is ideal
  1473. to only use 12--byte IVs. You can just increment it like a counter for each packet.
  1474. \subsubsection{Additional Authentication Data}
  1475. After the entire IV has been processed, the additional authentication data can be processed. Unlike the IV, a packet/session does not require additional
  1476. authentication data (AAD) for security. The AAD is meant to be used as side--channel data you want to be authenticated with the packet. Note: once
  1477. you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
  1478. \index{gcm\_add\_aad()}
  1479. \begin{verbatim}
  1480. int gcm_add_aad( gcm_state *gcm,
  1481. const unsigned char *adata,
  1482. unsigned long adatalen);
  1483. \end{verbatim}
  1484. This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
  1485. \subsubsection{Plaintext Processing}
  1486. After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
  1487. \index{gcm\_process()}
  1488. \begin{verbatim}
  1489. int gcm_process( gcm_state *gcm,
  1490. unsigned char *pt,
  1491. unsigned long ptlen,
  1492. unsigned char *ct,
  1493. int direction);
  1494. \end{verbatim}
  1495. This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
  1496. the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read,
  1497. encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
  1498. \subsubsection{State Termination}
  1499. To terminate a GCM state and retrieve the message authentication tag call the following function.
  1500. \index{gcm\_done()}
  1501. \begin{verbatim}
  1502. int gcm_done( gcm_state *gcm,
  1503. unsigned char *tag,
  1504. unsigned long *taglen);
  1505. \end{verbatim}
  1506. This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
  1507. \subsubsection{State Reset}
  1508. 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
  1509. it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
  1510. \index{gcm\_reset()}
  1511. \begin{verbatim}
  1512. int gcm_reset(gcm_state *gcm);
  1513. \end{verbatim}
  1514. This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it. The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
  1515. \subsubsection{One--Shot Packet}
  1516. To process a single packet under any given key the following helper function can be used.
  1517. \index{gcm\_memory()}
  1518. \begin{verbatim}
  1519. int gcm_memory(
  1520. int cipher,
  1521. const unsigned char *key,
  1522. unsigned long keylen,
  1523. const unsigned char *IV, unsigned long IVlen,
  1524. const unsigned char *adata, unsigned long adatalen,
  1525. unsigned char *pt, unsigned long ptlen,
  1526. unsigned char *ct,
  1527. unsigned char *tag, unsigned long *taglen,
  1528. int direction);
  1529. \end{verbatim}
  1530. 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
  1531. message tag. The definition of the variables is the same as it is for all the manual functions.
  1532. 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.
  1533. \subsubsection{Example Usage}
  1534. The following is an example usage of how to use GCM over multiple packets with a shared secret key.
  1535. \begin{small}
  1536. \begin{verbatim}
  1537. #include <tomcrypt.h>
  1538. int send_packet(const unsigned char *pt, unsigned long ptlen,
  1539. const unsigned char *iv, unsigned long ivlen,
  1540. const unsigned char *aad, unsigned long aadlen,
  1541. gcm_state *gcm)
  1542. {
  1543. int err;
  1544. unsigned long taglen;
  1545. unsigned char tag[16];
  1546. /* reset the state */
  1547. if ((err = gcm_reset(gcm)) != CRYPT_OK) {
  1548. return err;
  1549. }
  1550. /* Add the IV */
  1551. if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
  1552. return err;
  1553. }
  1554. /* Add the AAD (note: aad can be NULL if aadlen == 0) */
  1555. if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
  1556. return err;
  1557. }
  1558. /* process the plaintext */
  1559. if ((err =
  1560. gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
  1561. return err;
  1562. }
  1563. /* Finish up and get the MAC tag */
  1564. taglen = sizeof(tag);
  1565. if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
  1566. return err;
  1567. }
  1568. /* ... send a header describing the lengths ... */
  1569. /* depending on the protocol and how IV is
  1570. * generated you may have to send it too... */
  1571. send(socket, iv, ivlen, 0);
  1572. /* send the aad */
  1573. send(socket, aad, aadlen, 0);
  1574. /* send the ciphertext */
  1575. send(socket, pt, ptlen, 0);
  1576. /* send the tag */
  1577. send(socket, tag, taglen, 0);
  1578. return CRYPT_OK;
  1579. }
  1580. int main(void)
  1581. {
  1582. gcm_state gcm;
  1583. unsigned char key[16], IV[12], pt[PACKET_SIZE];
  1584. int err, x;
  1585. unsigned long ptlen;
  1586. /* somehow fill key/IV with random values */
  1587. /* register AES */
  1588. register_cipher(&aes_desc);
  1589. /* init the GCM state */
  1590. if ((err =
  1591. gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
  1592. whine_and_pout(err);
  1593. }
  1594. /* handle us some packets */
  1595. for (;;) {
  1596. ptlen = make_packet_we_want_to_send(pt);
  1597. /* use IV as counter (12 byte counter) */
  1598. for (x = 11; x >= 0; x--) {
  1599. if (++IV[x]) {
  1600. break;
  1601. }
  1602. }
  1603. if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm))
  1604. != CRYPT_OK) {
  1605. whine_and_pout(err);
  1606. }
  1607. }
  1608. return EXIT_SUCCESS;
  1609. }
  1610. \end{verbatim}
  1611. \end{small}
  1612. \chapter{One-Way Cryptographic Hash Functions}
  1613. \mysection{Core Functions}
  1614. Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}. To initialize hash
  1615. XXX (where XXX is the name) call:
  1616. \index{Hash Functions}
  1617. \begin{verbatim}
  1618. void XXX_init(hash_state *md);
  1619. \end{verbatim}
  1620. This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the message being hashed call:
  1621. \begin{verbatim}
  1622. int XXX_process( hash_state *md,
  1623. const unsigned char *in,
  1624. unsigned long inlen);
  1625. \end{verbatim}
  1626. 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
  1627. 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 (hash output) will be the same. For example,
  1628. this means that:
  1629. \begin{verbatim}
  1630. md5_process(&md, "hello ", 6);
  1631. md5_process(&md, "world", 5);
  1632. \end{verbatim}
  1633. Will produce the same message digest as the single call:
  1634. \index{Message Digest}
  1635. \begin{verbatim}
  1636. md5_process(&md, "hello world", 11);
  1637. \end{verbatim}
  1638. To finally get the message digest (the hash) call:
  1639. \begin{verbatim}
  1640. int XXX_done( hash_state *md,
  1641. unsigned char *out);
  1642. \end{verbatim}
  1643. This function will finish up the hash and store the result in the \textit{out} array. You must ensure that \textit{out} is long
  1644. enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
  1645. will wipe the \textit{md} variable before returning automatically.
  1646. To test a hash function call:
  1647. \begin{verbatim}
  1648. int XXX_test(void);
  1649. \end{verbatim}
  1650. This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
  1651. example snippet that hashes a message with md5 is given below.
  1652. \begin{small}
  1653. \begin{verbatim}
  1654. #include <tomcrypt.h>
  1655. int main(void)
  1656. {
  1657. hash_state md;
  1658. unsigned char *in = "hello world", out[16];
  1659. /* setup the hash */
  1660. md5_init(&md);
  1661. /* add the message */
  1662. md5_process(&md, in, strlen(in));
  1663. /* get the hash in out[0..15] */
  1664. md5_done(&md, out);
  1665. return 0;
  1666. }
  1667. \end{verbatim}
  1668. \end{small}
  1669. \mysection{Hash Descriptors}
  1670. Like the set of ciphers, the set of hashes have descriptors as well. They are stored in an array called \textit{hash\_descriptor} and
  1671. are defined by:
  1672. \begin{verbatim}
  1673. struct _hash_descriptor {
  1674. char *name;
  1675. unsigned long hashsize; /* digest output size in bytes */
  1676. unsigned long blocksize; /* the block size the hash uses */
  1677. void (*init) (hash_state *hash);
  1678. int (*process)( hash_state *hash,
  1679. const unsigned char *in,
  1680. unsigned long inlen);
  1681. int (*done) (hash_state *hash, unsigned char *out);
  1682. int (*test) (void);
  1683. };
  1684. \end{verbatim}
  1685. \index{find\_hash()}
  1686. The \textit{name} member is the name of the hash function (all lowercase). The \textit{hashsize} member is the size of the digest output
  1687. in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function. Technically, this detail is not important
  1688. for high level developers but is useful to know for performance reasons.
  1689. The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the
  1690. digest. The \textit{test} member tests the hash against the specified test vectors.
  1691. There is a function to search the array as well called \textit{int find\_hash(char *name)}. It returns -1 if the hash is not found, otherwise, the
  1692. position in the descriptor table of the hash.
  1693. In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
  1694. \index{find\_hash\_oid()}
  1695. \begin{verbatim}
  1696. int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
  1697. \end{verbatim}
  1698. You can use the table to indirectly call a hash function that is chosen at run-time. For example:
  1699. \begin{small}
  1700. \begin{verbatim}
  1701. #include <tomcrypt.h>
  1702. int main(void)
  1703. {
  1704. unsigned char buffer[100], hash[MAXBLOCKSIZE];
  1705. int idx, x;
  1706. hash_state md;
  1707. /* register hashes .... */
  1708. if (register_hash(&md5_desc) == -1) {
  1709. printf("Error registering MD5.\n");
  1710. return -1;
  1711. }
  1712. /* register other hashes ... */
  1713. /* prompt for name and strip newline */
  1714. printf("Enter hash name: \n");
  1715. fgets(buffer, sizeof(buffer), stdin);
  1716. buffer[strlen(buffer) - 1] = 0;
  1717. /* get hash index */
  1718. idx = find_hash(buffer);
  1719. if (idx == -1) {
  1720. printf("Invalid hash name!\n");
  1721. return -1;
  1722. }
  1723. /* hash input until blank line */
  1724. hash_descriptor[idx].init(&md);
  1725. while (fgets(buffer, sizeof(buffer), stdin) != NULL)
  1726. hash_descriptor[idx].process(&md, buffer, strlen(buffer));
  1727. hash_descriptor[idx].done(&md, hash);
  1728. /* dump to screen */
  1729. for (x = 0; x < hash_descriptor[idx].hashsize; x++)
  1730. printf("%02x ", hash[x]);
  1731. printf("\n");
  1732. return 0;
  1733. }
  1734. \end{verbatim}
  1735. \end{small}
  1736. Note the usage of \textbf{MAXBLOCKSIZE}. In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
  1737. length. This provides a simple size you can set your automatic arrays to that will not get overrun.
  1738. There are three helper functions to make working with hashes easier. The first is a function to hash a buffer, and produce the digest in a single
  1739. function call.
  1740. \index{hash\_memory()}
  1741. \begin{verbatim}
  1742. int hash_memory( int hash,
  1743. const unsigned char *in,
  1744. unsigned long inlen,
  1745. unsigned char *out,
  1746. unsigned long *outlen);
  1747. \end{verbatim}
  1748. This will hash the data pointed to by \textit{in} of length \textit{inlen}. The hash used is indexed by the \textit{hash} parameter. The message
  1749. digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  1750. The next helper function allows for the hashing of a file based on a file name.
  1751. \index{hash\_file()}
  1752. \begin{verbatim}
  1753. int hash_file( int hash,
  1754. const char *fname,
  1755. unsigned char *out,
  1756. unsigned long *outlen);
  1757. \end{verbatim}
  1758. This will hash the file named by \textit{fname} using the hash indexed by \textit{hash}. The file named in this function call must be readable by the
  1759. user owning the process performing the request. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
  1760. when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  1761. \index{hash\_filehandle()}
  1762. \begin{verbatim}
  1763. int hash_filehandle( int hash,
  1764. FILE *in,
  1765. unsigned char *out,
  1766. unsigned long *outlen);
  1767. \end{verbatim}
  1768. This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}. This will begin hashing from the current file pointer position, and
  1769. will not rewind the file pointer when finished. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
  1770. when it is called. The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
  1771. To perform the above hash with md5 the following code could be used:
  1772. \begin{small}
  1773. \begin{verbatim}
  1774. #include <tomcrypt.h>
  1775. int main(void)
  1776. {
  1777. int idx, err;
  1778. unsigned long len;
  1779. unsigned char out[MAXBLOCKSIZE];
  1780. /* register the hash */
  1781. if (register_hash(&md5_desc) == -1) {
  1782. printf("Error registering MD5.\n");
  1783. return -1;
  1784. }
  1785. /* get the index of the hash */
  1786. idx = find_hash("md5");
  1787. /* call the hash */
  1788. len = sizeof(out);
  1789. if ((err =
  1790. hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
  1791. printf("Error hashing data: %s\n", error_to_string(err));
  1792. return -1;
  1793. }
  1794. return 0;
  1795. }
  1796. \end{verbatim}
  1797. \end{small}
  1798. \subsection{Hash Registration}
  1799. Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
  1800. work exactly like those of the cipher registration code. The functions are:
  1801. \index{register\_hash()} \index{unregister\_hash()}
  1802. \begin{verbatim}
  1803. int register_hash(const struct _hash_descriptor *hash);
  1804. int unregister_hash(const struct _hash_descriptor *hash);
  1805. \end{verbatim}
  1806. The following hashes are provided as of this release within the LibTomCrypt library:
  1807. \index{Hash descriptor table}
  1808. \begin{figure}[h]
  1809. \begin{center}
  1810. \begin{tabular}{|c|c|c|}
  1811. \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Size of Message Digest (bytes)} \\
  1812. \hline WHIRLPOOL & whirlpool\_desc & 64 \\
  1813. \hline SHA3-512 & sha3\_512\_desc & 64 \\
  1814. \hline SHA-512 & sha512\_desc & 64 \\
  1815. \hline BLAKE2B-512 & blake2b\_512\_desc & 64 \\
  1816. \hline SHA3-384 & sha3\_384\_desc & 48 \\
  1817. \hline SHA-384 & sha384\_desc & 48 \\
  1818. \hline RIPEMD-320 & rmd160\_desc & 40 \\
  1819. \hline SHA-512/256 & sha512\_256\_desc & 32 \\
  1820. \hline SHA3-256 & sha3\_256\_desc & 32 \\
  1821. \hline SHA-256 & sha256\_desc & 32 \\
  1822. \hline RIPEMD-256 & rmd160\_desc & 32 \\
  1823. \hline BLAKE2S-256 & blake2s\_256\_desc & 32 \\
  1824. \hline BLAKE2B-256 & blake2b\_256\_desc & 32 \\
  1825. \hline SHA-512/224 & sha512\_224\_desc & 28 \\
  1826. \hline SHA3-224 & sha3\_224\_desc & 28 \\
  1827. \hline SHA-224 & sha224\_desc & 28 \\
  1828. \hline BLAKE2S-224 & blake2s\_224\_desc & 28 \\
  1829. \hline BLAKE2B-384 & blake2b\_384\_desc & 48 \\
  1830. \hline TIGER-192 & tiger\_desc & 24 \\
  1831. \hline SHA-1 & sha1\_desc & 20 \\
  1832. \hline RIPEMD-160 & rmd160\_desc & 20 \\
  1833. \hline BLAKE2S-160 & blake2s\_160\_desc & 20 \\
  1834. \hline BLAKE2B-160 & blake2b\_160\_desc & 20 \\
  1835. \hline RIPEMD-128 & rmd128\_desc & 16 \\
  1836. \hline MD5 & md5\_desc & 16 \\
  1837. \hline MD4 & md4\_desc & 16 \\
  1838. \hline MD2 & md2\_desc & 16 \\
  1839. \hline BLAKE2S-128 & blake2s\_128\_desc & 16 \\
  1840. \hline
  1841. \end{tabular}
  1842. \end{center}
  1843. \caption{Built--In Software Hashes}
  1844. \end{figure}
  1845. \vfil
  1846. \mysection{Cipher Hash Construction}
  1847. \index{Cipher Hash Construction}
  1848. An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode. In this mode
  1849. applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
  1850. particular this allows a cryptosystem to be designed using very few moving parts.
  1851. In order to use the CHC system the developer will have to take a few extra steps. First the \textit{chc\_desc} hash
  1852. descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
  1853. data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
  1854. via the chc\_register() function.
  1855. \index{chc\_register()}
  1856. \begin{verbatim}
  1857. int chc_register(int cipher);
  1858. \end{verbatim}
  1859. A cipher has to be registered with CHC (and also in the cipher descriptor tables with
  1860. register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
  1861. be bound to the CHC hash at a time. There are additional requirements for the system to work.
  1862. \begin{enumerate}
  1863. \item The cipher must have a block size greater than 64--bits.
  1864. \item The cipher must allow an input key the size of the block size.
  1865. \end{enumerate}
  1866. Example of using CHC with the AES block cipher.
  1867. \begin{verbatim}
  1868. #include <tomcrypt.h>
  1869. int main(void)
  1870. {
  1871. int err;
  1872. /* register cipher and hash */
  1873. if (register_cipher(&aes_enc_desc) == -1) {
  1874. printf("Could not register cipher\n");
  1875. return EXIT_FAILURE;
  1876. }
  1877. if (register_hash(&chc_desc) == -1) {
  1878. printf("Could not register hash\n");
  1879. return EXIT_FAILURE;
  1880. }
  1881. /* start chc with AES */
  1882. if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
  1883. printf("Error binding AES to CHC: %s\n",
  1884. error_to_string(err));
  1885. }
  1886. /* now you can use chc_hash in any LTC function
  1887. * [aside from pkcs...] */
  1888. }
  1889. \end{verbatim}
  1890. \mysection{Notice}
  1891. It is highly recommended that you \textbf{not} use the MD2, MD4, MD5, or SHA-1 hashes for the purposes of digital signatures or authentication codes.
  1892. These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
  1893. (e.g. Yarrow).
  1894. The other hashes such as the SHA-2 (that includes SHA-512, SHA-512/384, SHA-384, SHA-512/256, SHA-256 and SHA-224) and TIGER-192 are still considered secure
  1895. for all purposes you would normally use a hash for.
  1896. \chapter{Message Authentication Codes}
  1897. \mysection{HMAC Protocol}
  1898. Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short. An HMAC
  1899. of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify. The purpose is
  1900. 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
  1901. eavesdropper will not be able to verify the authenticity of a message.
  1902. The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
  1903. 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
  1904. unsigned characters. The initialization routine is:
  1905. \index{hmac\_init()}
  1906. \begin{verbatim}
  1907. int hmac_init( hmac_state *hmac,
  1908. int hash,
  1909. const unsigned char *key,
  1910. unsigned long keylen);
  1911. \end{verbatim}
  1912. The \textit{hmac} parameter is the state for the HMAC code. The \textit{hash} parameter is the index into the descriptor table of the hash you want
  1913. to use to authenticate the message. The \textit{key} parameter is the pointer to the array of chars that make up the key. The \textit{keylen} parameter is the
  1914. 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:
  1915. \index{hmac\_process()}
  1916. \begin{verbatim}
  1917. int hmac_process( hmac_state *hmac,
  1918. const unsigned char *in,
  1919. unsigned long inlen);
  1920. \end{verbatim}
  1921. \textit{hmac} is the HMAC state you are working with. \textit{in} is the array of octets to send into the HMAC process. \textit{inlen} is the
  1922. number of octets to process. Like the hash process routines, you can send the data in arbitrarily sized chunks. When you
  1923. are finished with the HMAC process you must call the following function to get the HMAC code:
  1924. \index{hmac\_done()}
  1925. \begin{verbatim}
  1926. int hmac_done( hmac_state *hmac,
  1927. unsigned char *out,
  1928. unsigned long *outlen);
  1929. \end{verbatim}
  1930. The \textit{hmac} parameter is the HMAC state you are working with. The \textit{out} parameter is the array of octets where the HMAC code should be stored.
  1931. You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
  1932. produced (depending on which hash was picked). If \textit{outlen} is less than the size of the message digest (and ultimately
  1933. the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).
  1934. There are two utility functions provided to make using HMACs easier to do. They accept the key and information about the
  1935. message (file pointer, address in memory), and produce the HMAC result in one shot. These are useful if you want to avoid
  1936. calling the three step process yourself.
  1937. \index{hmac\_memory()}
  1938. \begin{verbatim}
  1939. int hmac_memory(
  1940. int hash,
  1941. const unsigned char *key, unsigned long keylen,
  1942. const unsigned char *in, unsigned long inlen,
  1943. unsigned char *out, unsigned long *outlen);
  1944. \end{verbatim}
  1945. This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}. The index into the hash descriptor
  1946. table must be provided in \textit{hash}. It uses the key from \textit{key} with a key length of \textit{keylen}.
  1947. The result is stored in the array of octets \textit{out} and the length in \textit{outlen}. The value of \textit{outlen} must be set
  1948. to the size of the destination buffer before calling this function. Similarly for files there is the following function:
  1949. \index{hmac\_file()}
  1950. \begin{verbatim}
  1951. int hmac_file(
  1952. int hash,
  1953. const char *fname,
  1954. const unsigned char *key, unsigned long keylen,
  1955. unsigned char *out, unsigned long *outlen);
  1956. \end{verbatim}
  1957. \textit{hash} is the index into the hash descriptor table of the hash you want to use. \textit{fname} is the filename to process.
  1958. \textit{key} is the array of octets to use as the key of length \textit{keylen}. \textit{out} is the array of octets where the
  1959. result should be stored.
  1960. To test if the HMAC code is working there is the following function:
  1961. \index{hmac\_test()}
  1962. \begin{verbatim}
  1963. int hmac_test(void);
  1964. \end{verbatim}
  1965. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  1966. HMAC system is given below.
  1967. \begin{small}
  1968. \begin{verbatim}
  1969. #include <tomcrypt.h>
  1970. int main(void)
  1971. {
  1972. int idx, err;
  1973. hmac_state hmac;
  1974. unsigned char key[16], dst[MAXBLOCKSIZE];
  1975. unsigned long dstlen;
  1976. /* register SHA-1 */
  1977. if (register_hash(&sha1_desc) == -1) {
  1978. printf("Error registering SHA1\n");
  1979. return -1;
  1980. }
  1981. /* get index of SHA1 in hash descriptor table */
  1982. idx = find_hash("sha1");
  1983. /* we would make up our symmetric key in "key[]" here */
  1984. /* start the HMAC */
  1985. if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
  1986. printf("Error setting up hmac: %s\n", error_to_string(err));
  1987. return -1;
  1988. }
  1989. /* process a few octets */
  1990. if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
  1991. printf("Error processing hmac: %s\n", error_to_string(err));
  1992. return -1;
  1993. }
  1994. /* get result (presumably to use it somehow...) */
  1995. dstlen = sizeof(dst);
  1996. if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
  1997. printf("Error finishing hmac: %s\n", error_to_string(err));
  1998. return -1;
  1999. }
  2000. printf("The hmac is %lu bytes long\n", dstlen);
  2001. /* return */
  2002. return 0;
  2003. }
  2004. \end{verbatim}
  2005. \end{small}
  2006. \mysection{OMAC Support}
  2007. \index{OMAC} \index{CMAC}
  2008. OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
  2009. algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. Note: OMAC has been standardized as
  2010. CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous. From an API standpoint, the OMAC routines work much like the
  2011. HMAC routines. Instead, in this case a cipher is used instead of a hash.
  2012. To start an OMAC state you call
  2013. \index{omac\_init()}
  2014. \begin{verbatim}
  2015. int omac_init( omac_state *omac,
  2016. int cipher,
  2017. const unsigned char *key,
  2018. unsigned long keylen);
  2019. \end{verbatim}
  2020. The \textit{omac} parameter is the state for the OMAC algorithm. The \textit{cipher} parameter is the index into the cipher\_descriptor table
  2021. of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
  2022. wish to use. The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.
  2023. To send data through the algorithm call
  2024. \index{omac\_process()}
  2025. \begin{verbatim}
  2026. int omac_process( omac_state *state,
  2027. const unsigned char *in,
  2028. unsigned long inlen);
  2029. \end{verbatim}
  2030. This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}. Returns \textbf{CRYPT\_OK} if the
  2031. function succeeds. The function is not sensitive to the granularity of the data. For example,
  2032. \begin{verbatim}
  2033. omac_process(&mystate, "hello", 5);
  2034. omac_process(&mystate, " world", 6);
  2035. \end{verbatim}
  2036. Would produce the same result as,
  2037. \begin{verbatim}
  2038. omac_process(&mystate, "hello world", 11);
  2039. \end{verbatim}
  2040. When you are done processing the message you can call the following to compute the message tag.
  2041. \index{omac\_done()}
  2042. \begin{verbatim}
  2043. int omac_done( omac_state *state,
  2044. unsigned char *out,
  2045. unsigned long *outlen);
  2046. \end{verbatim}
  2047. Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}. Note that unlike the HMAC and other code
  2048. \textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
  2049. specification states that the output may be truncated. So if you pass in $outlen = 5$ and use AES as your cipher than
  2050. the output MAC code will only be five bytes long. If \textit{outlen} is larger than the default size it is set to the default
  2051. size to show how many bytes were actually used.
  2052. Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
  2053. following function.
  2054. \index{omac\_memory()}
  2055. \begin{verbatim}
  2056. int omac_memory(
  2057. int cipher,
  2058. const unsigned char *key, unsigned long keylen,
  2059. const unsigned char *in, unsigned long inlen,
  2060. unsigned char *out, unsigned long *outlen);
  2061. \end{verbatim}
  2062. This will compute the OMAC of \textit{inlen} bytes of \textit{in} using the key \textit{key} of length \textit{keylen} bytes and the cipher
  2063. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
  2064. rules as omac\_done.
  2065. To OMAC a file use
  2066. \index{omac\_file()}
  2067. \begin{verbatim}
  2068. int omac_file(
  2069. int cipher,
  2070. const unsigned char *key, unsigned long keylen,
  2071. const char *filename,
  2072. unsigned char *out, unsigned long *outlen);
  2073. \end{verbatim}
  2074. Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
  2075. and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
  2076. the same rules as omac\_done.
  2077. To test if the OMAC code is working there is the following function:
  2078. \index{omac\_test()}
  2079. \begin{verbatim}
  2080. int omac_test(void);
  2081. \end{verbatim}
  2082. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
  2083. OMAC system is given below.
  2084. \begin{small}
  2085. \begin{verbatim}
  2086. #include <tomcrypt.h>
  2087. int main(void)
  2088. {
  2089. int idx, err;
  2090. omac_state omac;
  2091. unsigned char key[16], dst[MAXBLOCKSIZE];
  2092. unsigned long dstlen;
  2093. /* register Rijndael */
  2094. if (register_cipher(&rijndael_desc) == -1) {
  2095. printf("Error registering Rijndael\n");
  2096. return -1;
  2097. }
  2098. /* get index of Rijndael in cipher descriptor table */
  2099. idx = find_cipher("rijndael");
  2100. /* we would make up our symmetric key in "key[]" here */
  2101. /* start the OMAC */
  2102. if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
  2103. printf("Error setting up omac: %s\n", error_to_string(err));
  2104. return -1;
  2105. }
  2106. /* process a few octets */
  2107. if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
  2108. printf("Error processing omac: %s\n", error_to_string(err));
  2109. return -1;
  2110. }
  2111. /* get result (presumably to use it somehow...) */
  2112. dstlen = sizeof(dst);
  2113. if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
  2114. printf("Error finishing omac: %s\n", error_to_string(err));
  2115. return -1;
  2116. }
  2117. printf("The omac is %lu bytes long\n", dstlen);
  2118. /* return */
  2119. return 0;
  2120. }
  2121. \end{verbatim}
  2122. \end{small}
  2123. \mysection{PMAC Support}
  2124. The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}}
  2125. protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
  2126. API as the provided OMAC code.
  2127. A PMAC state is initialized with the following.
  2128. \index{pmac\_init()}
  2129. \begin{verbatim}
  2130. int pmac_init( pmac_state *pmac,
  2131. int cipher,
  2132. const unsigned char *key,
  2133. unsigned long keylen);
  2134. \end{verbatim}
  2135. Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes. The chosen cipher
  2136. must have a 64 or 128 bit block size (e.x. AES).
  2137. To MAC data simply send it through the process function.
  2138. \index{pmac\_process()}
  2139. \begin{verbatim}
  2140. int pmac_process( pmac_state *state,
  2141. const unsigned char *in,
  2142. unsigned long inlen);
  2143. \end{verbatim}
  2144. This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}. The function is not sensitive to the granularity of the
  2145. data. For example,
  2146. \begin{verbatim}
  2147. pmac_process(&mystate, "hello", 5);
  2148. pmac_process(&mystate, " world", 6);
  2149. \end{verbatim}
  2150. Would produce the same result as,
  2151. \begin{verbatim}
  2152. pmac_process(&mystate, "hello world", 11);
  2153. \end{verbatim}
  2154. When a complete message has been processed the following function can be called to compute the message tag.
  2155. \index{pmac\_done()}
  2156. \begin{verbatim}
  2157. int pmac_done( pmac_state *state,
  2158. unsigned char *out,
  2159. unsigned long *outlen);
  2160. \end{verbatim}
  2161. This will store up to \textit{outlen} bytes of the tag for the given \textit{state} into \textit{out}. Note that if \textit{outlen} is larger
  2162. than the size of the tag it is set to the amount of bytes stored in \textit{out}.
  2163. Similar to the OMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
  2164. following function.
  2165. \index{pmac\_memory()}
  2166. \begin{verbatim}
  2167. int pmac_memory(
  2168. int cipher,
  2169. const unsigned char *key, unsigned long keylen,
  2170. const unsigned char *in, unsigned long inlen,
  2171. unsigned char *out, unsigned long *outlen);
  2172. \end{verbatim}
  2173. This will compute the PMAC of \textit{msglen} bytes of \textit{msg} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2174. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
  2175. rules as pmac\_done().
  2176. To PMAC a file use
  2177. \index{pmac\_file()}
  2178. \begin{verbatim}
  2179. int pmac_file(
  2180. int cipher,
  2181. const unsigned char *key, unsigned long keylen,
  2182. const char *filename,
  2183. unsigned char *out, unsigned long *outlen);
  2184. \end{verbatim}
  2185. Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes,
  2186. and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
  2187. the same rules as pmac\_done().
  2188. To test if the PMAC code is working there is the following function:
  2189. \index{pmac\_test()}
  2190. \begin{verbatim}
  2191. int pmac_test(void);
  2192. \end{verbatim}
  2193. Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
  2194. \mysection{Pelican MAC}
  2195. Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit{mixing function}. It achieves a very high
  2196. 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
  2197. as it calls AES directly.
  2198. \index{pelican\_init()}
  2199. \begin{verbatim}
  2200. int pelican_init( pelican_state *pelmac,
  2201. const unsigned char *key,
  2202. unsigned long keylen);
  2203. \end{verbatim}
  2204. This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
  2205. \index{pelican\_process()}
  2206. \begin{verbatim}
  2207. int pelican_process( pelican_state *pelmac,
  2208. const unsigned char *in,
  2209. unsigned long inlen);
  2210. \end{verbatim}
  2211. This will process \textit{inlen} bytes of \textit{in} through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
  2212. routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
  2213. an entire message.
  2214. \index{pelican\_done()}
  2215. \begin{verbatim}
  2216. int pelican_done(pelican_state *pelmac, unsigned char *out);
  2217. \end{verbatim}
  2218. This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.
  2219. \subsection{Example}
  2220. \begin{verbatim}
  2221. #include <tomcrypt.h>
  2222. int main(void)
  2223. {
  2224. pelican_state pelstate;
  2225. unsigned char key[32], tag[16];
  2226. int err;
  2227. /* somehow initialize a key */
  2228. /* initialize pelican mac */
  2229. if ((err = pelican_init(&pelstate, /* the state */
  2230. key, /* user key */
  2231. 32 /* key length in octets */
  2232. )) != CRYPT_OK) {
  2233. printf("Error initializing Pelican: %s",
  2234. error_to_string(err));
  2235. return EXIT_FAILURE;
  2236. }
  2237. /* MAC some data */
  2238. if ((err = pelican_process(&pelstate, /* the state */
  2239. "hello world", /* data to mac */
  2240. 11 /* length of data */
  2241. )) != CRYPT_OK) {
  2242. printf("Error processing Pelican: %s",
  2243. error_to_string(err));
  2244. return EXIT_FAILURE;
  2245. }
  2246. /* Terminate the MAC */
  2247. if ((err = pelican_done(&pelstate,/* the state */
  2248. tag /* where to store the tag */
  2249. )) != CRYPT_OK) {
  2250. printf("Error terminating Pelican: %s",
  2251. error_to_string(err));
  2252. return EXIT_FAILURE;
  2253. }
  2254. /* tag[0..15] has the MAC output now */
  2255. return EXIT_SUCCESS;
  2256. }
  2257. \end{verbatim}
  2258. \mysection{XCBC-MAC}
  2259. As of LibTomCrypt v1.15, XCBC-MAC (RFC 3566) has been provided to support TLS encryption suites. Like OMAC, it computes a message authentication code
  2260. by using a cipher in CBC mode. It also uses a single key which it expands into the requisite three keys for the MAC function. A XCBC--MAC state is
  2261. initialized with the following function:
  2262. \index{xcbc\_init()}
  2263. \begin{verbatim}
  2264. int xcbc_init( xcbc_state *xcbc,
  2265. int cipher,
  2266. const unsigned char *key,
  2267. unsigned long keylen);
  2268. \end{verbatim}
  2269. This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
  2270. by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
  2271. \index{LTC\_XCBC\_PURE}
  2272. It is possible to use XCBC in a three key mode by OR'ing the value \textbf{LTC\_XCBC\_PURE} against the \textit{keylen} parameter. In this mode, the key is
  2273. interpretted as three keys. If the cipher has a block size of $n$ octets, the first key is then $keylen - 2n$ octets and is the encryption key. The next
  2274. $2n$ octets are the $K_1$ and $K_2$ padding keys (used on the last block). For example, to use AES--192 \textit{keylen} should be $24 + 2 \cdot 16 = 56$ octets.
  2275. The three keys are interpretted as if they were concatenated in the \textit{key} buffer.
  2276. To process data through XCBC--MAC use the following function:
  2277. \index{xcbc\_process()}
  2278. \begin{verbatim}
  2279. int xcbc_process( xcbc_state *state,
  2280. const unsigned char *in,
  2281. unsigned long inlen);
  2282. \end{verbatim}
  2283. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}. Like the other MAC functions,
  2284. the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
  2285. To compute the MAC tag value use the following function:
  2286. \index{xcbc\_done()}
  2287. \begin{verbatim}
  2288. int xcbc_done( xcbc_state *state,
  2289. unsigned char *out,
  2290. unsigned long *outlen);
  2291. \end{verbatim}
  2292. This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
  2293. specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return \textbf{CRYPT\_OK} on success.
  2294. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  2295. \index{xcbc\_memory()}
  2296. \begin{verbatim}
  2297. int xcbc_memory(
  2298. int cipher,
  2299. const unsigned char *key, unsigned long keylen,
  2300. const unsigned char *in, unsigned long inlen,
  2301. unsigned char *out, unsigned long *outlen);
  2302. \end{verbatim}
  2303. This will compute the XCBC--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2304. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
  2305. To xcbc a file use
  2306. \index{xcbc\_file()}
  2307. \begin{verbatim}
  2308. int xcbc_file(
  2309. int cipher,
  2310. const unsigned char *key, unsigned long keylen,
  2311. const char *filename,
  2312. unsigned char *out, unsigned long *outlen);
  2313. \end{verbatim}
  2314. Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2315. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as xcbc\_done().
  2316. To test XCBC--MAC for RFC 3566 compliance use the following function:
  2317. \index{xcbc\_test()}
  2318. \begin{verbatim}
  2319. int xcbc_test(void);
  2320. \end{verbatim}
  2321. This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
  2322. \textbf{CRYPT\_NOP}.
  2323. \mysection{F9--MAC}
  2324. The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard. Originally specified to be used with the KASUMI block cipher, it can also be used
  2325. with other ciphers. For LibTomCrypt, the F9--MAC code can use any cipher.
  2326. \subsection{Usage Notice}
  2327. F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding. The padding quite simply is a direction
  2328. bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size. If the message is byte aligned, the padding takes on the form of
  2329. a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.
  2330. If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
  2331. with F9--MAC.
  2332. \subsection{F9--MAC Functions}
  2333. A F9--MAC state is initialized with the following function:
  2334. \index{f9\_init()}
  2335. \begin{verbatim}
  2336. int f9_init( f9_state *f9,
  2337. int cipher,
  2338. const unsigned char *key,
  2339. unsigned long keylen);
  2340. \end{verbatim}
  2341. This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
  2342. by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
  2343. To process data through F9--MAC use the following function:
  2344. \index{f9\_process()}
  2345. \begin{verbatim}
  2346. int f9_process( f9_state *state,
  2347. const unsigned char *in,
  2348. unsigned long inlen);
  2349. \end{verbatim}
  2350. This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}. Like the other MAC functions,
  2351. the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
  2352. To compute the MAC tag value use the following function:
  2353. \index{f9\_done()}
  2354. \begin{verbatim}
  2355. int f9_done( f9_state *state,
  2356. unsigned char *out,
  2357. unsigned long *outlen);
  2358. \end{verbatim}
  2359. This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
  2360. specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return
  2361. \textbf{CRYPT\_OK} on success.
  2362. Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
  2363. \index{f9\_memory()}
  2364. \begin{verbatim}
  2365. int f9_memory(
  2366. int cipher,
  2367. const unsigned char *key, unsigned long keylen,
  2368. const unsigned char *in, unsigned long inlen,
  2369. unsigned char *out, unsigned long *outlen);
  2370. \end{verbatim}
  2371. This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2372. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
  2373. To F9--MAC a file use
  2374. \index{f9\_file()}
  2375. \begin{verbatim}
  2376. int f9_file(
  2377. int cipher,
  2378. const unsigned char *key, unsigned long keylen,
  2379. const char *filename,
  2380. unsigned char *out, unsigned long *outlen);
  2381. \end{verbatim}
  2382. Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
  2383. specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
  2384. To test f9--MAC for RFC 3566 compliance use the following function:
  2385. \index{f9\_test()}
  2386. \begin{verbatim}
  2387. int f9_test(void);
  2388. \end{verbatim}
  2389. This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
  2390. \textbf{CRYPT\_NOP}.
  2391. \chapter{Pseudo-Random Number Generators}
  2392. \mysection{Core Functions}
  2393. The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
  2394. 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)
  2395. key generation. There is a universal structure called \textit{prng\_state}. To initialize a PRNG call:
  2396. \index{PRNG start}
  2397. \begin{verbatim}
  2398. int XXX_start(prng_state *prng);
  2399. \end{verbatim}
  2400. 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
  2401. entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
  2402. \index{PRNG add\_entropy}
  2403. \begin{verbatim}
  2404. int XXX_add_entropy(const unsigned char *in,
  2405. unsigned long inlen,
  2406. prng_state *prng);
  2407. \end{verbatim}
  2408. Which returns {\bf CRYPT\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
  2409. function to put the entropy into action.
  2410. \index{PRNG ready}
  2411. \begin{verbatim}
  2412. int XXX_ready(prng_state *prng);
  2413. \end{verbatim}
  2414. Which returns {\bf CRYPT\_OK} if it is ready. Finally to actually read bytes call:
  2415. \index{PRNG read}
  2416. \begin{verbatim}
  2417. unsigned long XXX_read(unsigned char *out,
  2418. unsigned long outlen,
  2419. prng_state *prng);
  2420. \end{verbatim}
  2421. Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
  2422. the following.
  2423. \index{PRNG done}
  2424. \begin{verbatim}
  2425. void XXX_done(prng_state *prng);
  2426. \end{verbatim}
  2427. This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
  2428. so that you can later resume the PRNG call the following.
  2429. \index{PRNG export}
  2430. \begin{verbatim}
  2431. int XXX_export(unsigned char *out,
  2432. unsigned long *outlen,
  2433. prng_state *prng);
  2434. \end{verbatim}
  2435. This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes. The idea of
  2436. the export is meant to be used as a \textit{seed file}. That is, when the program starts up there will not likely
  2437. be that much entropy available. To import a state to seed a PRNG call the following function.
  2438. \index{PRNG import}
  2439. \begin{verbatim}
  2440. int XXX_import(const unsigned char *in,
  2441. unsigned long inlen,
  2442. prng_state *prng);
  2443. \end{verbatim}
  2444. This will call the start and add\_entropy functions of the given PRNG. It will use the state in
  2445. \textit{in} of length \textit{inlen} as the initial seed. You must pass the same seed length as was exported
  2446. by the corresponding export function.
  2447. Note that importing a state will not \textit{resume} the PRNG from where it left off. That is, if you export
  2448. a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
  2449. specifically equal the 8 bytes you generated previously.
  2450. When a program is first executed the normal course of operation is:
  2451. \begin{enumerate}
  2452. \item Gather entropy from your sources for a given period of time or number of events.
  2453. \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
  2454. \end{enumerate}
  2455. When your program is finished you simply call the export function and save the state to a medium (disk,
  2456. flash memory, etc). The next time your application starts up you can detect the state, feed it to the
  2457. import function and go on your way. It is ideal that (as soon as possible) after start up you export a
  2458. fresh state. This helps in the case that the program aborts or the machine is powered down without
  2459. being given a chance to exit properly.
  2460. Note that even if you have a state to import it is important to add new entropy to the state. However,
  2461. there is less pressure to do so.
  2462. To test a PRNG for operational conformity call the following functions.
  2463. \index{PRNG test}
  2464. \begin{verbatim}
  2465. int XXX_test(void);
  2466. \end{verbatim}
  2467. This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
  2468. \subsection{Remarks}
  2469. It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
  2470. 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
  2471. 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
  2472. checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
  2473. \subsection{Example}
  2474. Below is a simple snippet to read 10 bytes from Yarrow. It is important to note that this snippet is {\bf NOT} secure since
  2475. the entropy added is not random.
  2476. \begin{verbatim}
  2477. #include <tomcrypt.h>
  2478. int main(void)
  2479. {
  2480. prng_state prng;
  2481. unsigned char buf[10];
  2482. int err;
  2483. /* start it */
  2484. if ((err = yarrow_start(&prng)) != CRYPT_OK) {
  2485. printf("Start error: %s\n", error_to_string(err));
  2486. }
  2487. /* add entropy */
  2488. if ((err = yarrow_add_entropy("hello world", 11, &prng))
  2489. != CRYPT_OK) {
  2490. printf("Add_entropy error: %s\n", error_to_string(err));
  2491. }
  2492. /* ready and read */
  2493. if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
  2494. printf("Ready error: %s\n", error_to_string(err));
  2495. }
  2496. printf("Read %lu bytes from yarrow\n",
  2497. yarrow_read(buf, sizeof(buf), &prng));
  2498. return 0;
  2499. }
  2500. \end{verbatim}
  2501. \mysection{PRNG Descriptors}
  2502. \index{PRNG Descriptor}
  2503. PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}. The
  2504. format of an element is:
  2505. \begin{verbatim}
  2506. struct _prng_descriptor {
  2507. char *name;
  2508. int export_size; /* size in bytes of exported state */
  2509. int (*start) (prng_state *);
  2510. int (*add_entropy)(const unsigned char *, unsigned long,
  2511. prng_state *);
  2512. int (*ready) (prng_state *);
  2513. unsigned long (*read)(unsigned char *, unsigned long len,
  2514. prng_state *);
  2515. void (*done)(prng_state *);
  2516. int (*pexport)(unsigned char *, unsigned long *, prng_state *);
  2517. int (*pimport)(const unsigned char *, unsigned long, prng_state *);
  2518. int (*test)(void);
  2519. };
  2520. \end{verbatim}
  2521. To find a PRNG in the descriptor table the following function can be used:
  2522. \index{find\_prng()}
  2523. \begin{verbatim}
  2524. int find_prng(const char *name);
  2525. \end{verbatim}
  2526. This will search the PRNG descriptor table for the PRNG named \textit{name}. It will return -1 if the PRNG is not found, otherwise, it returns
  2527. the index into the descriptor table.
  2528. Just like the ciphers and hashes, you must register your prng before you can use it. The two functions provided work exactly as those for the cipher registry functions.
  2529. They are the following:
  2530. \index{register\_prng()} \index{unregister\_prng()}
  2531. \begin{verbatim}
  2532. int register_prng(const struct _prng_descriptor *prng);
  2533. int unregister_prng(const struct _prng_descriptor *prng);
  2534. \end{verbatim}
  2535. The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error). It will avoid registering the same
  2536. descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once. The unregister function
  2537. will return \textbf{CRYPT\_OK} if the PRNG was found and removed. Otherwise, it returns \textbf{CRYPT\_ERROR}.
  2538. \subsection{PRNGs Provided}
  2539. \begin{figure}[h]
  2540. \begin{center}
  2541. \begin{small}
  2542. \begin{tabular}{|c|c|l|}
  2543. \hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
  2544. \hline ChaCha20 & chacha20\_prng\_desc & Stream Cipher PRNG (recommended, fast) \\
  2545. \hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended, secure) \\
  2546. \hline RC4 & rc4\_desc & Stream Cipher PRNG \\
  2547. \hline SOBER-128 & sober128\_desc & Stream Cipher PRNG \\
  2548. \hline sprng & sprng\_desc & Secure PRNG using the System RNG \\
  2549. \hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
  2550. \hline
  2551. \end{tabular}
  2552. \end{small}
  2553. \end{center}
  2554. \caption{List of Provided PRNGs}
  2555. \end{figure}
  2556. \subsubsection{Yarrow}
  2557. Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
  2558. (keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.
  2559. \textit{Note:} This PRNG is still secure for most tasks but is no longer recommended. Users
  2560. should use Fortuna or ChaCha20 instead.
  2561. \subsubsection{Fortuna}
  2562. Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
  2563. usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
  2564. to work with most cipher and hash combos based on which you have chosen to build into the library.} while
  2565. providing more security.
  2566. Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
  2567. and SHA--256 hash function. Technically, Fortuna will work with any block cipher that accepts a 256--bit
  2568. key, and any hash that produces at least a 256--bit output. However, to make the implementation simpler
  2569. it has been fixed to those choices.
  2570. Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
  2571. added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
  2572. details Fortuna has the ability to recover from state determination attacks where the attacker starts
  2573. to learn information from the PRNGs output about the internal state. Yarrow on the other hand, cannot
  2574. recover from that problem until new entropy is added to the pool and put to use through the ready() function.
  2575. \subsubsection{RC4}
  2576. RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You key RC4 by
  2577. calling add\_entropy(), and setup the key by calling ready().
  2578. You really should not use RC4 for cryptographical purposes, it's broken.
  2579. \subsubsection{SOBER-128}
  2580. SOBER--128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4, you key it by
  2581. calling add\_entropy(). There is no need to call ready() for this PRNG as it does not do anything.
  2582. Note: this cipher has several oddities about how it operates. The first call to add\_entropy() sets the cipher's key.
  2583. Every other time call to the add\_entropy() function sets the cipher's IV variable. The IV mechanism allows you to
  2584. encrypt several messages with the same key, and not re--use the same key material.
  2585. Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
  2586. you pass it on the \textbf{first} call to add\_entropy(). All buffers sent to add\_entropy() must have a length
  2587. that is a multiple of four bytes.
  2588. Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner, you can use
  2589. sober128\_read() as an encrypt (and decrypt) function.
  2590. Since SOBER--128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
  2591. key it from the output of Fortuna (or Yarrow), and use it to encrypt messages. It is also ideal for
  2592. simulations which need a high quality (and fast) stream of bytes.
  2593. \subsubsection{ChaCha20}
  2594. ChaCha20 is a fast stream cipher built on a pseudorandom function designed by Daniel J. Bernstein.
  2595. It can also double duty as a PRNG.
  2596. The implementation supports adding entropy via the add\_entropy() function while already being operational.
  2597. \subsubsection{Example Usage}
  2598. \begin{small}
  2599. \begin{verbatim}
  2600. #include <tomcrypt.h>
  2601. int main(void)
  2602. {
  2603. prng_state prng;
  2604. unsigned char buf[32];
  2605. int err;
  2606. if ((err = rc4_start(&prng)) != CRYPT_OK) {
  2607. printf("RC4 init error: %s\n", error_to_string(err));
  2608. exit(-1);
  2609. }
  2610. /* use "key" as the key */
  2611. if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
  2612. printf("RC4 add entropy error: %s\n", error_to_string(err));
  2613. exit(-1);
  2614. }
  2615. /* setup RC4 for use */
  2616. if ((err = rc4_ready(&prng)) != CRYPT_OK) {
  2617. printf("RC4 ready error: %s\n", error_to_string(err));
  2618. exit(-1);
  2619. }
  2620. /* encrypt buffer */
  2621. strcpy(buf,"hello world");
  2622. if (rc4_read(buf, 11, &prng) != 11) {
  2623. printf("RC4 read error\n");
  2624. exit(-1);
  2625. }
  2626. return 0;
  2627. }
  2628. \end{verbatim}
  2629. \end{small}
  2630. To decrypt you have to do the exact same steps.
  2631. \mysection{The Secure RNG}
  2632. \index{Secure RNG}
  2633. An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data. They generate their random bits
  2634. by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
  2635. PRNG. Computers are deterministic that try hard not to stray from pre--determined paths. This makes gathering entropy needed to seed a PRNG
  2636. a hard task.
  2637. There is one small function that may help on certain platforms:
  2638. \index{rng\_get\_bytes()}
  2639. \begin{verbatim}
  2640. unsigned long rng_get_bytes(
  2641. unsigned char *buf,
  2642. unsigned long len,
  2643. void (*callback)(void));
  2644. \end{verbatim}
  2645. Which will try one of three methods of getting random data. The first is to open the popular \textit{/dev/random} device which
  2646. on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite. It emulates \textit{/dev/random} via the Microsoft CSP.}.
  2647. The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG. The third method is an ANSI C
  2648. clock drift method that is also somewhat popular but gives bits of lower entropy. The \textit{callback} parameter is a pointer to a function that returns void. It is
  2649. used when the slower ANSI C RNG must be used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of roughly three
  2650. bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to. The function returns the number of bytes actually read from
  2651. any RNG source. There is a function to help setup a PRNG as well:
  2652. \index{rng\_make\_prng()}
  2653. \begin{verbatim}
  2654. int rng_make_prng( int bits,
  2655. int wprng,
  2656. prng_state *prng,
  2657. void (*callback)(void));
  2658. \end{verbatim}
  2659. This will try to initialize the prng with a state of at least \textit{bits} of entropy. The \textit{callback} parameter works much like
  2660. the callback in \textit{rng\_get\_bytes()}. It is highly recommended that you use this function to setup your PRNGs unless you have a
  2661. platform where the RNG does not work well. Example usage of this function is given below:
  2662. \begin{small}
  2663. \begin{verbatim}
  2664. #include <tomcrypt.h>
  2665. int main(void)
  2666. {
  2667. ecc_key mykey;
  2668. prng_state prng;
  2669. int err;
  2670. /* register yarrow */
  2671. if (register_prng(&yarrow_desc) == -1) {
  2672. printf("Error registering Yarrow\n");
  2673. return -1;
  2674. }
  2675. /* setup the PRNG */
  2676. if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL))
  2677. != CRYPT_OK) {
  2678. printf("Error setting up PRNG, %s\n", error_to_string(err));
  2679. return -1;
  2680. }
  2681. /* make a 192-bit ECC key */
  2682. if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey))
  2683. != CRYPT_OK) {
  2684. printf("Error making key: %s\n", error_to_string(err));
  2685. return -1;
  2686. }
  2687. return 0;
  2688. }
  2689. \end{verbatim}
  2690. \end{small}
  2691. \subsection{The Secure PRNG Interface}
  2692. \index{sprng\_desc}
  2693. It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
  2694. as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
  2695. requires to be started, that is you need not call the start, add\_entropy, or ready functions. For example, consider
  2696. the previous example using this PRNG.
  2697. \begin{small}
  2698. \begin{verbatim}
  2699. #include <tomcrypt.h>
  2700. int main(void)
  2701. {
  2702. ecc_key mykey;
  2703. int err;
  2704. /* register SPRNG */
  2705. if (register_prng(&sprng_desc) == -1) {
  2706. printf("Error registering SPRNG\n");
  2707. return -1;
  2708. }
  2709. /* make a 192-bit ECC key */
  2710. if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey))
  2711. != CRYPT_OK) {
  2712. printf("Error making key: %s\n", error_to_string(err));
  2713. return -1;
  2714. }
  2715. return 0;
  2716. }
  2717. \end{verbatim}
  2718. \end{small}
  2719. \chapter{RSA Public Key Cryptography}
  2720. \mysection{Introduction}
  2721. RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
  2722. padding algorithms for encryption and signatures. The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
  2723. To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.
  2724. \mysection{PKCS \#1 Padding}
  2725. PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function. Note: the
  2726. signature padding does \textbf{not} include the ASN.1 padding required. That is performed by the rsa\_sign\_hash\_ex() function
  2727. documented later on in this chapter.
  2728. \subsection{PKCS \#1 v1.5 Encoding}
  2729. The following function performs PKCS \#1 v1.5 padding:
  2730. \index{pkcs\_1\_v1\_5\_encode()}
  2731. \begin{verbatim}
  2732. int pkcs_1_v1_5_encode(
  2733. const unsigned char *msg,
  2734. unsigned long msglen,
  2735. int block_type,
  2736. unsigned long modulus_bitlen,
  2737. prng_state *prng,
  2738. int prng_idx,
  2739. unsigned char *out,
  2740. unsigned long *outlen);
  2741. \end{verbatim}
  2742. This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets. The \textit{block\_type} parameter must be set to
  2743. \textbf{LTC\_PKCS\_1\_EME} to perform encryption padding. It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding. The \textit{modulus\_bitlen}
  2744. parameter indicates the length of the modulus in bits. The padded data is stored in \textit{out} with a length of \textit{outlen} octets. The output will not be
  2745. longer than the modulus which helps allocate the correct output buffer size.
  2746. Only encryption padding requires a PRNG. When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.
  2747. \subsection{PKCS \#1 v1.5 Decoding}
  2748. The following function performs PKCS \#1 v1.5 de--padding:
  2749. \index{pkcs\_1\_v1\_5\_decode()}
  2750. \begin{verbatim}
  2751. int pkcs_1_v1_5_decode(
  2752. const unsigned char *msg,
  2753. unsigned long msglen,
  2754. int block_type,
  2755. unsigned long modulus_bitlen,
  2756. unsigned char *out,
  2757. unsigned long *outlen,
  2758. int *is_valid);
  2759. \end{verbatim}
  2760. \index{LTC\_PKCS\_1\_EME} \index{LTC\_PKCS\_1\_EMSA}
  2761. This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}. The decoded data is stored in \textit{out} of length
  2762. \textit{outlen}. If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored. The \textit{block\_type} parameter must be set to either
  2763. \textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.
  2764. \mysection{PKCS \#1 v2.1 Encryption}
  2765. PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
  2766. the library is concerned we are only dealing with th OAEP padding of the message.
  2767. \subsection{OAEP Encoding}
  2768. The following function performs PKCS \#1 v2.1 encryption padding:
  2769. \index{pkcs\_1\_oaep\_encode()}
  2770. \begin{alltt}
  2771. int pkcs_1_oaep_encode(
  2772. const unsigned char *msg,
  2773. unsigned long msglen,
  2774. const unsigned char *lparam,
  2775. unsigned long lparamlen,
  2776. unsigned long modulus_bitlen,
  2777. prng_state *prng,
  2778. int prng_idx,
  2779. int hash_idx,
  2780. unsigned char *out,
  2781. unsigned long *outlen);
  2782. \end{alltt}
  2783. This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded. The \textit{lparam} variable is an additional system specific
  2784. tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
  2785. \textit{lparam} can be set to \textbf{NULL}.
  2786. 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
  2787. \textit{modulus\_bitlen}. \textit{hash\_idx} is the index into the hash descriptor table of the hash desired. PKCS \#1 allows any hash to be
  2788. 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
  2789. sized input message. \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.
  2790. The padded message is stored in \textit{out} along with the length in \textit{outlen}.
  2791. If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for \textit{msg} is
  2792. $m - 2h - 2$. For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.
  2793. Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
  2794. rsa\_exptmod() to encrypt it.
  2795. \subsection{OAEP Decoding}
  2796. \index{pkcs\_1\_oaep\_decode()}
  2797. \begin{alltt}
  2798. int pkcs_1_oaep_decode(
  2799. const unsigned char *msg,
  2800. unsigned long msglen,
  2801. const unsigned char *lparam,
  2802. unsigned long lparamlen,
  2803. unsigned long modulus_bitlen,
  2804. int hash_idx,
  2805. unsigned char *out,
  2806. unsigned long *outlen,
  2807. int *res);
  2808. \end{alltt}
  2809. This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. \textit{msg} is the
  2810. output of pkcs\_1\_oaep\_encode() of length \textit{msglen}. \textit{lparam} is the same system variable passed to the OAEP encoder. If it does not
  2811. match what was used during encoding this function will not decode the packet. \textit{modulus\_bitlen} is the size of the RSA modulus in bits
  2812. and must match what was used during encoding. Similarly the \textit{hash\_idx} index into the hash descriptor table must match what was used
  2813. during encoding.
  2814. If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a
  2815. $1$ in \textit{res}. If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
  2816. it returns an error code.
  2817. \mysection{PKCS \#1 Digital Signatures}
  2818. \subsection{PSS Encoding}
  2819. PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
  2820. \index{pkcs\_1\_pss\_encode()}
  2821. \begin{alltt}
  2822. int pkcs_1_pss_encode(
  2823. const unsigned char *msghash,
  2824. unsigned long msghashlen,
  2825. unsigned long saltlen,
  2826. prng_state *prng,
  2827. int prng_idx,
  2828. int hash_idx,
  2829. unsigned long modulus_bitlen,
  2830. unsigned char *out,
  2831. unsigned long *outlen);
  2832. \end{alltt}
  2833. This function assumes the message to be PSS encoded has previously been hashed. The input hash \textit{msghash} is of length
  2834. \textit{msghashlen}. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
  2835. \textit{hash\_idx} is the index into the hash descriptor table of the hash to use. \textit{prng\_idx} and \textit{prng} are the random
  2836. number generator information required for the salt.
  2837. Similar to OAEP encoding \textit{modulus\_bitlen} is the size of the RSA modulus (in bits). It limits the size of the salt. If $m$ is the length
  2838. of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
  2839. 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().
  2840. \subsection{PSS Decoding}
  2841. To decode a PSS encoded signature block you have to use the following.
  2842. \index{pkcs\_1\_pss\_decode()}
  2843. \begin{alltt}
  2844. int pkcs_1_pss_decode(
  2845. const unsigned char *msghash,
  2846. unsigned long msghashlen,
  2847. const unsigned char *sig,
  2848. unsigned long siglen,
  2849. unsigned long saltlen,
  2850. int hash_idx,
  2851. unsigned long modulus_bitlen,
  2852. int *res);
  2853. \end{alltt}
  2854. This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
  2855. \textit{msghashlen}. If the block is a valid PSS block and the decoded hash equals the hash supplied \textit{res} is set to non--zero. Otherwise,
  2856. it is set to zero. The rest of the parameters are as in the PSS encode call.
  2857. It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
  2858. \mysection{RSA Key Operations}
  2859. \subsection{Background}
  2860. RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown
  2861. factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
  2862. not strictly equivalent.
  2863. The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or \textit{Euler totient} of the
  2864. multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
  2865. $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
  2866. $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
  2867. often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
  2868. A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
  2869. $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
  2870. given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
  2871. $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
  2872. can sign a message by \textit{decrypting} it. Others can verify it by \textit{encrypting} it.
  2873. Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
  2874. Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
  2875. the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
  2876. The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
  2877. designed for fast exponentiation (requires 16 squarings and one multiplication).
  2878. It is important to pad the input to RSA since it has particular mathematical structure. For instance
  2879. $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
  2880. to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
  2881. together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
  2882. the hash of documents only but also to pad the inputs with data to remove such structure.
  2883. \subsection{RSA Key Generation}
  2884. For RSA routines a single \textit{rsa\_key} structure is used. To make a new RSA key call:
  2885. \index{rsa\_make\_key()}
  2886. \begin{verbatim}
  2887. int rsa_make_key(prng_state *prng,
  2888. int wprng,
  2889. int size,
  2890. long e,
  2891. rsa_key *key);
  2892. \end{verbatim}
  2893. Where \textit{wprng} is the index into the PRNG descriptor array. The \textit{size} parameter is the size in bytes of the RSA modulus desired.
  2894. The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537. Stick with 65537 since it is big enough to prevent
  2895. trivial math attacks, and not super slow. The \textit{key} parameter is where the constructed key is placed. All keys must be at
  2896. least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
  2897. \index{rsa\_free()}
  2898. Note: the \textit{rsa\_make\_key()} function allocates memory at run--time when you make the key. Make sure to call
  2899. \textit{rsa\_free()} (see below) when you are finished with the key. If \textit{rsa\_make\_key()} fails it will automatically
  2900. free the memory allocated.
  2901. \index{PK\_PRIVATE} \index{PK\_PUBLIC}
  2902. There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
  2903. RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the
  2904. PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant). The second type, is a public RSA key which only includes the modulus and public exponent.
  2905. It takes the form of a RSAPublicKey (PKCS \#1 compliant).
  2906. \subsection{RSA Exponentiation}
  2907. To do raw work with the RSA function, that is without padding, use the following function:
  2908. \index{rsa\_exptmod()}
  2909. \begin{verbatim}
  2910. int rsa_exptmod(const unsigned char *in,
  2911. unsigned long inlen,
  2912. unsigned char *out,
  2913. unsigned long *outlen,
  2914. int which,
  2915. rsa_key *key);
  2916. \end{verbatim}
  2917. This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
  2918. in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e}
  2919. (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
  2920. Note: the output of this function is zero--padded as per PKCS \#1 specification. This allows this routine to work with PKCS \#1 padding functions properly.
  2921. \subsection{RSA Key Size}
  2922. To fetch the key size of an RSA key, use the following function:
  2923. \index{rsa\_get\_size()}
  2924. \begin{verbatim}
  2925. int rsa_get_size(rsa_key *key);
  2926. \end{verbatim}
  2927. This can be used to determine the modulus size of an RSA key.
  2928. \mysection{RSA Key Encryption}
  2929. Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
  2930. To facilitate encrypting short keys the following functions have been provided.
  2931. \index{rsa\_encrypt\_key()}
  2932. \begin{verbatim}
  2933. int rsa_encrypt_key(
  2934. const unsigned char *in,
  2935. unsigned long inlen,
  2936. unsigned char *out,
  2937. unsigned long *outlen,
  2938. const unsigned char *lparam,
  2939. unsigned long lparamlen,
  2940. prng_state *prng,
  2941. int prng_idx,
  2942. int hash_idx,
  2943. rsa_key *key);
  2944. \end{verbatim}
  2945. This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
  2946. in \textit{out} of length \textit{outlen} octets. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
  2947. to \index{pkcs\_1\_oaep\_encode()} pkcs\_1\_oaep\_encode().
  2948. \subsection{Extended Encryption}
  2949. As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
  2950. encryption function:
  2951. \index{rsa\_encrypt\_key\_ex()}
  2952. \begin{verbatim}
  2953. int rsa_encrypt_key_ex(
  2954. const unsigned char *in,
  2955. unsigned long inlen,
  2956. unsigned char *out,
  2957. unsigned long *outlen,
  2958. const unsigned char *lparam,
  2959. unsigned long lparamlen,
  2960. prng_state *prng,
  2961. int prng_idx,
  2962. int hash_idx,
  2963. int padding,
  2964. rsa_key *key);
  2965. \end{verbatim}
  2966. \index{LTC\_PKCS\_1\_OAEP} \index{LTC\_PKCS\_1\_V1\_5}
  2967. The parameters are all the same as for rsa\_encrypt\_key() except for the addition of the \textit{padding} parameter. It must be set to
  2968. \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 encryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 encryption.
  2969. When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
  2970. \mysection{RSA Key Decryption}
  2971. \index{rsa\_decrypt\_key()}
  2972. \begin{verbatim}
  2973. int rsa_decrypt_key(
  2974. const unsigned char *in,
  2975. unsigned long inlen,
  2976. unsigned char *out,
  2977. unsigned long *outlen,
  2978. const unsigned char *lparam,
  2979. unsigned long lparamlen,
  2980. int hash_idx,
  2981. int *stat,
  2982. rsa_key *key);
  2983. \end{verbatim}
  2984. This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
  2985. \textit{out} of length \textit{outlen}. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
  2986. to pkcs\_1\_oaep\_decode().
  2987. If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$. Otherwise, it is set to $1$.
  2988. \subsection{Extended Decryption}
  2989. As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions. The following is the extended
  2990. decryption function:
  2991. \index{rsa\_decrypt\_key\_ex()}
  2992. \begin{verbatim}
  2993. int rsa_decrypt_key_ex(
  2994. const unsigned char *in,
  2995. unsigned long inlen,
  2996. unsigned char *out,
  2997. unsigned long *outlen,
  2998. const unsigned char *lparam,
  2999. unsigned long lparamlen,
  3000. int hash_idx,
  3001. int padding,
  3002. int *stat,
  3003. rsa_key *key);
  3004. \end{verbatim}
  3005. Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.
  3006. It must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 decryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 decryption.
  3007. When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
  3008. \mysection{RSA Signature Generation}
  3009. Similar to RSA key encryption RSA is also used to \textit{digitally sign} message digests (hashes). To facilitate this
  3010. process the following functions have been provided.
  3011. \index{rsa\_sign\_hash()}
  3012. \begin{verbatim}
  3013. int rsa_sign_hash(const unsigned char *in,
  3014. unsigned long inlen,
  3015. unsigned char *out,
  3016. unsigned long *outlen,
  3017. prng_state *prng,
  3018. int prng_idx,
  3019. int hash_idx,
  3020. unsigned long saltlen,
  3021. rsa_key *key);
  3022. \end{verbatim}
  3023. This will PSS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PSS encoded hash will be RSA
  3024. \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.
  3025. The \textit{hash\_idx} parameter indicates which hash will be used to create the PSS encoding. It should be the same as the hash used to
  3026. hash the message being signed. The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small. A good
  3027. default value is between 8 and 16 octets. Strictly, it must be small than $modulus\_len - hLen - 2$ where \textit{modulus\_len} is the size of
  3028. the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.
  3029. \subsection{Extended Signatures}
  3030. As of v1.15, the library supports both v1.5 and v2.1 signatures. The extended signature generation function has the following prototype:
  3031. \index{rsa\_sign\_hash\_ex()}
  3032. \begin{verbatim}
  3033. int rsa_sign_hash_ex(
  3034. const unsigned char *in,
  3035. unsigned long inlen,
  3036. unsigned char *out,
  3037. unsigned long *outlen,
  3038. int padding,
  3039. prng_state *prng,
  3040. int prng_idx,
  3041. int hash_idx,
  3042. unsigned long saltlen,
  3043. rsa_key *key);
  3044. \end{verbatim}
  3045. This will PKCS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets. Next, the PKCS encoded hash will be RSA
  3046. \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets. The \textit{padding} parameter
  3047. must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to produce a v1.5 signature, otherwise, it must be set to \textbf{LTC\_PKCS\_1\_PSS} to produce a
  3048. v2.1 signature.
  3049. When performing a v1.5 signature the \textit{prng}, \textit{prng\_idx}, and \textit{hash\_idx} parameters are not checked and can be left to any
  3050. values such as $\lbrace$\textbf{NULL}, 0, 0$\rbrace$.
  3051. \mysection{RSA Signature Verification}
  3052. \index{rsa\_verify\_hash()}
  3053. \begin{verbatim}
  3054. int rsa_verify_hash(const unsigned char *sig,
  3055. unsigned long siglen,
  3056. const unsigned char *msghash,
  3057. unsigned long msghashlen,
  3058. int hash_idx,
  3059. unsigned long saltlen,
  3060. int *stat,
  3061. rsa_key *key);
  3062. \end{verbatim}
  3063. This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PSS decoded
  3064. and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
  3065. If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash}
  3066. value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
  3067. \subsection{RSA Signature Salt Length}
  3068. The v2.1 signature algorithm requires a salt length to be able to properly
  3069. encode resp. decode. To fetch the maximum possible salt length this function
  3070. is provided:
  3071. \index{rsa\_sign\_saltlen\_get\_max()}
  3072. \begin{verbatim}
  3073. int rsa_sign_saltlen_get_max(int hash_idx, rsa_key *key);
  3074. \end{verbatim}
  3075. As stated in the PKCS\#1 RFC3447 "Typical salt lengths in octets are hLen
  3076. (the length of the output of the hash function Hash) and 0".
  3077. This function is provided to be able to use other lengths as well and to make
  3078. sure at runtime that the RSA key can handle the desired salt length.
  3079. \subsection{Extended Verification}
  3080. As of v1.15, the library supports both v1.5 and v2.1 signature verification. The extended signature verification function has the following prototype:
  3081. \index{rsa\_verify\_hash\_ex()}
  3082. \begin{verbatim}
  3083. int rsa_verify_hash_ex(
  3084. const unsigned char *sig,
  3085. unsigned long siglen,
  3086. const unsigned char *hash,
  3087. unsigned long hashlen,
  3088. int padding,
  3089. int hash_idx,
  3090. unsigned long saltlen,
  3091. int *stat,
  3092. rsa_key *key);
  3093. \end{verbatim}
  3094. This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets. Next, the RSA decoded data is PKCS decoded
  3095. and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
  3096. If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash}
  3097. value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
  3098. The \textit{padding} parameter must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform a v1.5 verification. Otherwise, it must be set to
  3099. \textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification. When performing a v1.5 verification the \textit{hash\_idx} and \textit{saltlen} parameters are ignored.
  3100. \mysection{RSA Encryption Example}
  3101. \begin{small}
  3102. \begin{verbatim}
  3103. #include <tomcrypt.h>
  3104. int main(void)
  3105. {
  3106. int err, hash_idx, prng_idx, res;
  3107. unsigned long l1, l2;
  3108. unsigned char pt[16], pt2[16], out[1024];
  3109. rsa_key key;
  3110. /* register prng/hash */
  3111. if (register_prng(&sprng_desc) == -1) {
  3112. printf("Error registering sprng");
  3113. return EXIT_FAILURE;
  3114. }
  3115. /* register a math library (in this case TomsFastMath)
  3116. ltc_mp = tfm_desc;
  3117. if (register_hash(&sha1_desc) == -1) {
  3118. printf("Error registering sha1");
  3119. return EXIT_FAILURE;
  3120. }
  3121. hash_idx = find_hash("sha1");
  3122. prng_idx = find_prng("sprng");
  3123. /* make an RSA-1024 key */
  3124. if ((err = rsa_make_key(NULL, /* PRNG state */
  3125. prng_idx, /* PRNG idx */
  3126. 1024/8, /* 1024-bit key */
  3127. 65537, /* we like e=65537 */
  3128. &key) /* where to store the key */
  3129. ) != CRYPT_OK) {
  3130. printf("rsa_make_key %s", error_to_string(err));
  3131. return EXIT_FAILURE;
  3132. }
  3133. /* fill in pt[] with a key we want to send ... */
  3134. l1 = sizeof(out);
  3135. if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
  3136. 16, /* data is 16 bytes long */
  3137. out, /* where to store ciphertext */
  3138. &l1, /* length of ciphertext */
  3139. "TestApp", /* our lparam for this program */
  3140. 7, /* lparam is 7 bytes long */
  3141. NULL, /* PRNG state */
  3142. prng_idx, /* prng idx */
  3143. hash_idx, /* hash idx */
  3144. &key) /* our RSA key */
  3145. ) != CRYPT_OK) {
  3146. printf("rsa_encrypt_key %s", error_to_string(err));
  3147. return EXIT_FAILURE;
  3148. }
  3149. /* now let's decrypt the encrypted key */
  3150. l2 = sizeof(pt2);
  3151. if ((err = rsa_decrypt_key(out, /* encrypted data */
  3152. l1, /* length of ciphertext */
  3153. pt2, /* where to put plaintext */
  3154. &l2, /* plaintext length */
  3155. "TestApp", /* lparam for this program */
  3156. 7, /* lparam is 7 bytes long */
  3157. hash_idx, /* hash idx */
  3158. &res, /* validity of data */
  3159. &key) /* our RSA key */
  3160. ) != CRYPT_OK) {
  3161. printf("rsa_decrypt_key %s", error_to_string(err));
  3162. return EXIT_FAILURE;
  3163. }
  3164. /* if all went well pt == pt2, l2 == 16, res == 1 */
  3165. }
  3166. \end{verbatim}
  3167. \end{small}
  3168. \mysection{RSA Key Format}
  3169. The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as
  3170. RSAPublicKey and RSAPrivateKey. Additionally, the OpenSSL key format is supported as well.
  3171. \subsection{RSA Key Export}
  3172. To export a RSA key use the following function.
  3173. \index{rsa\_export()}
  3174. \begin{verbatim}
  3175. int rsa_export(unsigned char *out,
  3176. unsigned long *outlen,
  3177. int type,
  3178. rsa_key *key);
  3179. \end{verbatim}
  3180. This will export the RSA key depending on the value of \textit{type}.
  3181. The RSAPublicKey (PKCS \#1 type) format will be used for the public key,
  3182. indicated by \textbf{PK\_PUBLIC}.
  3183. The RSAPrivateKey (PKCS \#1 type) format will be used for the private key,
  3184. indicated by \textbf{PK\_PRIVATE}.
  3185. As of v1.18 this function can also export OpenSSL-compatible formatted public RSA keys.
  3186. By OR'ing \textbf{PK\_STD} and \textbf{PK\_PUBLIC} the public key will be exported
  3187. in the SubjectPublicKeyInfo (X.509 type) format.
  3188. \subsection{RSA Key Import}
  3189. To import a RSA key use the following function.
  3190. \index{rsa\_import()}
  3191. \begin{verbatim}
  3192. int rsa_import(const unsigned char *in,
  3193. unsigned long inlen,
  3194. rsa_key *key);
  3195. \end{verbatim}
  3196. This will import the key stored in \textit{inlen} and import it to \textit{key}. If the function fails it will automatically free any allocated memory. This
  3197. function can import both RSAPublicKey and RSAPrivateKey formats.
  3198. As of v1.06 this function can also import OpenSSL DER formatted public RSA keys. They are essentially encapsulated RSAPublicKeys. LibTomCrypt will
  3199. import the key, strip off the additional data and fill in the rsa\_key structure.
  3200. \chapter{Diffie-Hellman Key Exchange}
  3201. \section{Background}
  3202. Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
  3203. of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
  3204. generates a large sub-group of prime order (for unique values of $x$).
  3205. 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
  3206. ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
  3207. 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
  3208. a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
  3209. From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
  3210. $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
  3211. $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
  3212. the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
  3213. symmetric cipher.
  3214. It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
  3215. discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
  3216. modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
  3217. $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
  3218. To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
  3219. the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
  3220. smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
  3221. \section{Core Functions}
  3222. This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
  3223. provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
  3224. called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first routine is to
  3225. make a Diffie-Hellman private key pair:
  3226. \index{dh\_make\_key()}
  3227. \begin{verbatim}
  3228. int dh_make_key(prng_state *prng, int wprng,
  3229. int keysize, dh_key *key);
  3230. \end{verbatim}
  3231. The ``keysize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 512 bytes which correspond
  3232. 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
  3233. specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
  3234. above 512 it will return an error. So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass
  3235. ``keysize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
  3236. to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
  3237. $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
  3238. leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
  3239. hard.
  3240. The next two routines are for exporting/importing Diffie-Hellman keys in a binary format. This is useful for transport
  3241. over communication mediums.
  3242. \index{dh\_export()} \index{dh\_import()}
  3243. \begin{verbatim}
  3244. int dh_export(unsigned char *out, unsigned long *outlen,
  3245. int type, dh_key *key);
  3246. int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
  3247. \end{verbatim}
  3248. These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
  3249. 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
  3250. ``dh\_key'' using:
  3251. \begin{verbatim}
  3252. void dh_free(dh_key *key);
  3253. \end{verbatim}
  3254. After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
  3255. with the other user using:
  3256. \index{dh\_shared\_secret()}
  3257. \begin{verbatim}
  3258. int dh_shared_secret(dh_key *private_key,
  3259. dh_key *public_key,
  3260. unsigned char *out, unsigned long *outlen);
  3261. \end{verbatim}
  3262. 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
  3263. 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
  3264. 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
  3265. key:
  3266. \index{dh\_get\_size()}
  3267. \begin{verbatim}
  3268. int dh_get_size(dh_key *key);
  3269. \end{verbatim}
  3270. This returns the size in bytes of the modulus chosen for that key.
  3271. \subsection{Remarks on Usage}
  3272. Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
  3273. 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.}:
  3274. \newpage
  3275. \begin{small}
  3276. \begin{verbatim}
  3277. int establish_secure_socket(int sock, int mode, unsigned char *key,
  3278. prng_state *prng, int wprng)
  3279. {
  3280. unsigned char buf[4096], buf2[4096];
  3281. unsigned long x, len;
  3282. int res, err, inlen;
  3283. dh_key mykey, theirkey;
  3284. /* make up our private key */
  3285. if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK) {
  3286. return err;
  3287. }
  3288. /* export our key as public */
  3289. x = sizeof(buf);
  3290. if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
  3291. res = err;
  3292. goto done2;
  3293. }
  3294. if (mode == 0) {
  3295. /* mode 0 so we send first */
  3296. if (send(sock, buf, x, 0) != x) {
  3297. res = CRYPT_ERROR;
  3298. goto done2;
  3299. }
  3300. /* get their key */
  3301. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  3302. res = CRYPT_ERROR;
  3303. goto done2;
  3304. }
  3305. } else {
  3306. /* mode >0 so we send second */
  3307. if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
  3308. res = CRYPT_ERROR;
  3309. goto done2;
  3310. }
  3311. if (send(sock, buf, x, 0) != x) {
  3312. res = CRYPT_ERROR;
  3313. goto done2;
  3314. }
  3315. }
  3316. if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
  3317. res = err;
  3318. goto done2;
  3319. }
  3320. /* make shared secret */
  3321. x = sizeof(buf);
  3322. if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
  3323. res = err;
  3324. goto done;
  3325. }
  3326. /* hash it */
  3327. len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
  3328. if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
  3329. res = err;
  3330. goto done;
  3331. }
  3332. /* clean up and return */
  3333. res = CRYPT_OK;
  3334. done:
  3335. dh_free(&theirkey);
  3336. done2:
  3337. dh_free(&mykey);
  3338. zeromem(buf, sizeof(buf));
  3339. zeromem(buf2, sizeof(buf2));
  3340. return res;
  3341. }
  3342. \end{verbatim}
  3343. \end{small}
  3344. \newpage
  3345. \subsection{Remarks on The Snippet}
  3346. When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
  3347. passed to ``establish\_secure\_socket()''.
  3348. \section{Other Diffie-Hellman Functions}
  3349. In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
  3350. available:
  3351. \index{dh\_test()}
  3352. \begin{verbatim}
  3353. int dh_test(void);
  3354. \end{verbatim}
  3355. This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct. There is one last helper
  3356. function:
  3357. \index{dh\_sizes()}
  3358. \begin{verbatim}
  3359. void dh_sizes(int *low, int *high);
  3360. \end{verbatim}
  3361. Which stores the smallest and largest key sizes support into the two variables.
  3362. \section{DH Packet}
  3363. Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
  3364. algorithms.
  3365. \index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
  3366. \begin{verbatim}
  3367. int dh_encrypt_key(const unsigned char *in, unsigned long inlen,
  3368. unsigned char *out, unsigned long *len,
  3369. prng_state *prng, int wprng, int hash,
  3370. dh_key *key);
  3371. int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
  3372. unsigned char *out, unsigned long *outlen,
  3373. dh_key *key);
  3374. \end{verbatim}
  3375. Where ``in'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
  3376. and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
  3377. required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
  3378. as the symmetric key you are trying to share.
  3379. Similar to the RSA system you can sign and verify a hash of a message.
  3380. \index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
  3381. \begin{verbatim}
  3382. int dh_sign_hash(const unsigned char *in, unsigned long inlen,
  3383. unsigned char *out, unsigned long *outlen,
  3384. prng_state *prng, int wprng, dh_key *key);
  3385. int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
  3386. const unsigned char *hash, unsigned long hashlen,
  3387. int *stat, dh_key *key);
  3388. \end{verbatim}
  3389. The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.
  3390. The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''. It sets ``stat''
  3391. to non-zero if the signature passes or zero if it fails.
  3392. \chapter{Elliptic Curve Cryptography}
  3393. \mysection{Background}
  3394. The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
  3395. Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
  3396. to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
  3397. 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
  3398. 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
  3399. The curves in this library are taken from the following website:
  3400. \begin{verbatim}
  3401. http://csrc.nist.gov/cryptval/dss.htm
  3402. \end{verbatim}
  3403. As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves. These curves were added to
  3404. support smaller devices which do not need as large keys for security.
  3405. They are all curves over the integers modulo a prime. The curves have the basic equation that is:
  3406. \begin{equation}
  3407. y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
  3408. \end{equation}
  3409. The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
  3410. provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
  3411. range in order from $\approx 2^{112}$ points to $\approx 2^{521}$. According to the source document any key size greater
  3412. than or equal to 256-bits is sufficient for long term security.
  3413. \mysection{Fixed Point Optimizations}
  3414. \index{Fixed Point ECC}
  3415. \index{MECC\_FP}
  3416. As of v1.12 of LibTomCrypt, support for Fixed Point ECC point multiplication has been added. It is a generic optimization that is
  3417. supported by any conforming math plugin. It is enabled by defining \textbf{MECC\_FP} during the build, such as
  3418. \begin{verbatim}
  3419. CFLAGS="-DTFM_DESC -DMECC_FP" make
  3420. \end{verbatim}
  3421. which will build LTC using the TFM math library and enabling this new feature. The feature is not enabled by default as it is \textbf{NOT} thread
  3422. safe (by default). It supports the LTC locking macros (such as by enabling LTC\_PTHREAD), but by default is not locked.
  3423. \index{FP\_ENTRIES}
  3424. The optimization works by using a Fixed Point multiplier on any base point you use twice or more in a short period of time. It has a limited size
  3425. cache (of FP\_ENTRIES entries) which it uses to hold recent bases passed to ltc\_ecc\_mulmod(). Any base detected to be used twice is sent through the
  3426. pre--computation phase, and then the fixed point algorithm can be used. For example, if you use a NIST base point twice in a row, the 2$^{nd}$ and
  3427. all subsequent point multiplications with that point will use the faster algorithm.
  3428. \index{FP\_LUT}
  3429. The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the
  3430. value the faster the algorithm will be but the more memory it will take. The memory usage is $3 \cdot 2^{FP\_LUT}$ integers which by default
  3431. with TFM amounts to about 400kB of memory. Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount. Memory is only used by a cache entry
  3432. if it is active. Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,
  3433. \begin{verbatim}
  3434. CFLAGS="-DTFM_DESC -DMECC_FP -DFP_ENTRIES=8 -DFP_LUT=6" make
  3435. \end{verbatim}
  3436. \begin{flushleft}
  3437. \index{FP\_SIZE} \index{TFM} \index{tfm.h}
  3438. would define a window of 6 bits and limit the cache to 8 entries. Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h). It defaults
  3439. to 4096 bits (512 bytes) which is way more than what is required by ECC. At most, you need 1152 bits to accommodate ECC--521. If you're only using (say)
  3440. ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
  3441. \end{flushleft}
  3442. \mysection{Key Format}
  3443. LibTomCrypt uses a unique format for ECC public and private keys. While ANSI X9.63 partially specifies key formats, it does it in a less than ideally simple manner. \
  3444. In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves. The format of the keys is as follows:
  3445. \index{ECC Key Format}
  3446. \begin{small}
  3447. \begin{verbatim}
  3448. ECCPublicKey ::= SEQUENCE {
  3449. flags BIT STRING(0), -- public/private flag (always zero),
  3450. keySize INTEGER, -- Curve size (in bits) divided by eight
  3451. -- and rounded down, e.g. 521 => 65
  3452. pubkey.x INTEGER, -- The X co-ordinate of the public key point
  3453. pubkey.y INTEGER, -- The Y co-ordinate of the public key point
  3454. }
  3455. ECCPrivateKey ::= SEQUENCE {
  3456. flags BIT STRING(1), -- public/private flag (always one),
  3457. keySize INTEGER, -- Curve size (in bits) divided by eight
  3458. -- and rounded down, e.g. 521 => 65
  3459. pubkey.x INTEGER, -- The X co-ordinate of the public key point
  3460. pubkey.y INTEGER, -- The Y co-ordinate of the public key point
  3461. secret.k INTEGER, -- The secret key scalar
  3462. }
  3463. \end{verbatim}
  3464. \end{small}
  3465. The first flags bit denotes whether the key is public (zero) or private (one).
  3466. \vfil
  3467. \mysection{ECC Curve Parameters}
  3468. The library uses the following structure to describe an elliptic curve. This is used internally, as well as by the new
  3469. extended ECC functions which allow the user to specify their own curves.
  3470. \index{ltc\_ecc\_set\_type}
  3471. \begin{verbatim}
  3472. /** Structure defines a NIST GF(p) curve */
  3473. typedef struct {
  3474. /** The size of the curve in octets */
  3475. int size;
  3476. /** name of curve */
  3477. char *name;
  3478. /** The prime that defines the field (encoded in hex) */
  3479. char *prime;
  3480. /** The fields B param (hex) */
  3481. char *B;
  3482. /** The order of the curve (hex) */
  3483. char *order;
  3484. /** The x co-ordinate of the base point on the curve (hex) */
  3485. char *Gx;
  3486. /** The y co-ordinate of the base point on the curve (hex) */
  3487. char *Gy;
  3488. } ltc_ecc_set_type;
  3489. \end{verbatim}
  3490. The curve must be of the form $y^2 = x^3 - 3x + b$, and all of the integer parameters are encoded in hexadecimal format.
  3491. \mysection{Core Functions}
  3492. \subsection{ECC Key Generation}
  3493. There is a key structure called \textit{ecc\_key} used by the ECC functions. There is a function to make a key:
  3494. \index{ecc\_make\_key()}
  3495. \begin{verbatim}
  3496. int ecc_make_key(prng_state *prng,
  3497. int wprng,
  3498. int keysize,
  3499. ecc_key *key);
  3500. \end{verbatim}
  3501. The \textit{keysize} is the size of the modulus in bytes desired. Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
  3502. correspond to key sizes of 112, 128, 160, 192, 224, 256, 384, and 521 bits respectively. If you pass a key size that is between any key size it will round
  3503. the keysize up to the next available one.
  3504. The function will free any internally allocated resources if there is an error.
  3505. \subsection{Extended Key Generation}
  3506. As of v1.16, the library supports an extended key generation routine which allows the user to specify their own curve. It is specified as follows:
  3507. \index{ecc\_make\_key\_ex()}
  3508. \begin{verbatim}
  3509. int ecc_make_key_ex(
  3510. prng_state *prng,
  3511. int wprng,
  3512. ecc_key *key,
  3513. const ltc_ecc_set_type *dp);
  3514. \end{verbatim}
  3515. This function generates a random ECC key over the curve specified by the parameters by \textit{dp}. The rest of the parameters are equivalent to
  3516. those from the original key generation function.
  3517. \subsection{ECC Key Free}
  3518. To free the memory allocated by a ecc\_make\_key(), ecc\_make\_key\_ex(), ecc\_import(), or ecc\_import\_ex() call use the following function:
  3519. \index{ecc\_free()}
  3520. \begin{verbatim}
  3521. void ecc_free(ecc_key *key);
  3522. \end{verbatim}
  3523. \subsection{ECC Key Export}
  3524. To export an ECC key using the LibTomCrypt format call the following function:
  3525. \index{ecc\_export()}
  3526. \begin{verbatim}
  3527. int ecc_export(unsigned char *out,
  3528. unsigned long *outlen,
  3529. int type,
  3530. ecc_key *key);
  3531. \end{verbatim}
  3532. This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.
  3533. \subsection{ECC Key Import}
  3534. The following function imports a LibTomCrypt format ECC key:
  3535. \index{ecc\_import()}
  3536. \begin{verbatim}
  3537. int ecc_import(const unsigned char *in,
  3538. unsigned long inlen,
  3539. ecc_key *key);
  3540. \end{verbatim}
  3541. This will import the ECC key from \textit{in}, and store it in the ecc\_key structure pointed to by \textit{key}. If the operation fails it will free
  3542. any allocated memory automatically.
  3543. \subsection{Extended Key Import}
  3544. The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
  3545. \index{ecc\_import\_ex()}
  3546. \begin{verbatim}
  3547. int ecc_import_ex(const unsigned char *in,
  3548. unsigned long inlen,
  3549. ecc_key *key,
  3550. const ltc_ecc_set_type *dp);
  3551. \end{verbatim}
  3552. This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets. The key is stored in
  3553. the ECC structure pointed to by \textit{key}. The curve is specified by the parameters pointed to by \textit{dp}. The function will free
  3554. all internally allocated memory upon error.
  3555. \subsection{ANSI X9.63 Export}
  3556. The following function exports an ECC public key in the ANSI X9.63 format:
  3557. \index{ecc\_ansi\_x963\_export()}
  3558. \begin{verbatim}
  3559. int ecc_ansi_x963_export( ecc_key *key,
  3560. unsigned char *out,
  3561. unsigned long *outlen);
  3562. \end{verbatim}
  3563. The ECC key pointed to by \textit{key} is exported in public fashion to the array pointed to by \textit{out}. The ANSI X9.63 format used is from
  3564. section 4.3.6 of the standard. It does not allow for the export of private keys.
  3565. \subsection{ANSI X9.63 Import}
  3566. The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
  3567. \index{ecc\_ansi\_x963\_import()}
  3568. \begin{verbatim}
  3569. int ecc_ansi_x963_import(const unsigned char *in,
  3570. unsigned long inlen,
  3571. ecc_key *key);
  3572. \end{verbatim}
  3573. This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The imported key is stored in the ECC key pointed to by
  3574. \textit{key}. The function will free any allocated memory upon error.
  3575. \subsection{Extended ANSI X9.63 Import}
  3576. The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
  3577. \index{ecc\_ansi\_x963\_import\_ex()}
  3578. \begin{verbatim}
  3579. int ecc_ansi_x963_import_ex(const unsigned char *in,
  3580. unsigned long inlen,
  3581. ecc_key *key,
  3582. ltc_ecc_set_type *dp);
  3583. \end{verbatim}
  3584. This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.
  3585. The imported key is stored in the ECC key pointed to by \textit{key}. The function will free any allocated memory upon error.
  3586. \subsection{ECC Shared Secret}
  3587. To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
  3588. \index{ecc\_shared\_secret()}
  3589. \begin{verbatim}
  3590. int ecc_shared_secret( ecc_key *private_key,
  3591. ecc_key *public_key,
  3592. unsigned char *out,
  3593. unsigned long *outlen);
  3594. \end{verbatim}
  3595. The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.
  3596. Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.
  3597. \mysection{ECC Diffie-Hellman Encryption}
  3598. ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext. It is not strictly ANSI X9.63 compliant
  3599. but it is very similar. It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage. The following function
  3600. encrypts a short string (no longer than the message digest) using this technique:
  3601. \subsection{ECC-DH Encryption}
  3602. \index{ecc\_encrypt\_key()}
  3603. \begin{verbatim}
  3604. int ecc_encrypt_key(const unsigned char *in,
  3605. unsigned long inlen,
  3606. unsigned char *out,
  3607. unsigned long *outlen,
  3608. prng_state *prng,
  3609. int wprng,
  3610. int hash,
  3611. ecc_key *key);
  3612. \end{verbatim}
  3613. As the name implies this function encrypts a (symmetric) key, and is not intended for encrypting long messages directly. It will encrypt the
  3614. plaintext in the array pointed to by \textit{in} of length \textit{inlen} octets. It uses the public ECC key pointed to by \textit{key}, and
  3615. hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext. The ciphertext is stored in
  3616. the output buffer pointed to by \textit{out} of length \textit{outlen} octets.
  3617. The data is encrypted to the public ECC \textit{key} such that only the holder of the private key can decrypt the payload. To have multiple
  3618. recipients multiple call to this function for each public ECC key is required.
  3619. \subsection{ECC-DH Decryption}
  3620. \index{ecc\_decrypt\_key()}
  3621. \begin{verbatim}
  3622. int ecc_decrypt_key(const unsigned char *in,
  3623. unsigned long inlen,
  3624. unsigned char *out,
  3625. unsigned long *outlen,
  3626. ecc_key *key);
  3627. \end{verbatim}
  3628. This function will decrypt an encrypted payload. The \textit{key} provided must be the private key corresponding to the public key
  3629. used during encryption. If the wrong key is provided the function will not specifically return an error code. It is important
  3630. to use some form of challenge response in that case (e.g. compute a MAC of a known string).
  3631. \subsection{ECC Encryption Format}
  3632. The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
  3633. \begin{verbatim}
  3634. ECCEncrypt ::= SEQUENCE {
  3635. hashID OBJECT IDENTIFIER, -- OID of hash used
  3636. pubkey OCTET STRING , -- Encapsulated ECCPublicKey
  3637. skey OCTET STRING -- xor of plaintext and
  3638. --"hash of shared secret"
  3639. }
  3640. \end{verbatim}
  3641. \mysection{EC DSA Signatures}
  3642. There are also functions to sign and verify messages. They use the ANSI X9.62 EC-DSA algorithm to generate and verify signatures in the
  3643. ANSI X9.62 format.
  3644. \subsection{EC-DSA Signature Generation}
  3645. To sign a message digest (hash) use the following function:
  3646. \index{ecc\_sign\_hash()}
  3647. \begin{verbatim}
  3648. int ecc_sign_hash(const unsigned char *in,
  3649. unsigned long inlen,
  3650. unsigned char *out,
  3651. unsigned long *outlen,
  3652. prng_state *prng,
  3653. int wprng,
  3654. ecc_key *key);
  3655. \end{verbatim}
  3656. This function will EC--DSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The signature
  3657. will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets. The function requires a properly seeded PRNG, and
  3658. the ECC \textit{key} provided must be a private key.
  3659. \subsection{EC-DSA Signature Verification}
  3660. \index{ecc\_verify\_hash()}
  3661. \begin{verbatim}
  3662. int ecc_verify_hash(const unsigned char *sig,
  3663. unsigned long siglen,
  3664. const unsigned char *hash,
  3665. unsigned long hashlen,
  3666. int *stat,
  3667. ecc_key *key);
  3668. \end{verbatim}
  3669. This function will verify the EC-DSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest
  3670. pointed to by the array \textit{hash} of length \textit{hashlen}. It will store a non--zero value in \textit{stat} if the signature is valid. Note:
  3671. the function will not return an error if the signature is invalid. It will return an error, if the actual signature payload is an invalid format.
  3672. The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
  3673. \subsection{Signature Format}
  3674. The signature code is an implementation of X9.62 EC--DSA, and the output is compliant for GF(p) curves.
  3675. \mysection{ECC Keysizes}
  3676. With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems. The math will still work, and in effect the signature will still
  3677. work. With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller. For example, if you sign with
  3678. SHA256 and an ECC-192 key, you in effect have 96--bits of security.
  3679. The library will not warn you if you make this mistake, so it is important to check yourself before using the signatures.
  3680. \chapter{Digital Signature Algorithm}
  3681. \mysection{Introduction}
  3682. The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
  3683. reduce the bandwidth of the signatures. For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.
  3684. With DSA, you need a group of order at least 160--bits. By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature
  3685. would require only at least 40 bytes.
  3686. \mysection{Key Format}
  3687. Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
  3688. now so that others can interoperate with this library.
  3689. \begin{verbatim}
  3690. DSAPublicKey ::= SEQUENCE {
  3691. publicFlags BIT STRING(0), -- must be 0
  3692. g INTEGER , -- base generator
  3693. -- check that g^q mod p == 1
  3694. -- and that 1 < g < p - 1
  3695. p INTEGER , -- prime modulus
  3696. q INTEGER , -- order of sub-group
  3697. -- (must be prime)
  3698. y INTEGER , -- public key, specifically,
  3699. -- g^x mod p,
  3700. -- check that y^q mod p == 1
  3701. -- and that 1 < y < p - 1
  3702. }
  3703. DSAPrivateKey ::= SEQUENCE {
  3704. publicFlags BIT STRING(1), -- must be 1
  3705. g INTEGER , -- base generator
  3706. -- check that g^q mod p == 1
  3707. -- and that 1 < g < p - 1
  3708. p INTEGER , -- prime modulus
  3709. q INTEGER , -- order of sub-group
  3710. -- (must be prime)
  3711. y INTEGER , -- public key, specifically,
  3712. -- g^x mod p,
  3713. -- check that y^q mod p == 1
  3714. -- and that 1 < y < p - 1
  3715. x INTEGER -- private key
  3716. }
  3717. \end{verbatim}
  3718. The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys. This makes the structure uniquely decodable,
  3719. and easy to work with.
  3720. \mysection{Key Generation}
  3721. To make a DSA key you must call the following function
  3722. \begin{verbatim}
  3723. int dsa_make_key(prng_state *prng,
  3724. int wprng,
  3725. int group_size,
  3726. int modulus_size,
  3727. dsa_key *key);
  3728. \end{verbatim}
  3729. The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor. \textit{group\_size} and
  3730. \textit{modulus\_size} control the difficulty of forging a signature. Both parameters are in bytes. The larger the
  3731. \textit{group\_size} the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
  3732. $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
  3733. \begin{figure}[h]
  3734. \begin{center}
  3735. \begin{tabular}{|c|c|c|}
  3736. \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
  3737. \hline 80 & 20 & 128 \\
  3738. \hline 120 & 30 & 256 \\
  3739. \hline 140 & 35 & 384 \\
  3740. \hline 160 & 40 & 512 \\
  3741. \hline
  3742. \end{tabular}
  3743. \end{center}
  3744. \caption{DSA Key Sizes}
  3745. \end{figure}
  3746. When you are finished with a DSA key you can call the following function to free the memory used.
  3747. \index{dsa\_free()}
  3748. \begin{verbatim}
  3749. void dsa_free(dsa_key *key);
  3750. \end{verbatim}
  3751. \mysection{Key Verification}
  3752. Each DSA key is composed of the following variables.
  3753. \begin{enumerate}
  3754. \item $q$ a small prime of magnitude $256^{group\_size}$.
  3755. \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
  3756. \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
  3757. value. For this library they start at $h = 2$ and step until $g$ is not $1$.
  3758. \item $x$ a random secret (the secret key) in the range $1 < x < q$
  3759. \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
  3760. \end{enumerate}
  3761. A DSA key is considered valid if it passes all of the following tests.
  3762. \begin{enumerate}
  3763. \item $q$ must be prime.
  3764. \item $p$ must be prime.
  3765. \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
  3766. \item $g$ must be less than $p$.
  3767. \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
  3768. \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  3769. \item $1 < y < p - 1$
  3770. \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
  3771. \end{enumerate}
  3772. Tests one and two ensure that the values will at least form a field which is required for the signatures to
  3773. function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
  3774. forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
  3775. ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
  3776. is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
  3777. that $y$ belongs to a multiplicative sub-group of order $q$.
  3778. The following function will perform these tests.
  3779. \index{dsa\_verify\_key()}
  3780. \begin{verbatim}
  3781. int dsa_verify_key(dsa_key *key, int *stat);
  3782. \end{verbatim}
  3783. This will test \textit{key} and store the result in \textit{stat}. If the result is $stat = 0$ the DSA key failed one of the tests
  3784. 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).
  3785. \mysection{Signatures}
  3786. \subsection{Signature Generation}
  3787. To generate a DSA signature call the following function:
  3788. \index{dsa\_sign\_hash()}
  3789. \begin{verbatim}
  3790. int dsa_sign_hash(const unsigned char *in,
  3791. unsigned long inlen,
  3792. unsigned char *out,
  3793. unsigned long *outlen,
  3794. prng_state *prng,
  3795. int wprng,
  3796. dsa_key *key);
  3797. \end{verbatim}
  3798. Which will sign the data in \textit{in} of length \textit{inlen} bytes. The signature is stored in \textit{out} and the size
  3799. of the signature in \textit{outlen}. If the signature is longer than the size you initially specify in \textit{outlen} nothing
  3800. is stored and the function returns an error code. The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.
  3801. \subsection{Signature Verification}
  3802. To verify a hash created with that function use the following function:
  3803. \index{dsa\_verify\_hash()}
  3804. \begin{verbatim}
  3805. int dsa_verify_hash(const unsigned char *sig,
  3806. unsigned long siglen,
  3807. const unsigned char *hash,
  3808. unsigned long inlen,
  3809. int *stat,
  3810. dsa_key *key);
  3811. \end{verbatim}
  3812. Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.
  3813. It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.
  3814. \mysection{DSA Encrypt and Decrypt}
  3815. As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads. It works similar to the ECC encryption where
  3816. a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext. The format used is functional port of
  3817. the ECC encryption format to the DSA algorithm.
  3818. \subsection{DSA Encryption}
  3819. This function will encrypt a small payload with a recipients public DSA key.
  3820. \index{dsa\_encrypt\_key()}
  3821. \begin{verbatim}
  3822. int dsa_encrypt_key(const unsigned char *in,
  3823. unsigned long inlen,
  3824. unsigned char *out,
  3825. unsigned long *outlen,
  3826. prng_state *prng,
  3827. int wprng,
  3828. int hash,
  3829. dsa_key *key);
  3830. \end{verbatim}
  3831. This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}. The
  3832. length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer. The DSA \textit{key} can be
  3833. a public key.
  3834. \subsection{DSA Decryption}
  3835. \index{dsa\_decrypt\_key()}
  3836. \begin{verbatim}
  3837. int dsa_decrypt_key(const unsigned char *in,
  3838. unsigned long inlen,
  3839. unsigned char *out,
  3840. unsigned long *outlen,
  3841. dsa_key *key);
  3842. \end{verbatim}
  3843. This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
  3844. The DSA \textit{key} must be a private key.
  3845. \mysection{DSA Key Import and Export}
  3846. \subsection{DSA Key Export}
  3847. To export a DSA key so that it can be transported use the following function:
  3848. \index{dsa\_export()}
  3849. \begin{verbatim}
  3850. int dsa_export(unsigned char *out,
  3851. unsigned long *outlen,
  3852. int type,
  3853. dsa_key *key);
  3854. \end{verbatim}
  3855. This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
  3856. initialized to the maximum buffer size). The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
  3857. depending on whether you want to export a private or public copy of the DSA key.
  3858. \subsection{DSA Key Import}
  3859. To import an exported DSA key use the following function
  3860. :
  3861. \index{dsa\_import()}
  3862. \begin{verbatim}
  3863. int dsa_import(const unsigned char *in,
  3864. unsigned long inlen,
  3865. dsa_key *key);
  3866. \end{verbatim}
  3867. This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}. If the process fails the function
  3868. will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
  3869. \chapter{Standards Support}
  3870. \mysection{ASN.1 Formats}
  3871. LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
  3872. are all provided with three basic functions with \textit{similar} prototypes. One function has been dedicated to calculate the length in octets of a given
  3873. format, and two functions have been dedicated to encoding and decoding the format.
  3874. On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types. They are provided
  3875. in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure. It is defined as the following:
  3876. \index{ltc\_asn1\_list structure}
  3877. \begin{verbatim}
  3878. typedef struct {
  3879. int type;
  3880. void *data;
  3881. unsigned long size;
  3882. int used;
  3883. struct ltc_asn1_list_ *prev, *next,
  3884. *child, *parent;
  3885. } ltc_asn1_list;
  3886. \end{verbatim}
  3887. \index{LTC\_SET\_ASN1 macro}
  3888. The \textit{type} field is one of the following ASN.1 field definitions. The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the
  3889. \textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type). The \textit{used} field is primarily for the CHOICE decoder
  3890. and reflects if the particular member of a list was the decoded data type. To help build the lists in an orderly fashion the macro
  3891. \textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.
  3892. It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size). An example usage would be:
  3893. \begin{small}
  3894. \begin{verbatim}
  3895. ...
  3896. ltc_asn1_list sequence[3];
  3897. unsigned long three=3;
  3898. LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING, "hello", 5);
  3899. LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three, 1);
  3900. LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL, NULL, 0);
  3901. \end{verbatim}
  3902. \end{small}
  3903. The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
  3904. \begin{small}
  3905. \begin{verbatim}
  3906. ...
  3907. ltc_asn1_list sequence[3];
  3908. unsigned long three=3;
  3909. int x=0;
  3910. LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING, "hello", 5);
  3911. LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three, 1);
  3912. LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL, NULL, 0);
  3913. \end{verbatim}
  3914. \end{small}
  3915. \begin{figure}[h]
  3916. \begin{center}
  3917. \begin{small}
  3918. \begin{tabular}{|l|l|}
  3919. \hline \textbf{Definition} & \textbf{ASN.1 Type} \\
  3920. \hline LTC\_ASN1\_EOL & End of a ASN.1 list structure. \\
  3921. \hline LTC\_ASN1\_BOOLEAN & BOOLEAN type \\
  3922. \hline LTC\_ASN1\_INTEGER & INTEGER (uses mp\_int) \\
  3923. \hline LTC\_ASN1\_SHORT\_INTEGER & INTEGER (32--bit using unsigned long) \\
  3924. \hline LTC\_ASN1\_BIT\_STRING & BIT STRING (one bit per char) \\
  3925. \hline LTC\_ASN1\_OCTET\_STRING & OCTET STRING (one octet per char) \\
  3926. \hline LTC\_ASN1\_NULL & NULL \\
  3927. \hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER \\
  3928. \hline LTC\_ASN1\_IA5\_STRING & IA5 STRING (one octet per char) \\
  3929. \hline LTC\_ASN1\_PRINTABLE\_STRING & PRINTABLE STRING (one octet per char) \\
  3930. \hline LTC\_ASN1\_UTF8\_STRING & UTF8 STRING (one wchar\_t per char) \\
  3931. \hline LTC\_ASN1\_UTCTIME & UTCTIME (see ltc\_utctime structure) \\
  3932. \hline LTC\_ASN1\_CHOICE & CHOICE \\
  3933. \hline LTC\_ASN1\_SEQUENCE & SEQUENCE (and SEQUENCE OF) \\
  3934. \hline LTC\_ASN1\_SET & SET \\
  3935. \hline LTC\_ASN1\_SETOF & SET OF \\
  3936. \hline LTC\_ASN1\_RAW\_BIT\_STRING & BIT STRING (one octet per char) \\
  3937. \hline LTC\_ASN1\_TELETEX\_STRING & TELETEX STRING (one octet per char) \\
  3938. \hline LTC\_ASN1\_CONSTRUCTED & A constructed type that is not SEQUENCE or SET \\
  3939. \hline LTC\_ASN1\_CONTEXT\_SPECIFIC & A context-specific type \\
  3940. \hline LTC\_ASN1\_GENERALIZEDTIME & GeneralizedTime (see ltc\_generalizedtime structure) \\
  3941. \hline
  3942. \end{tabular}
  3943. \caption{List of ASN.1 Supported Types}
  3944. \end{small}
  3945. \end{center}
  3946. \end{figure}
  3947. \subsection{SEQUENCE Type}
  3948. The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
  3949. \subsubsection{SEQUENCE Encoding}
  3950. To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
  3951. with the following function.
  3952. \index{der\_encode\_sequence()}\index{LTC\_ASN1\_EOL}
  3953. \begin{verbatim}
  3954. int der_encode_sequence(ltc_asn1_list *list,
  3955. unsigned long inlen,
  3956. unsigned char *out,
  3957. unsigned long *outlen);
  3958. \end{verbatim}
  3959. This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it. The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}. The
  3960. function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
  3961. The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
  3962. verbatim to the dependent encoder. The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions. In these cases
  3963. the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
  3964. \subsubsection{SEQUENCE Decoding}
  3965. \index{der\_decode\_sequence()}
  3966. Decoding a SEQUENCE is similar to encoding. You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size
  3967. (in certain cases). For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
  3968. units of the respective type has been loaded.
  3969. \begin{verbatim}
  3970. int der_decode_sequence(const unsigned char *in,
  3971. unsigned long inlen,
  3972. ltc_asn1_list *list,
  3973. unsigned long outlen);
  3974. \end{verbatim}
  3975. This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets. The function will stop (gracefully) when it runs out of items to decode.
  3976. It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occurred.
  3977. For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
  3978. \begin{enumerate}
  3979. \item BIT STRING
  3980. \item OCTET STRING
  3981. \item OBJECT IDENTIFIER
  3982. \item IA5 STRING
  3983. \item PRINTABLE STRING
  3984. \end{enumerate}
  3985. \subsubsection{SEQUENCE Length}
  3986. The length of a SEQUENCE can be determined with the following function.
  3987. \index{der\_length\_sequence()}
  3988. \begin{verbatim}
  3989. int der_length_sequence(ltc_asn1_list *list,
  3990. unsigned long inlen,
  3991. unsigned long *outlen);
  3992. \end{verbatim}
  3993. This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.
  3994. \subsubsection{SEQUENCE Multiple Argument Lists}\index{LTC\_ASN1\_EOL}
  3995. For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
  3996. \index{der\_encode\_sequence\_multi()}
  3997. \index{der\_decode\_sequence\_multi()}
  3998. \begin{verbatim}
  3999. int der_encode_sequence_multi(unsigned char *out,
  4000. unsigned long *outlen, ...);
  4001. int der_decode_sequence_multi(const unsigned char *in,
  4002. unsigned long inlen, ...);
  4003. \end{verbatim}
  4004. These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
  4005. The list of items are specified as a triple of the form \textit{(type, size, data)} where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
  4006. and \textit{data} is \textbf{void} pointer. The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
  4007. It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function. Constants such as \textit{1} without
  4008. a cast or prototype are of type \textbf{int} by default. Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.
  4009. \begin{small}
  4010. \begin{verbatim}
  4011. unsigned char buf[MAXBUFSIZE];
  4012. unsigned long buflen;
  4013. int err;
  4014. buflen = sizeof(buf);
  4015. if ((err =
  4016. der_encode_sequence_multi(buf, &buflen,
  4017. LTC_ASN1_IA5_STRING, 5UL, "Hello",
  4018. LTC_ASN1_IA5_STRING, 7UL, " World!",
  4019. LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
  4020. // error handling
  4021. }
  4022. \end{verbatim}
  4023. \end{small}
  4024. This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively. Note the usage of the \textbf{UL} modifier
  4025. on the size parameters. This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
  4026. \subsection{SET and SET OF}
  4027. \index{SET} \index{SET OF}
  4028. SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code. However, they are different, and they should
  4029. be carefully noted. The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of
  4030. a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.
  4031. \subsubsection{SET Encoding}
  4032. SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use. They are encoded with the following function:
  4033. \index{der\_encode\_set()}
  4034. \begin{verbatim}
  4035. int der_encode_set(ltc_asn1_list *list,
  4036. unsigned long inlen,
  4037. unsigned char *out,
  4038. unsigned long *outlen);
  4039. \end{verbatim}
  4040. This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.
  4041. The function will make a copy of the list provided, and sort it by the TAG. Objects with identical TAGs are additionally sorted on their original placement in the
  4042. array (to make the process deterministic).
  4043. This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
  4044. \subsubsection{SET Decoding}
  4045. The SET type can be decoded with the following function.
  4046. \index{der\_decode\_set()}
  4047. \begin{verbatim}
  4048. int der_decode_set(const unsigned char *in,
  4049. unsigned long inlen,
  4050. ltc_asn1_list *list,
  4051. unsigned long outlen);
  4052. \end{verbatim}
  4053. This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.
  4054. It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.
  4055. \subsubsection{SET Length}
  4056. The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.
  4057. \subsubsection{SET OF Encoding}
  4058. A \textit{SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object. They are
  4059. used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
  4060. use. They are encoded with the following function.
  4061. \index{der\_encode\_setof()}
  4062. \begin{verbatim}
  4063. int der_encode_setof(ltc_asn1_list *list,
  4064. unsigned long inlen,
  4065. unsigned char *out,
  4066. unsigned long *outlen);
  4067. \end{verbatim}
  4068. This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.
  4069. The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer. This
  4070. means you need at least enough memory to keep an additional copy of the output on the heap.
  4071. \subsubsection{SET OF Decoding}
  4072. Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().
  4073. \subsubsection{SET OF Length}
  4074. Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.
  4075. \subsection{ASN.1 INTEGER}
  4076. To encode or decode INTEGER data types use the following functions.
  4077. \index{der\_encode\_integer()}\index{der\_decode\_integer()}\index{der\_length\_integer()}
  4078. \begin{verbatim}
  4079. int der_encode_integer( void *num,
  4080. unsigned char *out,
  4081. unsigned long *outlen);
  4082. int der_decode_integer(const unsigned char *in,
  4083. unsigned long inlen,
  4084. void *num);
  4085. int der_length_integer( void *num,
  4086. unsigned long *len);
  4087. \end{verbatim}
  4088. These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER. To encode smaller values without allocating
  4089. a bignum to store the value, the \textit{short} INTEGER functions were made available.
  4090. \index{der\_encode\_short\_integer()}\index{der\_decode\_short\_integer()}\index{der\_length\_short\_integer()}
  4091. \begin{verbatim}
  4092. int der_encode_short_integer(unsigned long num,
  4093. unsigned char *out,
  4094. unsigned long *outlen);
  4095. int der_decode_short_integer(const unsigned char *in,
  4096. unsigned long inlen,
  4097. unsigned long *num);
  4098. int der_length_short_integer(unsigned long num,
  4099. unsigned long *outlen);
  4100. \end{verbatim}
  4101. These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits). For values in the range $0 \dots 2^{32} - 1$ the integer
  4102. and short integer functions can encode and decode each others outputs.
  4103. \subsection{ASN.1 BIT STRING}
  4104. \index{der\_encode\_bit\_string()}\index{der\_decode\_bit\_string()}\index{der\_length\_bit\_string()}
  4105. \begin{verbatim}
  4106. int der_encode_bit_string(const unsigned char *in,
  4107. unsigned long inlen,
  4108. unsigned char *out,
  4109. unsigned long *outlen);
  4110. int der_decode_bit_string(const unsigned char *in,
  4111. unsigned long inlen,
  4112. unsigned char *out,
  4113. unsigned long *outlen);
  4114. int der_length_bit_string(unsigned long nbits,
  4115. unsigned long *outlen);
  4116. \end{verbatim}
  4117. These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf{char} per bit. A non--zero value will be interpreted
  4118. as a one bit, and a zero value a zero bit.
  4119. \subsection{ASN.1 RAW BIT STRING}
  4120. \index{der\_encode\_raw\_bit\_string()}\index{der\_decode\_raw\_bit\_string()}
  4121. \begin{verbatim}
  4122. int der_encode_raw_bit_string(const unsigned char *in,
  4123. unsigned long inlen,
  4124. unsigned char *out,
  4125. unsigned long *outlen);
  4126. int der_decode_raw_bit_string(const unsigned char *in,
  4127. unsigned long inlen,
  4128. unsigned char *out,
  4129. unsigned long *outlen);
  4130. \end{verbatim}
  4131. These will encode or decode a BIT STRING data type.
  4132. The bits are passed in (or read out) using one \textbf{unsigned char} per 8 bit.
  4133. This function differs from the normal BIT STRING, as it can be used to directly
  4134. process raw binary data and store it to resp. read it from an ASN.1 BIT STRING
  4135. data type.
  4136. The length function is the same as for the normal BIT STRING \textit{der\_length\_bit\_string()}.
  4137. \subsection{ASN.1 OCTET STRING}
  4138. \index{der\_encode\_octet\_string()}\index{der\_decode\_octet\_string()}\index{der\_length\_octet\_string()}
  4139. \begin{verbatim}
  4140. int der_encode_octet_string(const unsigned char *in,
  4141. unsigned long inlen,
  4142. unsigned char *out,
  4143. unsigned long *outlen);
  4144. int der_decode_octet_string(const unsigned char *in,
  4145. unsigned long inlen,
  4146. unsigned char *out,
  4147. unsigned long *outlen);
  4148. int der_length_octet_string(unsigned long noctets,
  4149. unsigned long *outlen);
  4150. \end{verbatim}
  4151. These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf{unsigned char} each.
  4152. \subsection{ASN.1 OBJECT IDENTIFIER}
  4153. \index{der\_encode\_object\_identifier()}\index{der\_decode\_object\_identifier()}\index{der\_length\_object\_identifier()}
  4154. \begin{verbatim}
  4155. int der_encode_object_identifier(unsigned long *words,
  4156. unsigned long nwords,
  4157. unsigned char *out,
  4158. unsigned long *outlen);
  4159. int der_decode_object_identifier(const unsigned char *in,
  4160. unsigned long inlen,
  4161. unsigned long *words,
  4162. unsigned long *outlen);
  4163. int der_length_object_identifier(unsigned long *words,
  4164. unsigned long nwords,
  4165. unsigned long *outlen);
  4166. \end{verbatim}
  4167. These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
  4168. $0 \ldots 2^{32} - 1$.
  4169. \subsection{ASN.1 IA5 STRING}
  4170. \index{der\_encode\_ia5\_string()}\index{der\_decode\_ia5\_string()}\index{der\_length\_ia5\_string()}
  4171. \begin{verbatim}
  4172. int der_encode_ia5_string(const unsigned char *in,
  4173. unsigned long inlen,
  4174. unsigned char *out,
  4175. unsigned long *outlen);
  4176. int der_decode_ia5_string(const unsigned char *in,
  4177. unsigned long inlen,
  4178. unsigned char *out,
  4179. unsigned long *outlen);
  4180. int der_length_ia5_string(const unsigned char *octets,
  4181. unsigned long noctets,
  4182. unsigned long *outlen);
  4183. \end{verbatim}
  4184. These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
  4185. to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
  4186. say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
  4187. that the build platform honours the run--time platforms character conventions.
  4188. \subsection{ASN.1 TELETEX STRING}
  4189. \index{der\_decode\_teletex\_string()}\index{der\_length\_teletex\_string()}
  4190. \begin{verbatim}
  4191. int der_decode_teletex_string(const unsigned char *in,
  4192. unsigned long inlen,
  4193. unsigned char *out,
  4194. unsigned long *outlen);
  4195. int der_length_teletex_string(const unsigned char *octets,
  4196. unsigned long noctets,
  4197. unsigned long *outlen);
  4198. \end{verbatim}
  4199. These will decode a TELETEX STRING.
  4200. The characters are read in individual \textbf{char} elements.
  4201. The internal structure is similar to that of the IA5 STRING implementation, to
  4202. be able to provide a stable conversion independent of the build-- and run--time
  4203. platform.
  4204. \subsection{ASN.1 PRINTABLE STRING}
  4205. \index{der\_encode\_printable\_string()}\index{der\_decode\_printable\_string()}\index{der\_length\_printable\_string()}
  4206. \begin{verbatim}
  4207. int der_encode_printable_string(const unsigned char *in,
  4208. unsigned long inlen,
  4209. unsigned char *out,
  4210. unsigned long *outlen);
  4211. int der_decode_printable_string(const unsigned char *in,
  4212. unsigned long inlen,
  4213. unsigned char *out,
  4214. unsigned long *outlen);
  4215. int der_length_printable_string(const unsigned char *octets,
  4216. unsigned long noctets,
  4217. unsigned long *outlen);
  4218. \end{verbatim}
  4219. These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
  4220. to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
  4221. say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
  4222. that the build platform honours the run-time platforms character conventions.
  4223. \subsection{ASN.1 UTF8 STRING}
  4224. \index{der\_encode\_utf8\_string()}\index{der\_decode\_utf8\_string()}\index{der\_length\_utf8\_string()}
  4225. \begin{verbatim}
  4226. int der_encode_utf8_string(const wchar_t *in,
  4227. unsigned long inlen,
  4228. unsigned char *out,
  4229. unsigned long *outlen);
  4230. int der_decode_utf8_string(const unsigned char *in,
  4231. unsigned long inlen,
  4232. wchar_t *out,
  4233. unsigned long *outlen);
  4234. int der_length_utf8_string(const wchar_t *octets,
  4235. unsigned long noctets,
  4236. unsigned long *outlen);
  4237. \end{verbatim}
  4238. These will encode or decode an UTF8 STRING. The characters are read or stored in individual \textbf{wchar\_t} elements. These function performs no internal
  4239. mapping and treat the characters as literals.
  4240. These functions use the \textbf{wchar\_t} type which is not universally available. In those cases, the library will typedef it to \textbf{unsigned long}. If you
  4241. intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.
  4242. \subsection{ASN.1 UTCTIME}
  4243. The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
  4244. \index{ltc\_utctime structure}
  4245. \begin{verbatim}
  4246. typedef struct {
  4247. unsigned YY, /* year 00--99 */
  4248. MM, /* month 01--12 */
  4249. DD, /* day 01--31 */
  4250. hh, /* hour 00--23 */
  4251. mm, /* minute 00--59 */
  4252. ss, /* second 00--59 */
  4253. off_dir, /* timezone offset direction 0 == +, 1 == - */
  4254. off_hh, /* timezone offset hours */
  4255. off_mm; /* timezone offset minutes */
  4256. } ltc_utctime;
  4257. \end{verbatim}
  4258. The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
  4259. will be subtracted. For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of
  4260. \textit{2005, June 20th, 22:04:00} with a time offset of +05h00.
  4261. \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
  4262. \begin{verbatim}
  4263. int der_encode_utctime( ltc_utctime *utctime,
  4264. unsigned char *out,
  4265. unsigned long *outlen);
  4266. int der_decode_utctime(const unsigned char *in,
  4267. unsigned long *inlen,
  4268. ltc_utctime *out);
  4269. int der_length_utctime( ltc_utctime *utctime,
  4270. unsigned long *outlen);
  4271. \end{verbatim}
  4272. The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the
  4273. input. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
  4274. It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
  4275. \subsection{ASN.1 GeneralizedTime}
  4276. The GeneralizedTime type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
  4277. \index{ltc\_utctime structure}
  4278. \begin{verbatim}
  4279. typedef struct {
  4280. unsigned YYYY, /* year 0--9999 */
  4281. MM, /* month 1--12 */
  4282. DD, /* day 1--31 */
  4283. hh, /* hour 0--23 */
  4284. mm, /* minute 0--59 */
  4285. ss, /* second 0--59 */
  4286. fs, /* fractional seconds 1--UINT_MAX */
  4287. off_dir, /* timezone offset direction 0 == +, 1 == - */
  4288. off_hh, /* timezone offset hours */
  4289. off_mm; /* timezone offset minutes */
  4290. } ltc_generalizedtime;
  4291. \end{verbatim}
  4292. The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
  4293. will be subtracted. For instance, the array $\lbrace 2005, 6, 20, 22, 4, 0, 122, 0, 5, 0 \rbrace$ represents the current time of
  4294. \textit{2005, June 20th, 22:04:00.122} with a time offset of +05h00.
  4295. \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
  4296. \begin{verbatim}
  4297. int der_encode_generalizedtime(ltc_generalizedtime *gtime,
  4298. unsigned char *out,
  4299. unsigned long *outlen);
  4300. int der_decode_generalizedtime(const unsigned char *in,
  4301. unsigned long *inlen,
  4302. ltc_generalizedtime *out);
  4303. int der_length_generalizedtime(ltc_generalizedtime *gtime,
  4304. unsigned long *outlen);
  4305. \end{verbatim}
  4306. The encoder will store time in one of the following ASN.1 formats, either \textit{YYYYMMDDhhmmssZ} or
  4307. \textit{YYYYMMDDhhmmss$\pm$hhmm} or\textit{YYYYMMDDhhmmss.fsZ} or \textit{YYYYMMDDhhmmss.fs$\pm$hhmm},
  4308. and perform minimal error checking on the input.
  4309. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but
  4310. rational) useful for catching packet errors.
  4311. The fractional seconds are always added in case they are not $0$.
  4312. The implementation of fractional seconds is currently unreliable and you can't detect decoded
  4313. resp. encode leading $0$'s (e.g. \textit{20170424232717.005Z} would be decoded as
  4314. \textit{22. April 2017, 23:27:17.5}).
  4315. It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
  4316. \subsection{ASN.1 CHOICE}
  4317. The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}. There is no encoder for the CHOICE type, only a
  4318. decoder. The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet. The list can contain any ASN.1 data
  4319. type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.
  4320. There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
  4321. \index{der\_decode\_choice()}
  4322. \begin{verbatim}
  4323. int der_decode_choice(const unsigned char *in,
  4324. unsigned long *inlen,
  4325. ltc_asn1_list *list,
  4326. unsigned long outlen);
  4327. \end{verbatim}
  4328. This will decode the input in the \textit{in} field of length \textit{inlen}. It uses the provided ASN.1 list specified in the \textit{list} field which has
  4329. \textit{outlen} elements. The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field
  4330. will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
  4331. \subsection{ASN.1 Flexi Decoder}
  4332. The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
  4333. the structure of the data. Where der\_decode\_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
  4334. free form.
  4335. The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent}
  4336. and \textit{child}. The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
  4337. encoded in a SEQUENCE are stored as a child element.
  4338. When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the child
  4339. pointer points to a new list of items contained within the object.
  4340. \index{der\_decode\_sequence\_flexi()}
  4341. \index{LTC\_ASN1\_CONSTRUCTED}
  4342. \index{LTC\_ASN1\_CONTEXT\_SPECIFIC}
  4343. \begin{verbatim}
  4344. int der_decode_sequence_flexi(const unsigned char *in,
  4345. unsigned long *inlen,
  4346. ltc_asn1_list **out);
  4347. \end{verbatim}
  4348. This will decode items in the \textit{in} buffer of max input length \textit{inlen} and store the newly created pointer to the list in \textit{out}. This function allocates
  4349. all required memory for the decoding. It stores the number of octets read back into \textit{inlen}.
  4350. The function will terminate when either it hits an invalid ASN.1 tag, or it reads \textit{inlen} octets. An early termination is a soft error, and returns
  4351. normally. The decoded list \textit{out} will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf{NULL}).
  4352. An invalid decoding will terminate the process, and free the allocated memory automatically.
  4353. The flexi decoder calls itself when decoding a constructed type. This leads to
  4354. a 'child process' that will terminate when it decodes an unkown/invalid
  4355. identifier and leaves an allocated but uninitialized child element.
  4356. However the parent processing will continue with a "soft-error".
  4357. This can be detected by checking for \textit{child} elements with
  4358. type \textbf{LTC\_ASN1\_EOL} after decoding.
  4359. As of v1.18 the flexi decoder will also decode arbitrary constructed types
  4360. other than SEQUENCE and SET. The \textit{type} field will be set to
  4361. \textbf{LTC\_ASN1\_CONSTRUCTED} and the plain identifier that was indicated in the ASN.1
  4362. encoding is stored in the \textit{used} field. Further decoding is done in the
  4363. same way as if it were a SEQUENCE or SET.
  4364. Also as of v1.18 the flexi decoder is capable to handle
  4365. \textit{context-specific} encodings. The \textit{type} field will be set to
  4366. \textbf{LTC\_ASN1\_CONTEXT\_SPECIFIC} and the plain identifier that was indicated
  4367. in the ASN.1 encoding is stored in the \textit{used} field. Encapsulated data
  4368. in the \textit{context-specific} encoding is copied to newly allocated memory
  4369. and is accessible through the \textit{data} field.
  4370. \textbf{Note:} the list decoded by this function is \textbf{NOT} in the correct form for der\_encode\_sequence() to use directly. You will first
  4371. have to convert the list by first storing all of the siblings in an array then storing all the children as sub-lists of a sequence using the \textit{.data}
  4372. pointer. Currently no function in LibTomCrypt provides this ability.
  4373. \subsubsection{Sample Decoding}
  4374. Suppose we decode the following structure:
  4375. \begin{small}
  4376. \begin{verbatim}
  4377. User ::= SEQUENCE {
  4378. Name IA5 STRING
  4379. LoginToken SEQUENCE {
  4380. passwdHash OCTET STRING
  4381. pubkey ECCPublicKey
  4382. }
  4383. LastOn UTCTIME
  4384. }
  4385. \end{verbatim}
  4386. \end{small}
  4387. \begin{flushleft}and we decoded it with the following code:\end{flushleft}
  4388. \begin{small}
  4389. \begin{verbatim}
  4390. unsigned char inbuf[MAXSIZE];
  4391. unsigned long inbuflen;
  4392. ltc_asn1_list *list;
  4393. int err;
  4394. /* somehow fill inbuf/inbuflen */
  4395. if ((err = der_decode_sequence_flexi(inbuf, inbuflen, &list)) != CRYPT_OK) {
  4396. printf("Error decoding: %s\n", error_to_string(err));
  4397. exit(EXIT_FAILURE);
  4398. }
  4399. \end{verbatim}
  4400. \end{small}
  4401. At this point \textit{list} would point to the SEQUENCE identified by \textit{User}. It would have no sibblings (prev or next), and only a child node. Walking to the child
  4402. node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
  4403. \begin{small}
  4404. \begin{verbatim}
  4405. list = list->child;
  4406. \end{verbatim}
  4407. \end{small}
  4408. Now \textit{list} points to the \textit{Name} member (with the tag IA5 STRING). The \textit{data}, \textit{size}, and \textit{type} members of \textit{list} should reflect
  4409. that of an IA5 STRING. The sibbling will now be the \textit{LoginToken} SEQUENCE. The sibbling has a child node which points to the \textit{passwdHash} OCTET STRING.
  4410. We can walk to this node with the following code:
  4411. \begin{small}
  4412. \begin{verbatim}
  4413. /* list already pointing to 'Name' */
  4414. list = list->next->child;
  4415. \end{verbatim}
  4416. \end{small}
  4417. At this point, \textit{list} will point to the \textit{passwdHash} member of the innermost SEQUENCE. This node has a sibbling, the \textit{pubkey} member of the SEQUENCE.
  4418. The \textit{LastOn} member of the SEQUENCE is a sibbling of the LoginToken node, if we wanted to walk there we would have to go up and over via:
  4419. \begin{small}
  4420. \begin{verbatim}
  4421. list = list->parent->next;
  4422. \end{verbatim}
  4423. \end{small}
  4424. At this point, we are pointing to the last node of the list. Lists are terminated in all directions by a \textbf{NULL} pointer. All nodes are doubly linked so that you
  4425. can walk up and down the nodes without keeping pointers lying around.
  4426. \subsubsection{Free'ing a Flexi List}
  4427. To free the list use the following function.
  4428. \index{der\_sequence\_free()}
  4429. \begin{verbatim}
  4430. void der_sequence_free(ltc_asn1_list *in);
  4431. \end{verbatim}
  4432. This will free all of the memory allocated by der\_decode\_sequence\_flexi().
  4433. \mysection{Password Based Cryptography}
  4434. \subsection{PKCS \#5}
  4435. \index{PKCS \#5}
  4436. In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
  4437. is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
  4438. for completeness. Algorithm Two is a bit more modern and more flexible to work with.
  4439. The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.
  4440. \subsection{Algorithm One}
  4441. 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
  4442. people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
  4443. algorithm and produces an output no longer than the output of the hash.
  4444. \index{pkcs\_5\_alg1()}
  4445. \begin{alltt}
  4446. int pkcs_5_alg1(const unsigned char *password,
  4447. unsigned long password_len,
  4448. const unsigned char *salt,
  4449. int iteration_count,
  4450. int hash_idx,
  4451. unsigned char *out,
  4452. unsigned long *outlen)
  4453. \end{alltt}
  4454. Where \textit{password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
  4455. The \textit{salt} is a fixed size 8--byte array which should be random for each user and session. The \textit{iteration\_count} is the delay desired
  4456. on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.
  4457. The output of length up to \textit{outlen} is stored in \textit{out}. If \textit{outlen} is initially larger than the size of the hash functions output
  4458. it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in \textit{out}.
  4459. \index{pkcs\_5\_alg1\_openssl()}
  4460. \begin{alltt}
  4461. int pkcs_5_alg1_openssl(const unsigned char *password,
  4462. unsigned long password_len,
  4463. const unsigned char *salt,
  4464. int iteration_count,
  4465. int hash_idx,
  4466. unsigned char *out,
  4467. unsigned long *outlen)
  4468. \end{alltt}
  4469. As above, but we generate as many bytes as requested in outlen per the OpenSSL extension to Algorithm One. If you are trying to be compatible with OpenSSL's EVP\_BytesToKey() or the "openssl enc" command line (or variants such as perl's Crypt::CBC), then use this function with MD5 as your hash (ick!) and iteration\_count=1 (double-ick!!).
  4470. \subsection{Algorithm Two}
  4471. Algorithm Two is the recommended algorithm for this task. It allows variable length salts, and can produce outputs larger than the
  4472. hash functions output. As such, it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
  4473. from a single password and invocation of this algorithm.
  4474. \index{pkcs\_5\_alg2()}
  4475. \begin{alltt}
  4476. int pkcs_5_alg2(const unsigned char *password,
  4477. unsigned long password_len,
  4478. const unsigned char *salt,
  4479. unsigned long salt_len,
  4480. int iteration_count,
  4481. int hash_idx,
  4482. unsigned char *out,
  4483. unsigned long *outlen)
  4484. \end{alltt}
  4485. Where \textit{password} is the users password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
  4486. The \textit{salt} is an array of size \textit{salt\_len}. It should be random for each user and session. The \textit{iteration\_count} is the delay desired
  4487. on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table. The output of length up to
  4488. \textit{outlen} is stored in \textit{out}.
  4489. \begin{verbatim}
  4490. /* demo to show how to make session state material
  4491. * from a password */
  4492. #include <tomcrypt.h>
  4493. int main(void)
  4494. {
  4495. unsigned char password[100], salt[100],
  4496. cipher_key[16], cipher_iv[16],
  4497. mac_key[16], outbuf[48];
  4498. int err, hash_idx;
  4499. unsigned long outlen, password_len, salt_len;
  4500. /* register hash and get it's idx .... */
  4501. /* get users password and make up a salt ... */
  4502. /* create the material (100 iterations in algorithm) */
  4503. outlen = sizeof(outbuf);
  4504. if ((err = pkcs_5_alg2(password, password_len, salt,
  4505. salt_len, 100, hash_idx, outbuf,
  4506. &outlen))
  4507. != CRYPT_OK) {
  4508. /* error handle */
  4509. }
  4510. /* now extract it */
  4511. memcpy(cipher_key, outbuf, 16);
  4512. memcpy(cipher_iv, outbuf+16, 16);
  4513. memcpy(mac_key, outbuf+32, 16);
  4514. /* use material (recall to store the salt in the output) */
  4515. }
  4516. \end{verbatim}
  4517. \mysection{Key Derviation Functions}
  4518. \subsection{HKDF}
  4519. \index{HKDF}
  4520. A key derivation function (KDF) is a basic and essential component of cryptographic systems. Its goal is to take some source of initial
  4521. keying material and derive from it one or more cryptographically strong secret keys.
  4522. HKDF follows the "extract-then-expand" paradigm, where the KDF logically consists of two modules. The first stage takes the input
  4523. keying material and "extracts" from it a fixed-length pseudorandom key K. The second stage "expands" the key K into several additional
  4524. pseudorandom keys (the output of the KDF).
  4525. In many applications, the input keying material is not necessarily distributed uniformly, and the attacker may have some partial
  4526. knowledge about it (for example, a Diffie-Hellman value computed by a key exchange protocol) or even partial control of it (as in some
  4527. entropy-gathering applications). Thus, the goal of the "extract" stage is to "concentrate" the possibly dispersed entropy of the input
  4528. keying material into a short, but cryptographically strong, pseudorandom key. In some applications, the input may already be a
  4529. good pseudorandom key; in these cases, the "extract" stage is not necessary, and the "expand" part can be used alone.
  4530. The second stage "expands" the pseudorandom key to the desired length; the number and lengths of the output keys depend on the
  4531. specific cryptographic algorithms for which the keys are needed.
  4532. \subsection{HKDF Extract}
  4533. To perform the extraction phase, use the following function:
  4534. \index{hkdf\_extract()}
  4535. \begin{alltt}
  4536. int hkdf_extract( int hash_idx,
  4537. const unsigned char *salt,
  4538. unsigned long saltlen,
  4539. const unsigned char *in,
  4540. unsigned long inlen,
  4541. unsigned char *out,
  4542. unsigned long *outlen);
  4543. \end{alltt}
  4544. The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
  4545. The \textit{salt} parameter is a pointer to the array of octets of length \textit{saltlen} containing the salt or a NULL pointer if a salt is not being used (in that case set saltlen to 0).
  4546. \textit{in} is a pointer to an array of octets of length \textit{inlen} containing the source entropy. The extracted output is stored in the location pointed to by \textit{out}.
  4547. You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated to the length of the extracted output. If \textit{outlen} is too small the extracted output will be truncated.
  4548. While the salt is optional, using one improves HKDF's security. If used, the salt should be randomly chosen, but does not need to be secret and may be re-used. Please see RFC5869 section 3.1 for more details.
  4549. \subsection{HKDF Expand}
  4550. To perform the expansion phase, use the following function:
  4551. \index{hkdf\_expand()}
  4552. \begin{alltt}
  4553. int hkdf_expand( int hash_idx,
  4554. const unsigned char *info,
  4555. unsigned long infolen,
  4556. const unsigned char *in,
  4557. unsigned long inlen,
  4558. unsigned char *out,
  4559. unsigned long outlen);
  4560. \end{alltt}
  4561. The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
  4562. The \textit{info} parameter, an array of octets of length \textit{infolen}, is an optional parameter (set \textit{info} to NULL and \textit{infolen} to 0 if not using it) which
  4563. may be used to bind the derived keys to some application and context specific information. This prevents the same keying material from being generated in different contexts. Please see RFC5869 section 3.2 for more information.
  4564. The extracted keying material is passed as octet array \textit{in} of length \textit{inlen}. Expanded output of length \textit{outlen} is generated and stored in octet arrat \textit{out}.
  4565. \subsection{HKDF Extract-and-Expand}
  4566. To perform both phases together, use the following function:
  4567. \index{hkdf()}
  4568. \begin{alltt}
  4569. int hkdf( int hash_idx,
  4570. const unsigned char *salt,
  4571. unsigned long saltlen,
  4572. const unsigned char *info,
  4573. unsigned long infolen,
  4574. const unsigned char *in,
  4575. unsigned long inlen,
  4576. unsigned char *out,
  4577. unsigned long outlen);
  4578. \end{alltt}
  4579. Parameters are as in \textit{hkdf\_extract()} and \textit{hkdf\_expand()}.
  4580. \chapter{Miscellaneous}
  4581. \mysection{Base64 Encoding and Decoding}
  4582. The library provides functions to encode and decode a RFC 1521 base--64 coding scheme. The characters used in the mappings are:
  4583. \begin{verbatim}
  4584. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
  4585. \end{verbatim}
  4586. Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
  4587. common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
  4588. where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
  4589. original input. After the first four characters is the rest of the message.
  4590. Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
  4591. put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
  4592. break up the first four characters.
  4593. To encode a binary string in base64 call:
  4594. \index{base64\_encode()} \index{base64\_decode()}
  4595. \begin{verbatim}
  4596. int base64_encode(const unsigned char *in,
  4597. unsigned long len,
  4598. unsigned char *out,
  4599. unsigned long *outlen);
  4600. \end{verbatim}
  4601. Where \textit{in} is the binary string and \textit{out} is where the ASCII output is placed. You must set the value of \textit{outlen} prior
  4602. to calling this function and it sets the length of the base64 output in \textit{outlen} when it is done. To decode a base64
  4603. string call:
  4604. \begin{verbatim}
  4605. int base64_decode(const unsigned char *in,
  4606. unsigned long len,
  4607. unsigned char *out,
  4608. unsigned long *outlen);
  4609. \end{verbatim}
  4610. \mysection{Primality Testing}
  4611. \index{Primality Testing}
  4612. The library includes primality testing and random prime functions as well. The primality tester will perform the test in
  4613. two phases. First it will perform trial division by the first few primes. Second it will perform eight rounds of the
  4614. Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
  4615. composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
  4616. the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
  4617. $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
  4618. When making random primes the trial division step is in fact an optimized implementation of \textit{Implementation of Fast RSA Key Generation on Smart Cards}\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
  4619. In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candidate
  4620. is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
  4621. math operations. As a result the routine can scan ahead to the next number required for testing with very little work
  4622. involved.
  4623. 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
  4624. instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
  4625. 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
  4626. 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
  4627. 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
  4628. not equal to $(p - 1)(rs - 1)$.
  4629. These are not technically part of the LibTomMath library but this is the best place to document them.
  4630. To test if a \textit{mp\_int} is prime call:
  4631. \begin{verbatim}
  4632. int is_prime(mp_int *N, int *result);
  4633. \end{verbatim}
  4634. This puts a one in \textit{result} if the number is probably prime, otherwise it places a zero in it. It is assumed that if
  4635. it returns an error that the value in \textit{result} is undefined. To make
  4636. a random prime call:
  4637. \begin{verbatim}
  4638. int rand_prime( mp_int *N,
  4639. unsigned long len,
  4640. prng_state *prng,
  4641. int wprng);
  4642. \end{verbatim}
  4643. Where \textit{len} is the size of the prime in bytes ($2 \le len \le 256$). You can set \textit{len} to the negative size you want
  4644. 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
  4645. \textit{len = -128} to the function. Upon success it will return {\bf CRYPT\_OK} and \textit{N} will contain an integer which
  4646. is very likely prime.
  4647. \mysection{Dynamic Language Support}
  4648. \index{Dynamic Language Support}
  4649. Various LibTomCrypt functions require that their callers define a struct
  4650. (or a union) and provide a pointer to it, or allocate sufficient memory and
  4651. provide its pointer. Programs written in C or C++ can obtain the necessary
  4652. information by simply including the appropriate header files, but dynamic
  4653. languages like Python don't understand C header files, and without assistance,
  4654. have no way to know how much memory to allocate. A similar story can be told
  4655. for certain LTC constant values.
  4656. LTC's Dynamic Language Support provides functions that return the size of
  4657. a named struct or union, the value of a named constant, a list of all sizes
  4658. supported, and a list of all named constants supported. Two additional
  4659. functions can initialize LTM and TFM.
  4660. To get the size of a named struct or union:
  4661. \begin{verbatim}
  4662. int crypt_get_size( const char *namein,
  4663. unsigned int *sizeout);
  4664. \end{verbatim}
  4665. $namein$ is spelled exactly as found in the C header files. This function will
  4666. return -1 if $namein$ is not found.
  4667. To get the value of a named constant:
  4668. \begin{verbatim}
  4669. int crypt_get_constant(const char *namein,
  4670. int *valueout);
  4671. \end{verbatim}
  4672. $namein$ is spelled exactly as found in the C header files. Again, -1 is
  4673. returned if $namein$ is not found.
  4674. To get the names of all the supported structs, unions and constants:
  4675. \begin{verbatim}
  4676. int crypt_list_all_sizes( char *names_list,
  4677. unsigned int *names_list_size);
  4678. int crypt_list_all_constants( char *names_list,
  4679. unsigned int *names_list_size);
  4680. \end{verbatim}
  4681. You may want to call these functions twice, first to get the amount
  4682. of memory to be allocated for the $names_list$, and a final time to
  4683. actually populate $names_list$. If $names_list$ is NULL,
  4684. $names_list_size$ will be the minimum size needed to receive the
  4685. complete $names_list$. If $names_list$ is NOT NULL, $names_list$ must
  4686. be a pointer to sufficient memory into which the $names_list$ will be
  4687. written. Also, the value in $names_list_size$ sets the upper bound of
  4688. the number of characters to be written. A -1 return value signifies
  4689. insufficient space.
  4690. The format of the $names_list$ string is a series of $name,value$ pairs
  4691. where each name and value is separated by a comma, the pairs are separated
  4692. by newlines, and the list is null terminated.
  4693. Calling either of these functions will initialize the respective
  4694. math library.
  4695. \begin{verbatim}
  4696. void init_LTM(void);
  4697. void init_TFM(void);
  4698. \end{verbatim}
  4699. Here is a Python program demonstrating how to call various LTC dynamic
  4700. language support functions.
  4701. \begin{verbatim}
  4702. from ctypes import *
  4703. # load the OSX shared/dynamic library
  4704. LIB = CDLL('libtomcrypt.dylib')
  4705. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  4706. # print info about this library
  4707. little = c_int() # assume False is big
  4708. word32 = c_int() # assume False is 64-bit
  4709. LIB.crypt_get_constant('ENDIAN_LITTLE', byref(little))
  4710. LIB.crypt_get_constant('ENDIAN_32BITWORD', byref(word32))
  4711. print('this lib was compiled for a %s endian %d-bit processor'
  4712. % ('little' if little else 'big', 32 if word32 else 64))
  4713. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  4714. # print the size of the struct named "sha256_state"
  4715. struct_size = c_int()
  4716. # don't forget to add the '_struct' or '_union' suffix
  4717. LIB.crypt_get_size('sha256_state_struct', byref(struct_size))
  4718. print('allocate %d bytes for sha256_state' % struct_size.value)
  4719. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  4720. # print a list of all supported named constants
  4721. list_size = c_int()
  4722. # call with NULL to calc the min size needed for the list
  4723. LIB.crypt_list_all_constants(None, byref(list_size))
  4724. # allocate required space
  4725. names_list = c_buffer(list_size.value)
  4726. # call again providing a pointer to where to write the list
  4727. LIB.crypt_list_all_constants(names_list, byref(list_size))
  4728. print(names_list.value)
  4729. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  4730. # print a list of all supported named structs and unions
  4731. list_size = c_int()
  4732. # call with NULL to calc the min size needed for the list
  4733. LIB.crypt_list_all_sizes(None, byref(list_size))
  4734. # allocate required space
  4735. names_list = c_buffer(list_size.value)
  4736. # call again providing a pointer to where to write the list
  4737. LIB.crypt_list_all_sizes(names_list, byref(list_size))
  4738. print(names_list.value)
  4739. \end{verbatim}
  4740. \chapter{Programming Guidelines}
  4741. \mysection{Secure Pseudo Random Number Generators}
  4742. Probably the single most vulnerable point of any cryptosystem is the PRNG. Without one, generating and protecting secrets
  4743. would be impossible. The requirement that one be setup correctly is vitally important, and to address this point the library
  4744. does provide two RNG sources that will address the largest amount of end users as possible. The \textit{sprng} PRNG provides an easy to
  4745. access source of entropy for any application on a UNIX (and the like) or Windows computer.
  4746. However, when the end user is not on one of these platforms, the application developer must address the issue of finding
  4747. entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
  4748. a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
  4749. \mysection{Preventing Trivial Errors}
  4750. Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values. All of the functions
  4751. which output variable length strings will require you to pass the length of the destination. If the size of your output
  4752. buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
  4753. Also, virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors, as simple
  4754. typos can cause algorithms to fail to work as desired.
  4755. \mysection{Registering Your Algorithms}
  4756. To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
  4757. before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
  4758. A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
  4759. having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
  4760. write the few functions required plus a descriptor. After registering your PRNG, all of the library functions that
  4761. need a PRNG can instantly take advantage of it. The same applies for ciphers, hashes, and bignum math routines.
  4762. \mysection{Key Sizes}
  4763. \subsection{Symmetric Ciphers}
  4764. For symmetric ciphers, use as large as of a key as possible. For the most part \textit{bits are cheap} so using a 256--bit key
  4765. is not a hard thing to do. As a good rule of thumb do not use a key smaller than 128 bits.
  4766. \subsection{Asymmetric Ciphers}
  4767. 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
  4768. $n$ is estimated to be
  4769. \begin{equation}
  4770. e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
  4771. \end{equation}
  4772. Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
  4773. is:
  4774. \begin{figure}[h]
  4775. \begin{center}
  4776. \begin{tabular}{|c|c|}
  4777. \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
  4778. \hline 512 & 63.92 \\
  4779. \hline 768 & 76.50 \\
  4780. \hline 1024 & 86.76 \\
  4781. \hline 1536 & 103.37 \\
  4782. \hline 2048 & 116.88 \\
  4783. \hline 2560 & 128.47 \\
  4784. \hline 3072 & 138.73 \\
  4785. \hline 4096 & 156.49 \\
  4786. \hline
  4787. \end{tabular}
  4788. \end{center}
  4789. \caption{RSA/DH Key Strength}
  4790. \end{figure}
  4791. The work factor for ECC keys is much higher since the best attack is still fully exponential. Given a key of magnitude
  4792. $n$ it requires $\sqrt n$ work. The following table summarizes the work required:
  4793. \begin{figure}[h]
  4794. \begin{center}
  4795. \begin{tabular}{|c|c|}
  4796. \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
  4797. \hline 112 & 56 \\
  4798. \hline 128 & 64 \\
  4799. \hline 160 & 80 \\
  4800. \hline 192 & 96 \\
  4801. \hline 224 & 112 \\
  4802. \hline 256 & 128 \\
  4803. \hline 384 & 192 \\
  4804. \hline 521 & 260.5 \\
  4805. \hline
  4806. \end{tabular}
  4807. \end{center}
  4808. \caption{ECC Key Strength}
  4809. \end{figure}
  4810. Using the above tables the following suggestions for key sizes seems appropriate:
  4811. \begin{center}
  4812. \begin{tabular}{|c|c|c|}
  4813. \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
  4814. \hline Near term & 1024 & 160 \\
  4815. \hline Short term & 1536 & 192 \\
  4816. \hline Long Term & 2560 & 384 \\
  4817. \hline
  4818. \end{tabular}
  4819. \end{center}
  4820. \mysection{Thread Safety}
  4821. The library is not fully thread safe but several simple precautions can be taken to avoid any problems. The registry functions
  4822. such as register\_cipher() are not thread safe no matter what you do. It is best to call them from your programs initialization
  4823. code before threads are initiated.
  4824. The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
  4825. thread has its own state variables then they will not affect each other, and are fully thread safe. This is fairly simple with symmetric ciphers
  4826. and hashes.
  4827. \index{LTC\_PTHREAD}
  4828. The only sticky issue is a shared PRNG which can be alleviated with the careful use of mutex devices. Defining LTC\_PTHREAD for instance, enables
  4829. pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.
  4830. \chapter{Configuring and Building the Library}
  4831. \mysection{Introduction}
  4832. The library is fairly flexible about how it can be built, used, and generally distributed. Additions are being made with
  4833. each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
  4834. the build process to make a smaller library. This is particularly useful for shared libraries.
  4835. As of v1.06 of the library, the build process has been moved to two steps for the typical LibTomCrypt application. This is because
  4836. LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath, GnuMP, or TomsFastMath).
  4837. The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
  4838. configured. Note that LibTomCrypt can be built with no internal math descriptors. This means that one must be provided at either
  4839. build, or run time for the application. LibTomCrypt comes with three math descriptors that provide a standard interface to math
  4840. libraries.
  4841. \mysection{Makefile variables}
  4842. All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process. Most of the
  4843. settings can be overwritten from the command line which makes custom installation a breeze.
  4844. \index{MAKE}\index{CC}\index{AR}
  4845. \subsection{MAKE, CC and AR}
  4846. The MAKE, CC and AR flags can all be overwritten. They default to \textit{make}, \textit{\$CC} and \textit{\$AR} respectively.
  4847. Changing MAKE allows you to change what program will be invoked to handle sub--directories. For example, this
  4848. \begin{verbatim}
  4849. MAKE=gmake gmake install
  4850. \end{verbatim}
  4851. \begin{flushleft} will build and install the libraries with the \textit{gmake} tool. Similarly, \end{flushleft}
  4852. \begin{verbatim}
  4853. CC=arm-gcc AR=arm-ar make
  4854. \end{verbatim}
  4855. \begin{flushleft} will build the library using \textit{arm--gcc} as the compiler and \textit{arm--ar} as the archiver. \end{flushleft}
  4856. \subsection{IGNORE\_SPEED}
  4857. \index{IGNORE\_SPEED}
  4858. When \textbf{IGNORE\_SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
  4859. CFLAGS on the command line. E.g. to add debugging
  4860. \begin{verbatim}
  4861. CFLAGS="-g3" make IGNORE_SPEED=1
  4862. \end{verbatim}
  4863. This will turn off optimizations and add \textit{-g3} to the CFLAGS which enables debugging.
  4864. \subsection{LIBNAME and LIBNAME\_S}
  4865. \index{LIBNAME} \index{LIBNAME\_S}
  4866. \textbf{LIBNAME} is the name of the output library (archive) to create. It defaults to \textit{libtomcrypt.a} for static builds and \textit{libtomcrypt.la} for
  4867. shared. The \textbf{LIBNAME\_S} variable is the static name while doing shared builds. Ideally they should have the same prefix but don't have to.
  4868. \index{LIBTEST} \index{LIBTEST\_S}
  4869. Similarly \textbf{LIBTEST} and \textbf{LIBTEST\_S} are the names for the profiling and testing library. The default is \textit{libtomcrypt\_prof.a} for
  4870. static and \textit{libtomcrypt\_prof.la} for shared.
  4871. \subsection{Installation Directories}
  4872. \index{DESTDIR} \index{LIBPATH} \index{INCPATH} \index{DATADIR}
  4873. \textbf{DESTDIR} is the prefix for the installation directories. It defaults to an empty string. \textbf{LIBPATH} is the prefix for the library
  4874. directory which defaults to \textit{/usr/lib}. \textbf{INCPATH} is the prefix for the header file directory which defaults to \textit{/usr/include}.
  4875. \textbf{DATADIR} is the prefix for the data (documentation) directory which defaults to \textit{/usr/share/doc/libtomcrypt/pdf}.
  4876. All four can be used to create custom install locations depending on the nature of the OS and file system in use.
  4877. \begin{verbatim}
  4878. make LIBPATH=/home/tom/project/lib INCPATH=/home/tom/project/include \
  4879. DATAPATH=/home/tom/project/docs install
  4880. \end{verbatim}
  4881. This will build the library and install it to the directories under \textit{/home/tom/project/}. e.g.
  4882. \begin{small}
  4883. \begin{verbatim}
  4884. /home/tom/project/:
  4885. total 1
  4886. drwxr-xr-x 2 tom users 80 Jul 30 16:02 docs
  4887. drwxr-xr-x 2 tom users 528 Jul 30 16:02 include
  4888. drwxr-xr-x 2 tom users 80 Jul 30 16:02 lib
  4889. /home/tom/project/docs:
  4890. total 452
  4891. -rwxr-xr-x 1 tom users 459009 Jul 30 16:02 crypt.pdf
  4892. /home/tom/project/include:
  4893. total 132
  4894. -rwxr-xr-x 1 tom users 2482 Jul 30 16:02 tomcrypt.h
  4895. -rwxr-xr-x 1 tom users 702 Jul 30 16:02 tomcrypt_argchk.h
  4896. -rwxr-xr-x 1 tom users 2945 Jul 30 16:02 tomcrypt_cfg.h
  4897. -rwxr-xr-x 1 tom users 22763 Jul 30 16:02 tomcrypt_cipher.h
  4898. -rwxr-xr-x 1 tom users 5174 Jul 30 16:02 tomcrypt_custom.h
  4899. -rwxr-xr-x 1 tom users 11314 Jul 30 16:02 tomcrypt_hash.h
  4900. -rwxr-xr-x 1 tom users 11571 Jul 30 16:02 tomcrypt_mac.h
  4901. -rwxr-xr-x 1 tom users 13614 Jul 30 16:02 tomcrypt_macros.h
  4902. -rwxr-xr-x 1 tom users 14714 Jul 30 16:02 tomcrypt_math.h
  4903. -rwxr-xr-x 1 tom users 632 Jul 30 16:02 tomcrypt_misc.h
  4904. -rwxr-xr-x 1 tom users 10934 Jul 30 16:02 tomcrypt_pk.h
  4905. -rwxr-xr-x 1 tom users 2634 Jul 30 16:02 tomcrypt_pkcs.h
  4906. -rwxr-xr-x 1 tom users 7067 Jul 30 16:02 tomcrypt_prng.h
  4907. -rwxr-xr-x 1 tom users 1467 Jul 30 16:02 tomcrypt_test.h
  4908. /home/tom/project/lib:
  4909. total 1073
  4910. -rwxr-xr-x 1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
  4911. \end{verbatim}
  4912. \end{small}
  4913. \mysection{Extra libraries}
  4914. \index{EXTRALIBS}
  4915. \textbf{EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
  4916. that GCC expects for global archives.
  4917. \begin{verbatim}
  4918. CFLAGS="-DTFM_DESC -DUSE_TFM" EXTRALIBS=-ltfm make install \
  4919. test timing
  4920. \end{verbatim}
  4921. This will install the library using the TomsFastMath library and link the \textit{libtfm.a} library out of the default library search path. The two
  4922. defines are explained below. You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
  4923. the \textbf{EXTRALIBS} variable by separating them by a space.
  4924. Note that \textbf{EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
  4925. \mysection{Building a Static Library}
  4926. Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
  4927. \begin{verbatim}
  4928. CFLAGS="-DTFM_DESC" make install
  4929. \end{verbatim}
  4930. That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously. You can enable
  4931. the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly, you can build the library with no built--in
  4932. math descriptors.
  4933. \begin{verbatim}
  4934. make install
  4935. \end{verbatim}
  4936. In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
  4937. public key functions.
  4938. Note that even if you include the built--in descriptors you must link against the source library as well.
  4939. \begin{verbatim}
  4940. gcc -DTFM_DESC myprogram.c -ltomcrypt -ltfm -o myprogram
  4941. \end{verbatim}
  4942. This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
  4943. we define \textbf{TFM\_DESC} for compilation. This is so that the TFM descriptor symbol will be defined for the client application to make use of without
  4944. giving warnings.
  4945. \mysection{Building a Shared Library}
  4946. LibTomCrypt can also be built as a shared library through the \textit{makefile.shared} make script. It is similar to use as the static script except
  4947. that you \textbf{must} specify the \textbf{EXTRALIBS} variable at install time.
  4948. \begin{verbatim}
  4949. CFLAGS="-DTFM_DESC" EXTRALIBS=-ltfm make -f makefile.shared install
  4950. \end{verbatim}
  4951. This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
  4952. shared build process requires libtool to be installed.
  4953. \mysection{Header Configuration}
  4954. The file \textit{tomcrypt\_cfg.h} is what lets you control various high level macros which control the behaviour of the library. Build options are also
  4955. stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.
  4956. \subsubsection{ARGTYPE}
  4957. This lets you control how the LTC\_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
  4958. NULL. There are four settings for ARGTYPE. When set to 0, it will have the default behaviour of printing a message to
  4959. stderr and raising a SIGABRT signal. This is provided so all platforms that use LibTomCrypt can have an error that functions
  4960. similarly. When set to 1, it will simply pass on to the assert() macro. When set to 2, the macro will display the error to
  4961. stderr then return execution to the caller. This could lead to a segmentation fault (e.g. when a pointer is \textbf{NULL}) but is useful
  4962. if you handle signals on your own. When set to 3, it will resolve to a empty macro and no error checking will be performed. Finally, when set
  4963. to 4, it will return CRYPT\_INVALID\_ARG to the caller.
  4964. \subsubsection{Endianness}
  4965. There are five macros related to endianness issues. For little endian platforms define, \textbf{ENDIAN\_LITTLE}. For big endian
  4966. platforms define \textbf{ENDIAN\_BIG}. Similarly when the default word size of an \textit{unsigned long} is 32-bits define \textbf{ENDIAN\_32BITWORD}
  4967. or define \textbf{ENDIAN\_64BITWORD} when its 64-bits. If you do not define any of them the library will automatically use \textbf{ENDIAN\_NEUTRAL}
  4968. which will work on all platforms.
  4969. Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.
  4970. \mysection{Customisation}
  4971. There are also options you can specify from the \textit{tomcrypt\_custom.h} header file.
  4972. \subsection{X memory routines}
  4973. \index{XMALLOC}\index{XCALLOC}\index{XREALLOC}\index{XFREE}
  4974. At the top of tomcrypt\_custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on. They resolve to
  4975. the name of the respective functions from the standard C library by default. This lets you substitute in your own memory routines.
  4976. If you substitute in your own functions they must behave like the standard C library functions in terms of what they expect as input and
  4977. output.
  4978. These macros are handy for working with platforms which do not have a standard C library. For instance, the OLPC\footnote{See http://dev.laptop.org/git?p=bios-crypto;a=summary}
  4979. bios code uses these macros to redirect to very compact heap and string operations.
  4980. \subsection{X clock routines}
  4981. The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
  4982. the default clock() used with a replacement. By default the standard C library clock() function is used.
  4983. \subsection{LTC\_NO\_FILE}
  4984. During the build if LTC\_NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
  4985. functions and instead simply return CRYPT\_NOP. This should help resolve any linker errors stemming from a lack of
  4986. file I/O on embedded platforms.
  4987. \subsection{LTC\_CLEAN\_STACK}
  4988. When this functions is defined the functions that store key material on the stack will clean up afterwards.
  4989. Assumes that you have no memory paging with the stack.
  4990. \subsection{LTC\_TEST}
  4991. When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build. This is the default configuration.
  4992. If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.
  4993. \subsection{LTC\_NO\_FAST}
  4994. When this has been defined the library will not use faster word oriented operations. By default, they are only enabled for platforms
  4995. which can be auto-detected. This macro ensures that they are never enabled.
  4996. \subsection{LTC\_FAST}
  4997. This mode (auto-detected with x86\_32, x86\_64 platforms with GCC or CLANG) configures various routines such as ctr\_encrypt() or
  4998. cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
  4999. cutting down the overhead of the respective functions.
  5000. This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
  5001. it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_FAST
  5002. is not \textit{portable} since unaligned accesses are not covered by the ISO C specifications.
  5003. In practice however, you can use it on pretty much any platform (even MIPS) with care.
  5004. By design the \textit{fast} mode functions won't get unaligned on their own. For instance, if you call ctr\_encrypt() right after calling
  5005. ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only. However, if you
  5006. call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
  5007. cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
  5008. whole word XOR operations. These operations will be unaligned.
  5009. The simplest precaution is to make sure you process all data in power of two blocks and handle \textit{remainder} at the end. e.g. If you are
  5010. 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.
  5011. \index{LTC\_FAST\_TYPE}
  5012. If you do plan on using the \textit{LTC\_FAST} mode, a \textit{LTC\_FAST\_TYPE} type which resolves to an optimal sized
  5013. data type you can perform integer operations with is required. For the auto-detected platforms this type will be defined automatically. Ideally it should be four or eight bytes since it must properly divide the size
  5014. 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
  5015. use this mode. So sad.
  5016. \subsection{LTC\_NO\_ASM}
  5017. When this has been defined the library will not use any inline assembler. Only a few platforms support assembler inlines but various versions of ICC and GCC
  5018. cannot handle all of the assembler functions.
  5019. \subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
  5020. There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
  5021. self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
  5022. dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
  5023. cipher and a hash function.
  5024. Also see technical note number five for more details.
  5025. \subsection{LTC\_EASY}
  5026. When defined the library is configured to build fewer algorithms and modes. Mostly it sticks to NIST and ANSI approved algorithms. See
  5027. the header file \textit{tomcrypt\_custom.h} for more details. It is meant to provide literally an easy method of trimming the library
  5028. build to the most minimum of useful functionality.
  5029. \subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
  5030. Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
  5031. to allow some trade-offs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
  5032. requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
  5033. defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
  5034. tables at a cost of 4KB of memory. The cipher will be much faster as a result.
  5035. When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
  5036. useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
  5037. will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
  5038. it will not speed up the encryption or decryption functions.
  5039. \subsection{GCM\_TABLES}
  5040. When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
  5041. It also increases the initialization time and is not suitable when you are going to use a key a few times only.
  5042. \subsection{GCM\_TABLES\_SSE2}
  5043. \index{SSE2}
  5044. When defined GCM will use the SSE2 instructions to perform the $GF(2^x)$ multiply using 16 128--bit XOR operations. It shaves a few cycles per byte
  5045. of GCM output on both the AMD64 and Intel Pentium 4 platforms. Requires GCC and an SSE2 equipped platform.
  5046. \subsection{LTC\_SMALL\_CODE}
  5047. When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
  5048. These variants are slower but can save quite a bit of code space.
  5049. \subsection{LTC\_PTHREAD}
  5050. When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
  5051. it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
  5052. Generally the rule of thumb is to setup the tables once at startup and then leave them be. This added build flag simply makes updating
  5053. the tables safer.
  5054. \subsection{LTC\_ECC\_TIMING\_RESISTANT}
  5055. When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
  5056. algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
  5057. where timing side channels pose a significant threat.
  5058. \subsection{Math Descriptors}
  5059. The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
  5060. libraries. When \textbf{GMP\_DESC}, \textbf{LTM\_DESC}, or \textbf{TFM\_DESC} are defined
  5061. descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.
  5062. In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
  5063. to tell the program which library to use. Only one of the USE flags can be defined at once.
  5064. \index{GMP\_DESC} \index{USE\_GMP} \index{LTM\_DESC} \index{TFM\_DESC} \index{USE\_LTM} \index{USE\_TFM}
  5065. \begin{small}
  5066. \begin{verbatim}
  5067. CFLAGS="-DGMP_DESC -DLTM_DESC -DTFM_DESC -DUSE_TFM" \
  5068. EXTRALIBS="-lgmp -ltommath -ltfm" make -f makefile.shared install timing
  5069. \end{verbatim}
  5070. \end{small}
  5071. That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.
  5072. \chapter{Optimizations}
  5073. \mysection{Introduction}
  5074. The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash, PRNG or bignum library and the dependent API will not
  5075. require updating. This has the nice benefit that one can add ciphers (etc.) not have to re--write portions of the API. For the most part, LibTomCrypt has also been written
  5076. 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
  5077. about the platform, etc...
  5078. That works well for most cases but there are times where performance is of the essence. This API allows optimized routines to be dropped in--place of the existing
  5079. portable routines. For instance, hand optimized assembler versions of AES could be provided. Any existing function that uses the cipher could automatically use
  5080. the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
  5081. At the heart of this flexibility is the \textit{descriptor} system. A descriptor is essentially just a C \textit{struct} which describes the algorithm and provides pointers
  5082. to functions that do the required work. For a given class of operation (e.g. cipher, hash, prng, bignum) the functions of a descriptor have identical prototypes which makes
  5083. development simple. In most dependent routines all an end developer has to do is register\_XXX() the descriptor and they are set.
  5084. \mysection{Ciphers}
  5085. The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
  5086. \label{sec:cipherdesc}
  5087. \begin{small}
  5088. \begin{verbatim}
  5089. struct ltc_cipher_descriptor {
  5090. /** name of cipher */
  5091. char *name;
  5092. /** internal ID */
  5093. unsigned char ID;
  5094. /** min keysize (octets) */
  5095. int min_key_length,
  5096. /** max keysize (octets) */
  5097. max_key_length,
  5098. /** block size (octets) */
  5099. block_length,
  5100. /** default number of rounds */
  5101. default_rounds;
  5102. /** Setup the cipher
  5103. @param key The input symmetric key
  5104. @param keylen The length of the input key (octets)
  5105. @param num_rounds The requested number of rounds (0==default)
  5106. @param skey [out] The destination of the scheduled key
  5107. @return CRYPT_OK if successful
  5108. */
  5109. int (*setup)(const unsigned char *key,
  5110. int keylen,
  5111. int num_rounds,
  5112. symmetric_key *skey);
  5113. /** Encrypt a block
  5114. @param pt The plaintext
  5115. @param ct [out] The ciphertext
  5116. @param skey The scheduled key
  5117. @return CRYPT_OK if successful
  5118. */
  5119. int (*ecb_encrypt)(const unsigned char *pt,
  5120. unsigned char *ct,
  5121. symmetric_key *skey);
  5122. /** Decrypt a block
  5123. @param ct The ciphertext
  5124. @param pt [out] The plaintext
  5125. @param skey The scheduled key
  5126. @return CRYPT_OK if successful
  5127. */
  5128. int (*ecb_decrypt)(const unsigned char *ct,
  5129. unsigned char *pt,
  5130. symmetric_key *skey);
  5131. /** Test the block cipher
  5132. @return CRYPT_OK if successful,
  5133. CRYPT_NOP if self-testing has been disabled
  5134. */
  5135. int (*test)(void);
  5136. /** Terminate the context
  5137. @param skey The scheduled key
  5138. */
  5139. void (*done)(symmetric_key *skey);
  5140. /** Determine a key size
  5141. @param keysize [in/out] The size of the key desired
  5142. The suggested size
  5143. @return CRYPT_OK if successful
  5144. */
  5145. int (*keysize)(int *keysize);
  5146. /** Accelerators **/
  5147. /** Accelerated ECB encryption
  5148. @param pt Plaintext
  5149. @param ct Ciphertext
  5150. @param blocks The number of complete blocks to process
  5151. @param skey The scheduled key context
  5152. @return CRYPT_OK if successful
  5153. */
  5154. int (*accel_ecb_encrypt)(const unsigned char *pt,
  5155. unsigned char *ct,
  5156. unsigned long blocks,
  5157. symmetric_key *skey);
  5158. /** Accelerated ECB decryption
  5159. @param pt Plaintext
  5160. @param ct Ciphertext
  5161. @param blocks The number of complete blocks to process
  5162. @param skey The scheduled key context
  5163. @return CRYPT_OK if successful
  5164. */
  5165. int (*accel_ecb_decrypt)(const unsigned char *ct,
  5166. unsigned char *pt,
  5167. unsigned long blocks,
  5168. symmetric_key *skey);
  5169. /** Accelerated CBC encryption
  5170. @param pt Plaintext
  5171. @param ct Ciphertext
  5172. @param blocks The number of complete blocks to process
  5173. @param IV The initial value (input/output)
  5174. @param skey The scheduled key context
  5175. @return CRYPT_OK if successful
  5176. */
  5177. int (*accel_cbc_encrypt)(const unsigned char *pt,
  5178. unsigned char *ct,
  5179. unsigned long blocks,
  5180. unsigned char *IV,
  5181. symmetric_key *skey);
  5182. /** Accelerated CBC decryption
  5183. @param pt Plaintext
  5184. @param ct Ciphertext
  5185. @param blocks The number of complete blocks to process
  5186. @param IV The initial value (input/output)
  5187. @param skey The scheduled key context
  5188. @return CRYPT_OK if successful
  5189. */
  5190. int (*accel_cbc_decrypt)(const unsigned char *ct,
  5191. unsigned char *pt,
  5192. unsigned long blocks,
  5193. unsigned char *IV,
  5194. symmetric_key *skey);
  5195. /** Accelerated CTR encryption
  5196. @param pt Plaintext
  5197. @param ct Ciphertext
  5198. @param blocks The number of complete blocks to process
  5199. @param IV The initial value (input/output)
  5200. @param mode little or big endian counter (mode=0 or mode=1)
  5201. @param skey The scheduled key context
  5202. @return CRYPT_OK if successful
  5203. */
  5204. int (*accel_ctr_encrypt)(const unsigned char *pt,
  5205. unsigned char *ct,
  5206. unsigned long blocks,
  5207. unsigned char *IV,
  5208. int mode,
  5209. symmetric_key *skey);
  5210. /** Accelerated LRW
  5211. @param pt Plaintext
  5212. @param ct Ciphertext
  5213. @param blocks The number of complete blocks to process
  5214. @param IV The initial value (input/output)
  5215. @param tweak The LRW tweak
  5216. @param skey The scheduled key context
  5217. @return CRYPT_OK if successful
  5218. */
  5219. int (*accel_lrw_encrypt)(const unsigned char *pt,
  5220. unsigned char *ct,
  5221. unsigned long blocks,
  5222. unsigned char *IV,
  5223. const unsigned char *tweak,
  5224. symmetric_key *skey);
  5225. /** Accelerated LRW
  5226. @param ct Ciphertext
  5227. @param pt Plaintext
  5228. @param blocks The number of complete blocks to process
  5229. @param IV The initial value (input/output)
  5230. @param tweak The LRW tweak
  5231. @param skey The scheduled key context
  5232. @return CRYPT_OK if successful
  5233. */
  5234. int (*accel_lrw_decrypt)(const unsigned char *ct,
  5235. unsigned char *pt,
  5236. unsigned long blocks,
  5237. unsigned char *IV,
  5238. const unsigned char *tweak,
  5239. symmetric_key *skey);
  5240. /** Accelerated CCM packet (one-shot)
  5241. @param key The secret key to use
  5242. @param keylen The length of the secret key (octets)
  5243. @param uskey A previously scheduled key [can be NULL]
  5244. @param nonce The session nonce [use once]
  5245. @param noncelen The length of the nonce
  5246. @param header The header for the session
  5247. @param headerlen The length of the header (octets)
  5248. @param pt [out] The plaintext
  5249. @param ptlen The length of the plaintext (octets)
  5250. @param ct [out] The ciphertext
  5251. @param tag [out] The destination tag
  5252. @param taglen [in/out] The max size and resulting size
  5253. of the authentication tag
  5254. @param direction Encrypt or Decrypt direction (0 or 1)
  5255. @return CRYPT_OK if successful
  5256. */
  5257. int (*accel_ccm_memory)(
  5258. const unsigned char *key, unsigned long keylen,
  5259. symmetric_key *uskey,
  5260. const unsigned char *nonce, unsigned long noncelen,
  5261. const unsigned char *header, unsigned long headerlen,
  5262. unsigned char *pt, unsigned long ptlen,
  5263. unsigned char *ct,
  5264. unsigned char *tag, unsigned long *taglen,
  5265. int direction);
  5266. /** Accelerated GCM packet (one shot)
  5267. @param key The secret key
  5268. @param keylen The length of the secret key
  5269. @param IV The initial vector
  5270. @param IVlen The length of the initial vector
  5271. @param adata The additional authentication data (header)
  5272. @param adatalen The length of the adata
  5273. @param pt The plaintext
  5274. @param ptlen The length of the plaintext/ciphertext
  5275. @param ct The ciphertext
  5276. @param tag [out] The MAC tag
  5277. @param taglen [in/out] The MAC tag length
  5278. @param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
  5279. @return CRYPT_OK on success
  5280. */
  5281. int (*accel_gcm_memory)(
  5282. const unsigned char *key, unsigned long keylen,
  5283. const unsigned char *IV, unsigned long IVlen,
  5284. const unsigned char *adata, unsigned long adatalen,
  5285. unsigned char *pt, unsigned long ptlen,
  5286. unsigned char *ct,
  5287. unsigned char *tag, unsigned long *taglen,
  5288. int direction);
  5289. /** Accelerated one shot OMAC
  5290. @param key The secret key
  5291. @param keylen The key length (octets)
  5292. @param in The message
  5293. @param inlen Length of message (octets)
  5294. @param out [out] Destination for tag
  5295. @param outlen [in/out] Initial and final size of out
  5296. @return CRYPT_OK on success
  5297. */
  5298. int (*omac_memory)(
  5299. const unsigned char *key, unsigned long keylen,
  5300. const unsigned char *in, unsigned long inlen,
  5301. unsigned char *out, unsigned long *outlen);
  5302. /** Accelerated one shot XCBC
  5303. @param key The secret key
  5304. @param keylen The key length (octets)
  5305. @param in The message
  5306. @param inlen Length of message (octets)
  5307. @param out [out] Destination for tag
  5308. @param outlen [in/out] Initial and final size of out
  5309. @return CRYPT_OK on success
  5310. */
  5311. int (*xcbc_memory)(
  5312. const unsigned char *key, unsigned long keylen,
  5313. const unsigned char *in, unsigned long inlen,
  5314. unsigned char *out, unsigned long *outlen);
  5315. /** Accelerated one shot F9
  5316. @param key The secret key
  5317. @param keylen The key length (octets)
  5318. @param in The message
  5319. @param inlen Length of message (octets)
  5320. @param out [out] Destination for tag
  5321. @param outlen [in/out] Initial and final size of out
  5322. @return CRYPT_OK on success
  5323. @remark Requires manual padding
  5324. */
  5325. int (*f9_memory)(
  5326. const unsigned char *key, unsigned long keylen,
  5327. const unsigned char *in, unsigned long inlen,
  5328. unsigned char *out, unsigned long *outlen);
  5329. };
  5330. \end{verbatim}
  5331. \end{small}
  5332. \subsection{Name}
  5333. \index{find\_cipher()}
  5334. The \textit{name} parameter specifies the name of the cipher. This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
  5335. tables.
  5336. \subsection{Internal ID}
  5337. This is a single byte Internal ID you can use to distinguish ciphers from each other.
  5338. \subsection{Key Lengths}
  5339. The minimum key length is \textit{min\_key\_length} and is measured in octets. Similarly the maximum key length is \textit{max\_key\_length}. They can be equal
  5340. and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
  5341. \subsection{Block Length}
  5342. The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.
  5343. \subsection{Rounds}
  5344. Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit{default\_rounds}.
  5345. \subsection{Setup}
  5346. To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets \textit{key} of length \textit{keylen} octets. The user
  5347. can specify the number of rounds they want through \textit{num\_rounds} where $num\_rounds = 0$ means use the default. The destination of a scheduled key is stored
  5348. in \textit{skey}.
  5349. Inside the \textit{symmetric\_key} union there is a \textit{void *data} which you can use to allocate data if you need a data structure that does not fit with the existing
  5350. ones provided. Just make sure in your \textit{done()} function that you free the allocated memory.
  5351. \subsection{Single block ECB}
  5352. 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
  5353. must make sure you do not overwrite the output before you are finished with the input.
  5354. \subsection{Testing}
  5355. The test() function is used to self--test the \textit{device}. It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly. You may return
  5356. \textbf{CRYPT\_NOP} to indicate that no testing was performed.
  5357. \subsection{Key Sizing}
  5358. 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
  5359. 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
  5360. 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
  5361. cannot be mapped to a valid key size for the cipher.
  5362. \subsection{Acceleration}
  5363. 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
  5364. it is not supported. In those cases the software defaults are used (using the single ECB block routines).
  5365. \subsubsection{Accelerated ECB}
  5366. 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
  5367. through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The \textit{blocks} count is the number of complete blocks to process.
  5368. \subsubsection{Accelerated CBC}
  5369. These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
  5370. The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CBC initial vector. It is an input upon calling this function and must be
  5371. updated by the function before returning.
  5372. \subsubsection{Accelerated CTR}
  5373. This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
  5374. The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CTR counter vector. It is an input upon calling this function and must be
  5375. updated by the function before returning. The \textit{mode} value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or
  5376. little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.
  5377. 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
  5378. called if the following conditions are met.
  5379. \begin{enumerate}
  5380. \item The accelerator is present
  5381. \item The CTR pad is empty
  5382. \item The remaining length of the input to process is greater than or equal to the block size.
  5383. \end{enumerate}
  5384. The \textit{CTR pad} is empty when a multiple (including zero) blocks of text have been processed. That is, if you pass in seven bytes to AES--CTR mode you would have to
  5385. 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
  5386. buffer provided) before encrypting it to create the pad.
  5387. The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
  5388. \subsubsection{Accelerated LRW}
  5389. These functions are meant for accelerated LRW. They process blocks of input in lengths of multiples of 16 octets. They must accept the \textit{IV} and \textit{tweak}
  5390. state variables and updated them prior to returning. Note that you may want to disable \textbf{LRW\_TABLES} in \textit{tomcrypt\_custom.h} if you intend
  5391. to use accelerators for LRW.
  5392. While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_setiv() more efficient.
  5393. Note that calling lrw\_done() will only invoke the cipher\_descriptor[].done() function on the \textit{symmetric\_key} parameter of the LRW state. That means
  5394. if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
  5395. the plugin solely to do LRW with the cipher. That way cipher\_descriptor[].setup() means to init LRW resources and cipher\_descriptor[].done() means to
  5396. free them.
  5397. \subsubsection{Accelerated CCM}
  5398. This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
  5399. by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance). This
  5400. function MUST support both key passing methods.
  5401. \begin{center}
  5402. \begin{small}
  5403. \begin{tabular}{|r|r|l|}
  5404. \hline \textbf{key} & \textbf{uskey} & \textbf{Source of key} \\
  5405. \hline NULL & NULL & Error, not supported \\
  5406. \hline non-NULL & NULL & Use key, do a key schedule \\
  5407. \hline NULL & non-NULL & Use uskey, key schedule not required \\
  5408. \hline non-NULL & non-NULL & Use uskey, key schedule not required \\
  5409. \hline
  5410. \end{tabular}
  5411. \end{small}
  5412. \end{center}
  5413. \index{ccm\_memory()} This function is called when the user calls ccm\_memory().
  5414. \subsubsection{Accelerated GCM}
  5415. \index{gcm\_memory()}
  5416. 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
  5417. be called prior to this. This function must handle scheduling the key provided on its own. It is called when the user calls gcm\_memory().
  5418. \subsubsection{Accelerated OMAC}
  5419. \index{omac\_memory()}
  5420. This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_memory().
  5421. \subsubsection{Accelerated XCBC-MAC}
  5422. \index{xcbc\_memory()}
  5423. This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_memory().
  5424. \subsubsection{Accelerated F9}
  5425. \index{f9\_memory()}
  5426. This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory(). Like f9\_memory(), it requires
  5427. the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.
  5428. \mysection{One--Way Hashes}
  5429. The hash functions are accessed through the ltc\_hash\_descriptor structure.
  5430. \begin{small}
  5431. \begin{verbatim}
  5432. struct ltc_hash_descriptor {
  5433. /** name of hash */
  5434. char *name;
  5435. /** internal ID */
  5436. unsigned char ID;
  5437. /** Size of digest in octets */
  5438. unsigned long hashsize;
  5439. /** Input block size in octets */
  5440. unsigned long blocksize;
  5441. /** ASN.1 OID */
  5442. unsigned long OID[16];
  5443. /** Length of DER encoding */
  5444. unsigned long OIDlen;
  5445. /** Init a hash state
  5446. @param hash The hash to initialize
  5447. @return CRYPT_OK if successful
  5448. */
  5449. int (*init)(hash_state *hash);
  5450. /** Process a block of data
  5451. @param hash The hash state
  5452. @param in The data to hash
  5453. @param inlen The length of the data (octets)
  5454. @return CRYPT_OK if successful
  5455. */
  5456. int (*process)( hash_state *hash,
  5457. const unsigned char *in,
  5458. unsigned long inlen);
  5459. /** Produce the digest and store it
  5460. @param hash The hash state
  5461. @param out [out] The destination of the digest
  5462. @return CRYPT_OK if successful
  5463. */
  5464. int (*done)( hash_state *hash,
  5465. unsigned char *out);
  5466. /** Self-test
  5467. @return CRYPT_OK if successful,
  5468. CRYPT_NOP if self-tests have been disabled
  5469. */
  5470. int (*test)(void);
  5471. /* accelerated hmac callback: if you need to-do
  5472. multiple packets just use the generic hmac_memory
  5473. and provide a hash callback
  5474. */
  5475. int (*hmac_block)(const unsigned char *key,
  5476. unsigned long keylen,
  5477. const unsigned char *in,
  5478. unsigned long inlen,
  5479. unsigned char *out,
  5480. unsigned long *outlen);
  5481. };
  5482. \end{verbatim}
  5483. \end{small}
  5484. \subsection{Name}
  5485. This is the name the hash is known by and what find\_hash() will look for.
  5486. \subsection{Internal ID}
  5487. This is the internal ID byte used to distinguish the hash from other hashes.
  5488. \subsection{Digest Size}
  5489. The \textit{hashsize} variable indicates the length of the output in octets.
  5490. \subsection{Block Size}
  5491. The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
  5492. invocation.
  5493. \subsection{OID Identifier}
  5494. This is the universal ASN.1 Object Identifier for the hash.
  5495. \subsection{Initialization}
  5496. The init function initializes the hash and prepares it to process message bytes.
  5497. \subsection{Process}
  5498. This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
  5499. guaranteed to be a multiple of the block size in length.
  5500. \subsection{Done}
  5501. The done function terminates the hash and returns the message digest.
  5502. \subsection{Acceleration}
  5503. A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
  5504. \subsection{HMAC Acceleration}
  5505. The hmac\_block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_memory() if present. If you need
  5506. to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_memory() as provided in LibTomCrypt.
  5507. \mysection{Pseudo--Random Number Generators}
  5508. The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
  5509. \begin{small}
  5510. \begin{verbatim}
  5511. struct ltc_prng_descriptor {
  5512. /** Name of the PRNG */
  5513. char *name;
  5514. /** size in bytes of exported state */
  5515. int export_size;
  5516. /** Start a PRNG state
  5517. @param prng [out] The state to initialize
  5518. @return CRYPT_OK if successful
  5519. */
  5520. int (*start)(prng_state *prng);
  5521. /** Add entropy to the PRNG
  5522. @param in The entropy
  5523. @param inlen Length of the entropy (octets)
  5524. @param prng The PRNG state
  5525. @return CRYPT_OK if successful
  5526. */
  5527. int (*add_entropy)(const unsigned char *in,
  5528. unsigned long inlen,
  5529. prng_state *prng);
  5530. /** Ready a PRNG state to read from
  5531. @param prng The PRNG state to ready
  5532. @return CRYPT_OK if successful
  5533. */
  5534. int (*ready)(prng_state *prng);
  5535. /** Read from the PRNG
  5536. @param out [out] Where to store the data
  5537. @param outlen Length of data desired (octets)
  5538. @param prng The PRNG state to read from
  5539. @return Number of octets read
  5540. */
  5541. unsigned long (*read)(unsigned char *out,
  5542. unsigned long outlen,
  5543. prng_state *prng);
  5544. /** Terminate a PRNG state
  5545. @param prng The PRNG state to terminate
  5546. @return CRYPT_OK if successful
  5547. */
  5548. int (*done)(prng_state *prng);
  5549. /** Export a PRNG state
  5550. @param out [out] The destination for the state
  5551. @param outlen [in/out] The max size and resulting size
  5552. @param prng The PRNG to export
  5553. @return CRYPT_OK if successful
  5554. */
  5555. int (*pexport)(unsigned char *out,
  5556. unsigned long *outlen,
  5557. prng_state *prng);
  5558. /** Import a PRNG state
  5559. @param in The data to import
  5560. @param inlen The length of the data to import (octets)
  5561. @param prng The PRNG to initialize/import
  5562. @return CRYPT_OK if successful
  5563. */
  5564. int (*pimport)(const unsigned char *in,
  5565. unsigned long inlen,
  5566. prng_state *prng);
  5567. /** Self-test the PRNG
  5568. @return CRYPT_OK if successful,
  5569. CRYPT_NOP if self-testing has been disabled
  5570. */
  5571. int (*test)(void);
  5572. };
  5573. \end{verbatim}
  5574. \end{small}
  5575. \subsection{Name}
  5576. The name by which find\_prng() will find the PRNG.
  5577. \subsection{Export Size}
  5578. When an PRNG state is to be exported for future use you specify the space required in this variable.
  5579. \subsection{Start}
  5580. Initialize the PRNG and make it ready to accept entropy.
  5581. \subsection{Entropy Addition}
  5582. Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
  5583. \subsection{Ready}
  5584. This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
  5585. on the specific PRNG used.
  5586. \subsection{Read}
  5587. Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
  5588. if it does as many protocols do not retry reads and will fail on the first try.
  5589. \subsection{Done}
  5590. Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
  5591. \subsection{Exporting and Importing}
  5592. An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume \textit{the same session}
  5593. but should at least maintain the same level of state entropy.
  5594. \mysection{BigNum Math Descriptors}
  5595. The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
  5596. it hasn't proven hard to write \textit{glue} to use math libraries so far. The basic descriptor looks like.
  5597. \begin{small}
  5598. \begin{verbatim}
  5599. /** math descriptor */
  5600. typedef struct {
  5601. /** Name of the math provider */
  5602. char *name;
  5603. /** Bits per digit, amount of bits must fit in an unsigned long */
  5604. int bits_per_digit;
  5605. /* ---- init/deinit functions ---- */
  5606. /** initialize a bignum
  5607. @param a The number to initialize
  5608. @return CRYPT_OK on success
  5609. */
  5610. int (*init)(void **a);
  5611. /** init copy
  5612. @param dst The number to initialize and write to
  5613. @param src The number to copy from
  5614. @return CRYPT_OK on success
  5615. */
  5616. int (*init_copy)(void **dst, void *src);
  5617. /** deinit
  5618. @param a The number to free
  5619. @return CRYPT_OK on success
  5620. */
  5621. void (*deinit)(void *a);
  5622. /* ---- data movement ---- */
  5623. /** negate
  5624. @param src The number to negate
  5625. @param dst The destination
  5626. @return CRYPT_OK on success
  5627. */
  5628. int (*neg)(void *src, void *dst);
  5629. /** copy
  5630. @param src The number to copy from
  5631. @param dst The number to write to
  5632. @return CRYPT_OK on success
  5633. */
  5634. int (*copy)(void *src, void *dst);
  5635. /* ---- trivial low level functions ---- */
  5636. /** set small constant
  5637. @param a Number to write to
  5638. @param n Source upto bits_per_digit (actually meant for very small constants)
  5639. @return CRYPT_OK on success
  5640. */
  5641. int (*set_int)(void *a, unsigned long n);
  5642. /** get small constant
  5643. @param a Small number to read,
  5644. only fetches up to bits_per_digit from the number
  5645. @return The lower bits_per_digit of the integer (unsigned)
  5646. */
  5647. unsigned long (*get_int)(void *a);
  5648. /** get digit n
  5649. @param a The number to read from
  5650. @param n The number of the digit to fetch
  5651. @return The bits_per_digit sized n'th digit of a
  5652. */
  5653. ltc_mp_digit (*get_digit)(void *a, int n);
  5654. /** Get the number of digits that represent the number
  5655. @param a The number to count
  5656. @return The number of digits used to represent the number
  5657. */
  5658. int (*get_digit_count)(void *a);
  5659. /** compare two integers
  5660. @param a The left side integer
  5661. @param b The right side integer
  5662. @return LTC_MP_LT if a < b,
  5663. LTC_MP_GT if a > b and
  5664. LTC_MP_EQ otherwise. (signed comparison)
  5665. */
  5666. int (*compare)(void *a, void *b);
  5667. /** compare against int
  5668. @param a The left side integer
  5669. @param b The right side integer (upto bits_per_digit)
  5670. @return LTC_MP_LT if a < b,
  5671. LTC_MP_GT if a > b and
  5672. LTC_MP_EQ otherwise. (signed comparison)
  5673. */
  5674. int (*compare_d)(void *a, unsigned long n);
  5675. /** Count the number of bits used to represent the integer
  5676. @param a The integer to count
  5677. @return The number of bits required to represent the integer
  5678. */
  5679. int (*count_bits)(void * a);
  5680. /** Count the number of LSB bits which are zero
  5681. @param a The integer to count
  5682. @return The number of contiguous zero LSB bits
  5683. */
  5684. int (*count_lsb_bits)(void *a);
  5685. /** Compute a power of two
  5686. @param a The integer to store the power in
  5687. @param n The power of two you want to store (a = 2^n)
  5688. @return CRYPT_OK on success
  5689. */
  5690. int (*twoexpt)(void *a , int n);
  5691. /* ---- radix conversions ---- */
  5692. /** read ascii string
  5693. @param a The integer to store into
  5694. @param str The string to read
  5695. @param radix The radix the integer has been represented in (2-64)
  5696. @return CRYPT_OK on success
  5697. */
  5698. int (*read_radix)(void *a, const char *str, int radix);
  5699. /** write number to string
  5700. @param a The integer to store
  5701. @param str The destination for the string
  5702. @param radix The radix the integer is to be represented in (2-64)
  5703. @return CRYPT_OK on success
  5704. */
  5705. int (*write_radix)(void *a, char *str, int radix);
  5706. /** get size as unsigned char string
  5707. @param a The integer to get the size (when stored in array of octets)
  5708. @return The length of the integer in octets
  5709. */
  5710. unsigned long (*unsigned_size)(void *a);
  5711. /** store an integer as an array of octets
  5712. @param src The integer to store
  5713. @param dst The buffer to store the integer in
  5714. @return CRYPT_OK on success
  5715. */
  5716. int (*unsigned_write)(void *src, unsigned char *dst);
  5717. /** read an array of octets and store as integer
  5718. @param dst The integer to load
  5719. @param src The array of octets
  5720. @param len The number of octets
  5721. @return CRYPT_OK on success
  5722. */
  5723. int (*unsigned_read)( void *dst,
  5724. unsigned char *src,
  5725. unsigned long len);
  5726. /* ---- basic math ---- */
  5727. /** add two integers
  5728. @param a The first source integer
  5729. @param b The second source integer
  5730. @param c The destination of "a + b"
  5731. @return CRYPT_OK on success
  5732. */
  5733. int (*add)(void *a, void *b, void *c);
  5734. /** add two integers
  5735. @param a The first source integer
  5736. @param b The second source integer
  5737. (single digit of upto bits_per_digit in length)
  5738. @param c The destination of "a + b"
  5739. @return CRYPT_OK on success
  5740. */
  5741. int (*addi)(void *a, unsigned long b, void *c);
  5742. /** subtract two integers
  5743. @param a The first source integer
  5744. @param b The second source integer
  5745. @param c The destination of "a - b"
  5746. @return CRYPT_OK on success
  5747. */
  5748. int (*sub)(void *a, void *b, void *c);
  5749. /** subtract two integers
  5750. @param a The first source integer
  5751. @param b The second source integer
  5752. (single digit of upto bits_per_digit in length)
  5753. @param c The destination of "a - b"
  5754. @return CRYPT_OK on success
  5755. */
  5756. int (*subi)(void *a, unsigned long b, void *c);
  5757. /** multiply two integers
  5758. @param a The first source integer
  5759. @param b The second source integer
  5760. (single digit of upto bits_per_digit in length)
  5761. @param c The destination of "a * b"
  5762. @return CRYPT_OK on success
  5763. */
  5764. int (*mul)(void *a, void *b, void *c);
  5765. /** multiply two integers
  5766. @param a The first source integer
  5767. @param b The second source integer
  5768. (single digit of upto bits_per_digit in length)
  5769. @param c The destination of "a * b"
  5770. @return CRYPT_OK on success
  5771. */
  5772. int (*muli)(void *a, unsigned long b, void *c);
  5773. /** Square an integer
  5774. @param a The integer to square
  5775. @param b The destination
  5776. @return CRYPT_OK on success
  5777. */
  5778. int (*sqr)(void *a, void *b);
  5779. /** Divide an integer
  5780. @param a The dividend
  5781. @param b The divisor
  5782. @param c The quotient (can be NULL to signify don't care)
  5783. @param d The remainder (can be NULL to signify don't care)
  5784. @return CRYPT_OK on success
  5785. */
  5786. int (*mpdiv)(void *a, void *b, void *c, void *d);
  5787. /** divide by two
  5788. @param a The integer to divide (shift right)
  5789. @param b The destination
  5790. @return CRYPT_OK on success
  5791. */
  5792. int (*div_2)(void *a, void *b);
  5793. /** Get remainder (small value)
  5794. @param a The integer to reduce
  5795. @param b The modulus (upto bits_per_digit in length)
  5796. @param c The destination for the residue
  5797. @return CRYPT_OK on success
  5798. */
  5799. int (*modi)(void *a, unsigned long b, unsigned long *c);
  5800. /** gcd
  5801. @param a The first integer
  5802. @param b The second integer
  5803. @param c The destination for (a, b)
  5804. @return CRYPT_OK on success
  5805. */
  5806. int (*gcd)(void *a, void *b, void *c);
  5807. /** lcm
  5808. @param a The first integer
  5809. @param b The second integer
  5810. @param c The destination for [a, b]
  5811. @return CRYPT_OK on success
  5812. */
  5813. int (*lcm)(void *a, void *b, void *c);
  5814. /** Modular multiplication
  5815. @param a The first source
  5816. @param b The second source
  5817. @param c The modulus
  5818. @param d The destination (a*b mod c)
  5819. @return CRYPT_OK on success
  5820. */
  5821. int (*mulmod)(void *a, void *b, void *c, void *d);
  5822. /** Modular squaring
  5823. @param a The first source
  5824. @param b The modulus
  5825. @param c The destination (a*a mod b)
  5826. @return CRYPT_OK on success
  5827. */
  5828. int (*sqrmod)(void *a, void *b, void *c);
  5829. /** Modular inversion
  5830. @param a The value to invert
  5831. @param b The modulus
  5832. @param c The destination (1/a mod b)
  5833. @return CRYPT_OK on success
  5834. */
  5835. int (*invmod)(void *, void *, void *);
  5836. /* ---- reduction ---- */
  5837. /** setup Montgomery
  5838. @param a The modulus
  5839. @param b The destination for the reduction digit
  5840. @return CRYPT_OK on success
  5841. */
  5842. int (*montgomery_setup)(void *a, void **b);
  5843. /** get normalization value
  5844. @param a The destination for the normalization value
  5845. @param b The modulus
  5846. @return CRYPT_OK on success
  5847. */
  5848. int (*montgomery_normalization)(void *a, void *b);
  5849. /** reduce a number
  5850. @param a The number [and dest] to reduce
  5851. @param b The modulus
  5852. @param c The value "b" from montgomery_setup()
  5853. @return CRYPT_OK on success
  5854. */
  5855. int (*montgomery_reduce)(void *a, void *b, void *c);
  5856. /** clean up (frees memory)
  5857. @param a The value "b" from montgomery_setup()
  5858. @return CRYPT_OK on success
  5859. */
  5860. void (*montgomery_deinit)(void *a);
  5861. /* ---- exponentiation ---- */
  5862. /** Modular exponentiation
  5863. @param a The base integer
  5864. @param b The power (can be negative) integer
  5865. @param c The modulus integer
  5866. @param d The destination
  5867. @return CRYPT_OK on success
  5868. */
  5869. int (*exptmod)(void *a, void *b, void *c, void *d);
  5870. /** Primality testing
  5871. @param a The integer to test
  5872. @param b The number of Miller-Rabin tests that shall be executed
  5873. @param c The destination of the result (FP_YES if prime)
  5874. @return CRYPT_OK on success
  5875. */
  5876. int (*isprime)(void *a, int b, int *c);
  5877. /* ---- (optional) ecc point math ---- */
  5878. /** ECC GF(p) point multiplication (from the NIST curves)
  5879. @param k The integer to multiply the point by
  5880. @param G The point to multiply
  5881. @param R The destination for kG
  5882. @param modulus The modulus for the field
  5883. @param map Boolean indicated whether to map back to affine or not
  5884. (can be ignored if you work in affine only)
  5885. @return CRYPT_OK on success
  5886. */
  5887. int (*ecc_ptmul)( void *k,
  5888. ecc_point *G,
  5889. ecc_point *R,
  5890. void *modulus,
  5891. int map);
  5892. /** ECC GF(p) point addition
  5893. @param P The first point
  5894. @param Q The second point
  5895. @param R The destination of P + Q
  5896. @param modulus The modulus
  5897. @param mp The "b" value from montgomery_setup()
  5898. @return CRYPT_OK on success
  5899. */
  5900. int (*ecc_ptadd)(ecc_point *P,
  5901. ecc_point *Q,
  5902. ecc_point *R,
  5903. void *modulus,
  5904. void *mp);
  5905. /** ECC GF(p) point double
  5906. @param P The first point
  5907. @param R The destination of 2P
  5908. @param modulus The modulus
  5909. @param mp The "b" value from montgomery_setup()
  5910. @return CRYPT_OK on success
  5911. */
  5912. int (*ecc_ptdbl)(ecc_point *P,
  5913. ecc_point *R,
  5914. void *modulus,
  5915. void *mp);
  5916. /** ECC mapping from projective to affine,
  5917. currently uses (x,y,z) => (x/z^2, y/z^3, 1)
  5918. @param P The point to map
  5919. @param modulus The modulus
  5920. @param mp The "b" value from montgomery_setup()
  5921. @return CRYPT_OK on success
  5922. @remark The mapping can be different but keep in mind a
  5923. ecc_point only has three integers (x,y,z) so if
  5924. you use a different mapping you have to make it fit.
  5925. */
  5926. int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
  5927. /** Computes kA*A + kB*B = C using Shamir's Trick
  5928. @param A First point to multiply
  5929. @param kA What to multiple A by
  5930. @param B Second point to multiply
  5931. @param kB What to multiple B by
  5932. @param C [out] Destination point (can overlap with A or B)
  5933. @param modulus Modulus for curve
  5934. @return CRYPT_OK on success
  5935. */
  5936. int (*ecc_mul2add)(ecc_point *A, void *kA,
  5937. ecc_point *B, void *kB,
  5938. ecc_point *C,
  5939. void *modulus);
  5940. /* ---- (optional) rsa optimized math (for internal CRT) ---- */
  5941. /** RSA Key Generation
  5942. @param prng An active PRNG state
  5943. @param wprng The index of the PRNG desired
  5944. @param size The size of the key in octets
  5945. @param e The "e" value (public key).
  5946. e==65537 is a good choice
  5947. @param key [out] Destination of a newly created private key pair
  5948. @return CRYPT_OK if successful, upon error all allocated ram is freed
  5949. */
  5950. int (*rsa_keygen)(prng_state *prng,
  5951. int wprng,
  5952. int size,
  5953. long e,
  5954. rsa_key *key);
  5955. /** RSA exponentiation
  5956. @param in The octet array representing the base
  5957. @param inlen The length of the input
  5958. @param out The destination (to be stored in an octet array format)
  5959. @param outlen The length of the output buffer and the resulting size
  5960. (zero padded to the size of the modulus)
  5961. @param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
  5962. @param key The RSA key to use
  5963. @return CRYPT_OK on success
  5964. */
  5965. int (*rsa_me)(const unsigned char *in, unsigned long inlen,
  5966. unsigned char *out, unsigned long *outlen, int which,
  5967. rsa_key *key);
  5968. /* ---- basic math continued ---- */
  5969. /** Modular addition
  5970. @param a The first source
  5971. @param b The second source
  5972. @param c The modulus
  5973. @param d The destination (a + b mod c)
  5974. @return CRYPT_OK on success
  5975. */
  5976. int (*addmod)(void *a, void *b, void *c, void *d);
  5977. /** Modular substraction
  5978. @param a The first source
  5979. @param b The second source
  5980. @param c The modulus
  5981. @param d The destination (a - b mod c)
  5982. @return CRYPT_OK on success
  5983. */
  5984. int (*submod)(void *a, void *b, void *c, void *d);
  5985. /* ---- misc stuff ---- */
  5986. /** Make a pseudo-random mpi
  5987. @param a The mpi to make random
  5988. @param size The desired length
  5989. @return CRYPT_OK on success
  5990. */
  5991. int (*rand)(void *a, int size);
  5992. } ltc_math_descriptor;
  5993. \end{verbatim}
  5994. \end{small}
  5995. Most of the functions are fairly straightforward and do not need documentation. We'll cover the basic conventions of the API and then explain the accelerated functions.
  5996. \subsection{Conventions}
  5997. All \textit{bignums} are accessed through an opaque \textit{void *} data type. You must internally cast the pointer if you need to access members of your bignum structure. During
  5998. the init calls a \textit{void **} will be passed where you allocate your structure and set the pointer then initialize the number to zero. During the deinit calls you must
  5999. free the bignum as well as the structure you allocated to place it in.
  6000. All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $c \leftarrow ab$.
  6001. All functions (except where noted otherwise) return \textbf{CRYPT\_OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
  6002. The digit routines (including functions with the \textit{i} suffix) use a \textit{unsigned long} to represent the digit. If your internal digit is larger than this you must
  6003. then partition your digits. Normally this does not matter as \textit{unsigned long} will be the same size as your register size. Note that if your digit is smaller
  6004. than an \textit{unsigned long} that is also acceptable as the \textit{bits\_per\_digit} parameter will specify this.
  6005. \subsection{ECC Functions}
  6006. The ECC system in LibTomCrypt is based off of the NIST recommended curves over $GF(p)$ and is used to implement EC-DSA and EC-DH. The ECC functions work with
  6007. the \textbf{ecc\_point} structure and assume the points are stored in Jacobian projective format.
  6008. \begin{verbatim}
  6009. /** A point on a ECC curve, stored in Jacobian format such
  6010. that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */
  6011. typedef struct {
  6012. /** The x co-ordinate */
  6013. void *x;
  6014. /** The y co-ordinate */
  6015. void *y;
  6016. /** The z co-ordinate */
  6017. void *z;
  6018. } ecc_point;
  6019. \end{verbatim}
  6020. All ECC functions must use this mapping system. The only exception is when you remap all ECC callbacks which will allow you to have more control
  6021. over how the ECC math will be implemented. Out of the box you only have three parameters per point to use $(x, y, z)$ however, these are just void pointers. They
  6022. could point to anything you want. The only further exception is the export functions which expects the values to be in affine format.
  6023. \subsubsection{Point Multiply}
  6024. This will multiply the point $G$ by the scalar $k$ and store the result in the point $R$. The value should be mapped to affine only if $map$ is set to one.
  6025. \subsubsection{Point Addition}
  6026. This will add the point $P$ to the point $Q$ and store it in the point $R$. The $mp$ parameter is the \textit{b} value from the montgomery\_setup() call. The input points
  6027. may be in either affine (with $z = 1$) or projective format and the output point is always projective.
  6028. \subsubsection{Point Mapping}
  6029. This will map the point $P$ back from projective to affine. The output point $P$ must be of the form $(x, y, 1)$.
  6030. \subsubsection{Shamir's Trick}
  6031. \index{Shamir's Trick}
  6032. \index{ltc\_ecc\_mul2add()}
  6033. To accelerate EC--DSA verification the library provides a built--in function called ltc\_ecc\_mul2add(). This performs two point multiplications and an addition in
  6034. roughly the time of one point multiplication. It is called from ecc\_verify\_hash() if an accelerator is not present. The acclerator function must allow the points to
  6035. overlap (e.g., $A \leftarrow k_1A + k_2B$) and must return the final point in affine format.
  6036. \subsection{RSA Functions}
  6037. The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
  6038. private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
  6039. \begin{verbatim}
  6040. /** RSA PKCS style key */
  6041. typedef struct Rsa_key {
  6042. /** Type of key, PK_PRIVATE or PK_PUBLIC */
  6043. int type;
  6044. /** The public exponent */
  6045. void *e;
  6046. /** The private exponent */
  6047. void *d;
  6048. /** The modulus */
  6049. void *N;
  6050. /** The p factor of N */
  6051. void *p;
  6052. /** The q factor of N */
  6053. void *q;
  6054. /** The 1/q mod p CRT param */
  6055. void *qP;
  6056. /** The d mod (p - 1) CRT param */
  6057. void *dP;
  6058. /** The d mod (q - 1) CRT param */
  6059. void *dQ;
  6060. } rsa_key;
  6061. \end{verbatim}
  6062. The call reads the \textit{in} buffer as an unsigned char array in big endian format. Then it performs the exponentiation and stores the output in big endian format
  6063. to the \textit{out} buffer. The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes). For example,
  6064. for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
  6065. Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \#1 v2.1 specification.
  6066. \newpage
  6067. \markboth{Index}{Index}
  6068. \input{crypt.ind}
  6069. \end{document}
  6070. % ref: $Format:%D$
  6071. % git commit: $Format:%H$
  6072. % commit time: $Format:%ai$