comparison libtomcrypt/crypt.tex @ 285:1b9e69c058d2

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