11 \def\getsrandom{\stackrel{\rm R}{\gets}}
13 \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
15 \def\divides{\hspace{0.3em} | \hspace{0.3em}}
16 \def\nequiv{\not\equiv}
17 \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
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}
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}}
37 \newcommand{\str}[1]{{\mathbf{#1}}}
45 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
47 \def\gap{\vspace{0.5ex}}
50 \title{A Tiny Crypto Library, \\ LibTomCrypt \\ Version 0.86}
51 \author{Tom St Denis \\
55 http://libtomcrypt.org \\ \\
56 Phone: 1-613-836-3160\\
65 \chapter{Introduction}
66 \section{What is the LibTomCrypt?}
67 LibTomCrypt is a portable ANSI C cryptographic library that supports symmetric ciphers, one-way hashes,
68 pseudo-random number generators, public key cryptography (via RSA,DH or ECC/DH) and a plethora of support
69 routines. It is designed to compile out of the box with the GNU C Compiler (GCC) version 2.95.3 (and higher)
70 and with MSVC version 6 in win32.
72 The library has been successfully tested on quite a few other platforms ranging from the ARM7TDMI in a
73 Gameboy Advanced to various PowerPC processors and even the MIPS processor in the PlayStation 2. Suffice it
74 to say the code is portable.
76 The library is designed so new ciphers/hashes/PRNGs can be added at runtime and the existing API (and helper API functions) will
77 be able to use the new designs automatically. There exist self-check functions for each cipher and hash to ensure that
78 they compile and execute to the published design specifications. The library also performs extensive parameter error checking
79 and will give verbose error messages when possible.
81 Essentially the library saves the time of having to implement the ciphers, hashes, prngs yourself. Typically implementing
82 useful cryptography is an error prone business which means anything that can save considerable time and effort is a good
85 \subsection{What the library IS for?}
87 The library typically serves as a basis for other protocols and message formats. For example, it should be possible to
88 take the RSA routines out of this library, apply the appropriate message padding and get PKCS compliant RSA routines.
89 Similarly SSL protocols could be formed on top of the low-level symmetric cipher functions. The goal of this package is
90 to provide these low level core functions in a robust and easy to use fashion.
92 The library also serves well as a toolkit for applications where they don't need to be OpenPGP, PKCS, etc. compliant.
93 Included are fully operational public key routines for encryption, decryption, signature generation and verification.
94 These routines are fully portable but are not conformant to any known set of standards. They are all based on established
95 number theory and cryptography.
97 \subsection{What the library IS NOT for?}
99 The library is not designed to be in anyway an implementation of the SSL, PKCS, P1363 or OpenPGP standards. The library
100 is not designed to be compliant with any known form of API or programming hierarchy. It is not a port of any other
101 library and it is not platform specific (like the MS CSP). So if you're looking to drop in some buzzword
102 compliant crypto library this is not for you. The library has been written from scratch to provide basic functions as
103 well as non-standard higher level functions.
105 This is not to say that the library is a ``homebrew'' project. All of the symmetric ciphers and one-way hash functions
106 conform to published test vectors. The public key functions are derived from publicly available material and the majority
107 of the code has been reviewed by a growing community of developers.
109 \subsubsection{Why not?}
110 You may be asking why I didn't choose to go all out and support standards like P1363, PKCS and the whole lot. The reason
111 is quite simple too much money gets in the way. When I tried to access the P1363 draft documents and was denied (it
112 requires a password) I realized that they're just a business anyways. See what happens is a company will sit down and
113 invent a ``standard''. Then they try to sell it to as many people as they can. All of a sudden this ``standard'' is
114 everywhere. Then the standard is updated every so often to keep people dependent. Then you become RSA. If people are
115 supposed to support these standards they had better make them more accessible.
117 \section{Why did I write it?}
118 You may be wondering, ``Tom, why did you write a crypto library. I already have one.''. Well the reason falls into
121 \item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
122 \item It was (still is) good coding practice.
125 The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
126 {\bf own} crypto library and hopefully along the way others will appreciate the work.
128 With this library all core functions (ciphers, hashes, prngs) have the {\bf exact} same prototype definition. They all load
129 and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
130 on an x86 with zero problems. The consistent API also means that if you learn how to use blowfish with my library you
131 know how to use Safer+ or RC6 or Serpent or ... as well. With all of the core functions there are central descriptor tables
132 that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime. That means your
133 application can support all ciphers/hashes/prngs without changing the source code.
136 The LibTomCrypt package has also been written to be very modular. The block ciphers, one-way hashes and
137 pseudo-random number generators (PRNG) are all used within the API through ``descriptor'' tables which
138 are essentially structures with pointers to functions. While you can still call particular functions
139 directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
140 usage of the library.
142 For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
143 that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has todo
144 is write a descriptor and the few support routines required for the device. After that the rest of the
145 API can make use of it without change. Similiarly imagine a few years down the road when AES2 (\textit{or whatever they call it}) is
146 invented. It can be added to the library and used within applications with zero modifications to the
147 end applications provided they are written properly.
149 This flexibility within the library means it can be used with any combination of primitive algorithms and
150 unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
151 mode routines for every single cipher. That means every time you add or remove a cipher from the library
152 you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
153 are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
154 the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
155 can make use of the cipher right away.
160 All of the source code except for the following files have been written by the author or donated to the project
161 under the TDCAL license:
168 `mpi.c'' was originally written
169 by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with my LibTomMath library.
170 ``rc2.c'' is based on publicly available code that is not attributed to a person from the given source. ``safer.c''
171 was written by Richard De Moliner (demoliner@isi.ee.ethz.ch) and is public domain.
173 The rest of the code was written either by Tom St Denis or contributed to the project under the ``Tom Doesn't Care
174 About Licenses'' (TDCAL) license. Essentially this license grants the user unlimited distribution and usage (including
175 commercial usage). This means that you can use the package, you can re-distribute the package and even branch it. I
176 still retain ownership over the name of the package. If you want to branch the project you can use the code as a base
177 but you must change the name. The package is also royalty free which means you can use it in commercial products
178 without compensation towards the author. I assume no risk from usage of the code nor do I guarantee it works as
181 \section{Patent Disclosure}
183 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
184 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
185 They can be removed from a build by simply commenting out the two appropriate lines in the makefile script. The rest
186 of the ciphers and hashes are patent free or under patents that have since expired.
188 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
189 the ciphers you just can't advertise that you are doing so.
191 \section{Building the library}
193 To build the library on a GCC equipped platform simply type ``make'' at your command prompt. It will build the library
194 file ``libtomcrypt.a''.
196 To install the library copy all of the ``.h'' files into your ``\#include'' path and the single libtomcrypt.a file into
199 With MSVC you can build the library with ``nmake -f makefile.msvc''. This will produce a ``tomcrypt.lib'' file which
200 is the core library. Copy the header files into your MSVC include path and the library in the lib path (typically
201 under where VC98 is installed).
203 \section{Building against the library}
205 In the recent versions the build steps have changed. The build options are now stored in ``mycrypt\_custom.h'' and
206 no longer in the makefile. If you change a build option in that file you must re-build the library from clean to
207 ensure the build is intact. The perl script ``config.pl'' will help setup the custom header and a custom makefile
208 if you want one (the provided ``makefile'' will work with custom configs).
211 I would like to give thanks to the following people (in no particular order) for helping me develop this project:
213 \item Richard van de Laarschot
214 \item Richard Heathfield
215 \item Ajay K. Agrawal
217 \item Svante Seleborg
220 \item Dobes Vandermeer
221 \item Daniel Richards
225 \item Christopher Imes
228 \chapter{The Application Programming Interface (API)}
229 \section{Introduction}
230 \index{CRYPT\_ERROR} \index{CRYPT\_OK}
232 In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
233 that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful or one of the many error codes
234 if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
235 commented upon. When a function does return a CRYPT error code it can be translated into a string with
238 const char *error_to_string(int errno);
241 An example of handling an error is:
247 /* call a cryptographic function */
248 if ((errno = some_crypto_function(...)) != CRYPT_OK) {
249 printf("A crypto error occured, %s\n", error_to_string(errno));
250 /* perform error handling */
252 /* continue on if no error occured */
256 There is no initialization routine for the library and for the most part the code is thread safe. The only thread
257 related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
258 that is not an issue.
260 To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``mycrypt.h'' like so:
268 The header file ``mycrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and ``mpi.h''
269 (the bignum library routines).
273 There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
274 32/64-bit words in little/big endian format. The macros are:
276 \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L}
277 \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
280 \begin{tabular}{|c|c|c|}
281 \hline STORE32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
282 \hline STORE64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
283 \hline LOAD32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
284 \hline LOAD64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
285 \hline STORE32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
286 \hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
287 \hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
288 \hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
289 \hline BSWAP(x) & {\bf unsigned long} x & Swaps the byte order of x. \\
295 There are 32-bit cyclic rotations as well:
296 \index{ROL} \index{ROR}
298 \begin{tabular}{|c|c|c|}
299 \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y$ \\
300 \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y$ \\
305 \section{Functions with Variable Length Output}
306 Certain functions such as (for example) ``rsa\_export()'' give an output that is variable length. To prevent buffer overflows you
307 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
308 the output will be stored. For example:
314 unsigned char buffer[1024];
318 /* ... Make up the RSA key somehow */
320 /* lets export the key, set x to the size of the output buffer */
322 if ((errno = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
323 printf("Export error: %s\n", error_to_string(errno));
327 /* if rsa_export() was successful then x will have the size of the output */
328 printf("RSA exported key takes %d bytes\n", x);
330 /* ... do something with the buffer */
336 In the above example if the size of the RSA public key was more than 1024 bytes this function would not store anything in
337 either ``buffer'' or ``x'' and simply return an error code. If the function suceeds it stores the length of the output
338 back into ``x'' so that the calling application will know how many bytes used.
340 \section{Functions that need a PRNG}
341 Certain functions such as ``rsa\_make\_key()'' require a PRNG. These functions do not setup the PRNG themselves so it is
342 the responsibility of the calling function to initialize the PRNG before calling them.
344 \section{Functions that use Arrays of Octets}
345 Most functions require inputs that are arrays of the data type ``unsigned char''. Whether it is a symmetric key, IV
346 for a chaining mode or public key packet it is assumed that regardless of the actual size of ``unsigned char'' only the
347 lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine
348 you must pass it in (a pointer to) an array of 32 ``unsigned char'' variables. Certain routines
349 (such as SAFER+) take special care to work properly on platforms where an ``unsigned char'' is not eight bits.
351 For the purposes of this library the term ``byte'' will refer to an octet or eight bit word. Typically an array of
352 type ``byte'' will be synonymous with an array of type ``unsigned char''.
354 \chapter{Symmetric Block Ciphers}
355 \section{Core Functions}
357 Libtomcrypt provides several block ciphers all in a plain vanilla ECB block mode. Its important to first note that you
358 should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode
359 or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
360 the API to grow in a modular fashion.
362 All ciphers store their scheduled keys in a single data type called ``symmetric\_key''. This allows all ciphers to
363 have the same prototype and store their keys as naturally as possible. All ciphers provide five visible functions which
364 are (given that XXX is the name of the cipher):
367 int XXX_setup(const unsigned char *key, int keylen, int rounds,
368 symmetric_key *skey);
371 The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
372 The number of rounds can be set to zero to use the default, which is generally a good idea.
374 If the function returns successfully the variable ``skey'' will have a scheduled key stored in it. Its important to note
375 that you should only used this scheduled key with the intended cipher. For example, if you call
376 ``blowfish\_setup()'' do not pass the scheduled key onto ``rc5\_ecb\_encrypt()''. All setup functions do not allocate
377 memory off the heap so when you are done with a key you can simply discard it (e.g. they can be on the stack).
379 To encrypt or decrypt a block in ECB mode there are these two functions:
380 \index{Cipher Encrypt} \index{Cipher Decrypt}
382 void XXX_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
383 symmetric_key *skey);
385 void XXX_ecb_decrypt(const unsigned char *ct, unsigned char *pt,
386 symmetric_key *skey);
388 These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
389 which cipher you are using.} and store the result where you want it. It is possible that the input and output buffer are
390 the same buffer. For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and ``ct'' is the output.
391 For the decryption function its the opposite. To test a particular cipher against test vectors\footnote{As published in their design papers.} call: \index{Cipher Testing}
395 This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
396 based upon. Finally for each cipher there is a function which will help find a desired key size:
398 int XXX_keysize(int *keysize);
400 Essentially it will round the input keysize in ``keysize'' down to the next appropriate key size. This function
401 return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
409 /* now given a 20 byte key what keysize does Twofish want to use? */
411 if ((errno = twofish_keysize(&keysize)) != CRYPT_OK) {
412 printf("Error getting key size: %s\n", error_to_string(errno));
415 printf("Twofish suggested a key size of %d\n", keysize);
420 This should indicate a keysize of sixteen bytes is suggested. An example snippet that encodes a block with
421 Blowfish in ECB mode is below.
428 unsigned char pt[8], ct[8], key[8];
432 /* ... key is loaded appropriately in ``key'' ... */
433 /* ... load a block of plaintext in ``pt'' ... */
435 /* schedule the key */
436 if ((errno = blowfish_setup(key, 8, 0, &skey)) != CRYPT_OK) {
437 printf("Setup error: %s\n", error_to_string(errno));
441 /* encrypt the block */
442 blowfish_ecb_encrypt(pt, ct, &skey);
444 /* decrypt the block */
445 blowfish_ecb_decrypt(ct, pt, &skey);
452 \section{Key Sizes and Number of Rounds}
453 \index{Symmetric Keys}
454 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
455 keys (mainly for test vectors anyways). Ideally your application should be making at least 256 bit keys. This is not
456 because you're supposed to be paranoid. Its because if your PRNG has a bias of any sort the more bits the better. For
457 example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
458 total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
459 were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
460 only 53 bits of entropy.
462 The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
463 rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
464 ciphers are configured such that the default number of rounds provide adequate security for the given block size.
466 \section{The Cipher Descriptors}
467 \index{Cipher Descriptor}
468 To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_descriptor''. An element
469 of this array has the following format:
472 struct _cipher_descriptor {
474 unsigned long min_key_length, max_key_length,
475 block_length, default_rounds;
476 int (*setup) (const unsigned char *key, int keylength,
477 int num_rounds, symmetric_key *skey);
478 void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct,
480 void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt,
483 int (*keysize) (int *desired_keysize);
487 Where ``name'' is the lower case ASCII version of the name. The fields ``min\_key\_length'', ``max\_key\_length'' and
488 ``block\_length'' are all the number of bytes not bits. As a good rule of thumb it is assumed that the cipher supports
489 the min and max key lengths but not always everything in between. The ``default\_rounds'' field is the default number
490 of rounds that will be used.
492 The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
493 marked when ``name'' equals {\bf NULL}.
495 As of this release the current cipher\_descriptors elements are
499 \begin{tabular}{|c|c|c|c|c|c|}
500 \hline Name & Descriptor Name & Block Size (bytes) & Key Range (bytes) & Rounds \\
501 \hline Blowfish & blowfish\_desc & 8 & 8 ... 56 & 16 \\
502 \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
503 \hline RC2 & rc2\_desc & 8 & 8 .. 128 & 16 \\
504 \hline RC5-32/12/b & rc5\_desc & 8 & 8 ... 128 & 12 ... 24 \\
505 \hline RC6-32/20/b & rc6\_desc & 16 & 8 ... 128 & 20 \\
506 \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
507 \hline Safer K64 & safer\_k64\_desc & 8 & 8 & 6 .. 13 \\
508 \hline Safer SK64 & safer\_sk64\_desc & 8 & 8 & 6 .. 13 \\
509 \hline Safer K128 & safer\_k128\_desc & 8 & 16 & 6 .. 13 \\
510 \hline Safer SK128 & safer\_sk128\_desc & 8 & 16 & 6 .. 13 \\
511 \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
512 \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
513 \hline DES & des\_desc & 8 & 7 & 16 \\
514 \hline 3DES (EDE mode) & des3\_desc & 8 & 21 & 16 \\
515 \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 .. 16 & 12, 16 \\
516 \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
523 For the 64-bit SAFER famliy of ciphers (e.g K64, SK64, K128, SK128) the ecb\_encrypt() and ecb\_decrypt()
524 functions are the same. So if you want to use those functions directly just call safer\_ecb\_encrypt()
525 or safer\_ecb\_decrypt() respectively.
527 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
528 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
529 byte string from the real 7/21 byte key.
531 Note that ``Twofish'' has additional configuration options that take place at build time. These options are found in
532 the file ``mycrypt\_cfg.h''. The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
533 to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
534 key will require less ram but the resulting cipher will be slower. The second option is ``TWOFISH\_TABLES'' which when
535 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
536 by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
537 speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
538 Twofish round function.
542 \begin{tabular}{|l|l|l|}
543 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
544 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
545 \hline undefined & defined & As above, faster keysetup, larger code (1KB more). \\
546 \hline defined & undefined & Very slow, 0.2KB of ram. \\
547 \hline defined & defined & Somewhat faster, 0.2KB of ram, larger code. \\
553 To work with the cipher\_descriptor array there is a function:
555 int find_cipher(char *name)
557 Which will search for a given name in the array. It returns negative one if the cipher is not found, otherwise it returns
558 the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
564 unsigned char key[8];
568 /* you must register a cipher before you use it */
569 if (register_cipher(&blowfish_desc)) == -1) {
570 printf("Unable to register Blowfish cipher.");
574 /* generic call to function (assuming the key in key[] was already setup) */
575 if ((errno = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != CRYPT_OK) {
576 printf("Error setting up Blowfish: %s\n", error_to_string(errno));
580 /* ... use cipher ... */
585 A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function. In order
586 to use a cipher with the descriptor table you must register it first using:
588 int register_cipher(const struct _cipher_descriptor *cipher);
590 Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
591 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
592 than once it will just return the index of the first copy. To remove a cipher call:
594 int unregister_cipher(const struct _cipher_descriptor *cipher);
596 Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}. Consider:
604 /* register the cipher */
605 if (register_cipher(&rijndael_desc) == -1) {
606 printf("Error registering Rijndael\n");
613 if ((errno = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
614 printf("Error removing Rijndael: %s\n", error_to_string(errno));
622 This snippet is a small program that registers only Rijndael only. Note you must register ciphers before
623 using the PK code since all of the PK code (RSA, DH and ECC) rely heavily on the descriptor tables.
625 \section{Symmetric Modes of Operations}
626 \subsection{Background}
627 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
628 size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
629 $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
631 \subsubsection{ECB Mode}
632 ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
636 This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
639 \subsubsection{CBC Mode}
640 CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
643 C_i = E_k(P_i \oplus C_{i - 1})
645 It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
647 \subsubsection{CTR Mode}
648 CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
649 treated as a large binary counter the CTR mode is given as:
651 C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
652 C_i = P_i \oplus E_k(C_{-1})
654 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
655 encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
656 as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
658 \subsubsection{CFB Mode}
659 CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
661 C_i = P_i \oplus C_{-1} \nonumber \\
664 Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
665 to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
666 blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
668 \subsubsection{OFB Mode}
669 OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
671 C_{-1} = E_k(C_{-1}) \nonumber \\
672 C_i = P_i \oplus C_{-1}
674 Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
675 buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
677 \subsection{Choice of Mode}
678 My personal preference is for the CTR mode since it has several key benefits:
680 \item No short cycles which is possible in the OFB and CFB modes.
681 \item Provably as secure as the block cipher being used under a chosen plaintext attack.
682 \item Technically does not require the decryption routine of the cipher.
683 \item Allows random access to the plaintext.
684 \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
686 The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
687 accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
688 block of memory with either of the three modes.
690 The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore they are less flexible than the
693 \subsection{Implementation}
694 \index{CBC Mode} \index{CTR Mode}
695 \index{OFB Mode} \index{CFB Mode}
696 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
697 you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
698 use that mode. They have identical setup routines (except ECB mode for obvious reasons):
700 int XXX_start(int cipher, const unsigned char *IV,
701 const unsigned char *key, int keylen,
702 int num_rounds, symmetric_XXX *XXX);
704 int ecb_start(int cipher, const unsigned char *key, int keylen,
705 int num_rounds, symmetric_ECB *ecb);
708 In each case ``cipher'' is the index into the cipher\_descriptor array of the cipher you want to use. The ``IV'' value is
709 the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
710 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.}
711 of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
712 parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call. The final parameter
713 is a pointer to the structure you want to hold the information for the mode of operation.
715 Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code. To
716 actually encrypt or decrypt the following routines are provided:
718 int XXX_encrypt(const unsigned char *pt, unsigned char *ct,
720 int XXX_decrypt(const unsigned char *ct, unsigned char *pt,
723 int YYY_encrypt(const unsigned char *pt, unsigned char *ct,
724 unsigned long len, symmetric_YYY *YYY);
725 int YYY_decrypt(const unsigned char *ct, unsigned char *pt,
726 unsigned long len, symmetric_YYY *YYY);
728 Where ``XXX'' is one of (ecb, cbc) and ``YYY'' is one of (ctr, ofb, cfb). In the CTR, OFB and CFB cases ``len'' is the
729 size of the buffer (as number of chars) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
730 chunk sensitive. That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
731 and end up with the same ciphertext. However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts. All
732 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
734 To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
735 and use the decrypt routine on all of the blocks. When you are done working with either mode you should wipe the
736 memory (using ``zeromem()'') to help prevent the key from leaking. For example:
743 unsigned char key[16], IV[16], buffer[512];
747 /* register twofish first */
748 if (register_cipher(&twofish_desc) == -1) {
749 printf("Error registering cipher.\n");
753 /* somehow fill out key and IV */
755 /* start up CTR mode */
756 if ((errno = ctr_start(find_cipher("twofish"), IV, key, 16, 0, &ctr)) != CRYPT_OK) {
757 printf("ctr_start error: %s\n", error_to_string(errno));
761 /* somehow fill buffer than encrypt it */
762 if ((errno = ctr_encrypt(buffer, buffer, sizeof(buffer), &ctr)) != CRYPT_OK) {
763 printf("ctr_encrypt error: %s\n", error_to_string(errno));
767 /* make use of ciphertext... */
769 /* clear up and return */
770 zeromem(key, sizeof(key));
771 zeromem(&ctr, sizeof(ctr));
778 \chapter{One-Way Cryptographic Hash Functions}
779 \section{Core Functions}
781 Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_state''.
782 To initialize hash XXX (where XXX is the name) call:
783 \index{Hash Functions}
785 void XXX_init(hash_state *md);
788 This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the
789 message being hashed call:
791 void XXX_process(hash_state *md, const unsigned char *in, unsigned long len);
794 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
795 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
796 (hash output) will be the same. For example, this means that:
798 md5_process(&md, "hello ", 6);
799 md5_process(&md, "world", 5);
801 Will produce the same message digest as the single call:
802 \index{Message Digest}
804 md5_process(&md, "hello world", 11);
807 To finally get the message digest (the hash) call:
809 void XXX_done(hash_state *md,
813 This function will finish up the hash and store the result in the ``out'' array. You must ensure that ``out'' is long
814 enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the ``XXX\_done()'' functions
815 will wipe the ``md'' variable before returning automatically.
817 To test a hash function call:
822 This will return {\bf CRYPTO\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
823 example snippet that hashes a message with md5 is given below.
830 unsigned char *in = "hello world", out[16];
835 /* add the message */
836 md5_process(&md, in, strlen(in));
838 /* get the hash in out[0..15] */
846 \section{Hash Descriptors}
847 \index{Hash Descriptors}
848 Like the set of ciphers the set of hashes have descriptors too. They are stored in an array called ``hash\_descriptor'' and
851 struct _hash_descriptor {
853 unsigned long hashsize; /* digest output size in bytes */
854 unsigned long blocksize; /* the block size the hash uses */
855 void (*init) (hash_state *);
856 void (*process)(hash_state *, const unsigned char *, unsigned long);
857 void (*done) (hash_state *, unsigned char *);
862 Similarly ``name'' is the name of the hash function in ASCII (all lowercase). ``hashsize'' is the size of the digest output
863 in bytes. The remaining fields are pointers to the functions that do the respective tasks. There is a function to
864 search the array as well called ``int find\_hash(char *name)''. It returns -1 if the hash is not found, otherwise the
865 position in the descriptor table of the hash.
867 You can use the table to indirectly call a hash function that is chosen at runtime. For example:
873 unsigned char buffer[100], hash[MAXBLOCKSIZE];
877 /* register hashes .... */
878 if (register_hash(&md5_desc) == -1) {
879 printf("Error registering MD5.\n");
883 /* register other hashes ... */
885 /* prompt for name and strip newline */
886 printf("Enter hash name: \n");
887 fgets(buffer, sizeof(buffer), stdin);
888 buffer[strlen(buffer) - 1] = 0;
891 idx = find_hash(buffer);
893 printf("Invalid hash name!\n");
897 /* hash input until blank line */
898 hash_descriptor[idx].init(&md);
899 while (fgets(buffer, sizeof(buffer), stdin) != NULL)
900 hash_descriptor[idx].process(&md, buffer, strlen(buffer));
901 hash_descriptor[idx].done(&md, hash);
904 for (x = 0; x < hash_descriptor[idx].hashsize; x++)
905 printf("%02x ", hash[x]);
912 Note the usage of ``MAXBLOCKSIZE''. In Libtomcrypt no symmetric block, key or hash digest is larger than MAXBLOCKSIZE in
913 length. This provides a simple size you can set your automatic arrays to that will not get overrun.
915 There are three helper functions as well:
916 \index{hash\_memory()} \index{hash\_file()}
918 int hash_memory(int hash, const unsigned char *data,
919 unsigned long len, unsigned char *dst,
920 unsigned long *outlen);
922 int hash_file(int hash, const char *fname,
924 unsigned long *outlen);
926 int hash_filehandle(int hash, FILE *in,
927 unsigned char *dst, unsigned long *outlen);
930 The ``hash'' parameter is the location in the descriptor table of the hash (\textit{e.g. the return of find\_hash()}).
931 The ``*outlen'' variable is used to keep track of the output size. You
932 must set it to the size of your output buffer before calling the functions. When they complete succesfully they store
933 the length of the message digest back in it. The functions are otherwise straightforward. The ``hash\_filehandle''
934 function assumes that ``in'' is an file handle opened in binary mode. It will hash to the end of file and not reset
935 the file position when finished.
937 To perform the above hash with md5 the following code could be used:
945 unsigned char out[MAXBLOCKSIZE];
947 /* register the hash */
948 if (register_hash(&md5_desc) == -1) {
949 printf("Error registering MD5.\n");
953 /* get the index of the hash */
954 idx = find_hash("md5");
958 if ((errno = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
959 printf("Error hashing data: %s\n", error_to_string(errno));
967 The following hashes are provided as of this release:
969 \begin{tabular}{|c|c|c|}
970 \hline Name & Descriptor Name & Size of Message Digest (bytes) \\
971 \hline SHA-512 & sha512\_desc & 64 \\
972 \hline SHA-384 & sha384\_desc & 48 \\
973 \hline SHA-256 & sha256\_desc & 32 \\
974 \hline TIGER-192 & tiger\_desc & 24 \\
975 \hline SHA-1 & sha1\_desc & 20 \\
976 \hline MD5 & md5\_desc & 16 \\
977 \hline MD4 & md4\_desc & 16 \\
978 \hline MD2 & md2\_desc & 16 \\
983 Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
984 work exactly like those of the cipher registration code. The functions are:
986 int register_hash(const struct _hash_descriptor *hash);
987 int unregister_hash(const struct _hash_descriptor *hash);
991 It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.
992 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
995 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
996 for all purposes you would normally use a hash for.
998 \section{Hash based Message Authenication Codes}
999 Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short. An HMAC
1000 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
1001 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
1002 eavesdropper will not be able to verify the authenticity of a message.
1004 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
1005 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
1006 chars. The initialization routine is:
1008 int hmac_init(hmac_state *hmac, int hash,
1009 const unsigned char *key, unsigned long keylen);
1011 The ``hmac'' parameter is the state for the HMAC code. ``hash'' is the index into the descriptor table of the hash you want
1012 to use to authenticate the message. ``key'' is the pointer to the array of chars that make up the key. ``keylen'' is the
1013 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:
1015 int hmac_process(hmac_state *hmac, const unsigned char *buf,
1018 ``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process. ``len'' is the
1019 number of octets to process. Like the hash process routines you can send the data in arbitrarly sized chunks. When you
1020 are finished with the HMAC process you must call the following function to get the HMAC code:
1022 int hmac_done(hmac_state *hmac, unsigned char *hash);
1024 ``hmac'' is the HMAC state you are working with. ``hash'' is the array of octets where the HMAC code should be stored. You
1025 must ensure that your destination array is the right size (or just make it of size MAXBLOCKSIZE to be sure).
1027 There are two utility functions provided to make using HMACs easier todo. They accept the key and information about the
1028 message (file pointer, address in memory) and produce the HMAC result in one shot. These are useful if you want to avoid
1029 calling the three step process yourself.
1032 int hmac_memory(int hash, const unsigned char *key, unsigned long keylen,
1033 const unsigned char *data, unsigned long len,
1034 unsigned char *dst, unsigned long *dstlen);
1036 This will produce an HMAC code for the array of octets in ``data'' of length ``len''. The index into the hash descriptor
1037 table must be provided in ``hash''. It uses the key from ``key'' with a key length of ``keylen''.
1038 The result is stored in the array of octets ``dst'' and the length in ``dstlen''. The value of ``dstlen'' must be set
1039 to the size of the destination buffer before calling this function. Similarly for files there is the following function:
1041 int hmac_file(int hash, const char *fname, const unsigned char *key,
1042 unsigned long keylen,
1043 unsigned char *dst, unsigned long *dstlen);
1045 ``hash'' is the index into the hash descriptor table of the hash you want to use. ``fname'' is the filename to process.
1046 ``key'' is the array of octets to use as the key of length ``keylen''. ``dst'' is the array of octets where the
1047 result should be stored.
1049 To test if the HMAC code is working there is the following function:
1051 int hmac_test(void);
1053 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
1054 HMAC system is given below.
1058 #include <mycrypt.h>
1063 unsigned char key[16], dst[MAXBLOCKSIZE];
1065 /* register SHA-1 */
1066 if (register_hash(&sha1_desc) == -1) {
1067 printf("Error registering SHA1\n");
1071 /* get index of SHA1 in hash descriptor table */
1072 idx = find_hash("sha1");
1074 /* we would make up our symmetric key in "key[]" here */
1076 /* start the HMAC */
1077 if ((errno = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
1078 printf("Error setting up hmac: %s\n", error_to_string(errno));
1082 /* process a few octets */
1083 if((errno = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
1084 printf("Error processing hmac: %s\n", error_to_string(errno));
1088 /* get result (presumably to use it somehow...) */
1089 if ((errno = hmac_done(&hmac, dst)) != CRYPT_OK) {
1090 printf("Error finishing hmac: %s\n", error_to_string(errno));
1100 \chapter{Pseudo-Random Number Generators}
1101 \section{Core Functions}
1103 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
1104 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)
1105 key generation. There is a universal structure called ``prng\_state''. To initialize a PRNG call:
1107 int XXX_start(prng_state *prng);
1110 This will setup the PRNG for future use and not seed it. In order
1111 for the PRNG to be cryptographically useful you must give it entropy. Ideally you'd have some OS level source to tap
1112 like in UNIX (see section 5.3). To add entropy to the PRNG call:
1114 int XXX_add_entropy(const unsigned char *in, unsigned long len,
1118 Which returns {\bf CRYPTO\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
1119 function to put the entropy into action.
1121 int XXX_ready(prng_state *prng);
1124 Which returns {\bf CRYPTO\_OK} if it is ready. Finally to actually read bytes call:
1126 unsigned long XXX_read(unsigned char *out, unsigned long len,
1130 Which returns the number of bytes read from the PRNG.
1132 \subsection{Remarks}
1134 It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
1135 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
1136 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
1137 checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading.
1139 \subsection{Example}
1141 Below is a simple snippet to read 10 bytes from yarrow. Its important to note that this snippet is {\bf NOT} secure since
1142 the entropy added is not random.
1145 #include <mycrypt.h>
1149 unsigned char buf[10];
1153 if ((errno = yarrow_start(&prng)) != CRYPT_OK) {
1154 printf("Start error: %s\n", error_to_string(errno));
1157 if ((errno = yarrow_add_entropy("hello world", 11, &prng)) != CRYPT_OK) {
1158 printf("Add_entropy error: %s\n", error_to_string(errno));
1160 /* ready and read */
1161 if ((errno = yarrow_ready(&prng)) != CRYPT_OK) {
1162 printf("Ready error: %s\n", error_to_string(errno));
1164 printf("Read %lu bytes from yarrow\n", yarrow_read(buf, 10, &prng));
1169 \section{PRNG Descriptors}
1170 \index{PRNG Descriptor}
1171 PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descriptor''. The format of an element is:
1173 struct _prng_descriptor {
1175 int (*start) (prng_state *);
1176 int (*add_entropy)(const unsigned char *, unsigned long, prng_state *);
1177 int (*ready) (prng_state *);
1178 unsigned long (*read)(unsigned char *, unsigned long len, prng_state *);
1182 There is a ``int find\_prng(char *name)'' function as well. Returns -1 if the PRNG is not found, otherwise it returns
1183 the position in the prng\_descriptor array.
1185 Just like the ciphers and hashes you must register your prng before you can use it. The two functions provided work
1186 exactly as those for the cipher registry functions. They are:
1188 int register_prng(const struct _prng_descriptor *prng);
1189 int unregister_prng(const struct _prng_descriptor *prng);
1192 \subsubsection{PRNGs Provided}
1193 Currently Yarrow (yarrow\_desc), RC4 (rc4\_desc) and the secure RNG (sprng\_desc) are provided as PRNGs within the
1196 RC4 is provided with a PRNG interface because it is a stream cipher and not well suited for the symmetric block cipher
1197 interface. You provide the key for RC4 via the rc4\_add\_entropy() function. By calling rc4\_ready() the key will be used
1198 to setup the RC4 state for encryption or decryption. The rc4\_read() function has been modified from RC4 since it will
1199 XOR the output of the RC4 keystream generator against the input buffer you provide. The following snippet will demonstrate
1200 how to encrypt a buffer with RC4:
1204 #include <mycrypt.h>
1208 unsigned char buf[32];
1211 if ((errno = rc4_start(&prng)) != CRYPT_OK) {
1212 printf("RC4 init error: %s\n", error_to_string(errno));
1216 /* use ``key'' as the key */
1217 if ((errno = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
1218 printf("RC4 add entropy error: %s\n", error_to_string(errno));
1222 /* setup RC4 for use */
1223 if ((errno = rc4_ready(&prng)) != CRYPT_OK) {
1224 printf("RC4 ready error: %s\n", error_to_string(errno));
1228 /* encrypt buffer */
1229 strcpy(buf,"hello world");
1230 if (rc4_read(buf, 11, &prng) != 11) {
1231 printf("RC4 read error\n");
1238 To decrypt you have to do the exact same steps.
1240 \section{The Secure RNG}
1242 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
1243 by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
1244 PRNG. Computers are deterministic beasts that try hard not to stray from pre-determined paths. That makes gathering
1245 entropy needed to seed the PRNG a hard task.
1247 There is one small function that may help on certain platforms:
1248 \index{rng\_get\_bytes()}
1250 unsigned long rng_get_bytes(unsigned char *buf, unsigned long len,
1251 void (*callback)(void));
1254 Which will try one of three methods of getting random data. The first is to open the popular ``/dev/random'' device which
1255 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.}.
1256 The second method is to try the Microsoft Cryptographic Service Provider and read the RNG. The third method is an ANSI C
1257 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
1258 used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of three
1259 bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you don't want to. The function
1260 returns the number of bytes actually read from any RNG source. There is a function to help setup a PRNG as well:
1261 \index{rng\_make\_prng()}
1263 int rng_make_prng(int bits, int wprng, prng_state *prng,
1264 void (*callback)(void));
1266 This will try to setup the prng with a state of at least ``bits'' of entropy. The ``callback'' parameter works much like
1267 the callback in ``rng\_get\_bytes()''. It is highly recommended that you use this function to setup your PRNGs unless you have a
1268 platform where the RNG doesn't work well. Example usage of this function is given below.
1272 #include <mycrypt.h>
1279 /* register yarrow */
1280 if (register_prng(&yarrow_desc) == -1) {
1281 printf("Error registering Yarrow\n");
1285 /* setup the PRNG */
1286 if ((errno = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
1287 printf("Error setting up PRNG, %s\n", error_to_string(errno));
1291 /* make a 192-bit ECC key */
1292 if ((errno = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) {
1293 printf("Error making key: %s\n", error_to_string(errno));
1301 \subsection{The Secure PRNG Interface}
1302 It is possible to access the secure RNG through the PRNG interface and in turn use it within dependent functions such
1303 as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
1304 requires to be started, that is you need not call the start, add\_entropy or ready functions. For example, consider
1305 the previous example using this PRNG.
1309 #include <mycrypt.h>
1315 /* register SPRNG */
1316 if (register_prng(&sprng_desc) == -1) {
1317 printf("Error registering SPRNG\n");
1321 /* make a 192-bit ECC key */
1322 if ((errno = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) != CRYPT_OK) {
1323 printf("Error making key: %s\n", error_to_string(errno));
1331 \chapter{RSA Routines}
1333 \section{Background}
1335 RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown
1336 factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
1337 not strictly equivalent.
1339 The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or ``Euler totient'' of the
1340 multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
1341 $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
1342 $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
1343 often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
1345 A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
1346 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
1347 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
1348 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
1349 can sign a message by ``decrypting'' it. Others can verify it by ``encrypting'' it.
1351 Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
1352 Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
1353 the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
1354 The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
1355 designed for fast exponentiation (requires 16 squarings and one multiplication).
1357 It is important to pad the input to RSA since it has particular mathematical structure. For instance
1358 $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
1359 to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
1360 together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
1361 the hash of documents only but also to pad the inputs with data to remove such structure.
1363 \section{Core Functions}
1365 For RSA routines a single ``rsa\_key'' structure is used. To make a new RSA key call:
1366 \index{rsa\_make\_key()}
1368 int rsa_make_key(prng_state *prng,
1369 int wprng, int size,
1370 long e, rsa_key *key);
1373 Where ``wprng'' is the index into the PRNG descriptor array. ``size'' is the size in bytes of the RSA modulus desired.
1374 ``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537. I suggest you stick with 65537 since its big
1375 enough to prevent trivial math attacks and not super slow. ``key'' is where the key is placed. All keys must be at
1376 least 128 bytes and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
1378 Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you make the key. Make sure to call
1379 ``rsa\_free()'' (see below) when you are finished with the key. If ``rsa\_make\_key()'' fails it will automatically
1380 free the ram allocated itself.
1382 There are three types of RSA keys. The types are {\bf PK\_PRIVATE\_OPTIMIZED}, {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first
1383 two are private keys where the ``optimized'' type uses the Chinese Remainder Theorem to speed up decryption/signatures. By
1384 default all new keys are of the ``optimized'' type. The non-optimized private type is provided for backwards compatibility
1385 as well as to save space since the optimized key requires about four times as much memory.
1387 To do raw work with the RSA function call:
1388 \index{rsa\_exptmod()}
1390 int rsa_exptmod(const unsigned char *in, unsigned long inlen,
1391 unsigned char *out, unsigned long *outlen,
1392 int which, rsa_key *key);
1394 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
1395 in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e''
1396 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
1398 \section{Packet Routines}
1399 To encrypt or decrypt a symmetric key using RSA the following functions are provided. The idea is that you make up
1400 a random symmetric key and use that to encode your message. By RSA encrypting the symmetric key you can send it to a
1401 recipient who can RSA decrypt it and symmetrically decrypt the message.
1403 int rsa_encrypt_key(const unsigned char *inkey, unsigned long inlen,
1404 unsigned char *outkey, unsigned long *outlen,
1405 prng_state *prng, int wprng, rsa_key *key);
1407 This function is used to RSA encrypt a symmetric to share with another user. The symmetric key and its length are
1408 passed as ``inkey'' and ``inlen'' respectively. The symmetric key is limited to a range of 8 to 32 bytes
1409 (\textit{64 to 256 bits}). The RSA encrypted packet is stored in ``outkey'' and will be of length ``outlen'' bytes. The
1410 value of ``outlen'' must be originally set to the size of the output buffer.
1413 int rsa_decrypt_key(const unsigned char *in, unsigned long inlen,
1414 unsigned char *outkey, unsigned long *keylen,
1418 This function will decrypt an RSA packet to retrieve the original symmetric key encrypted with rsa\_encrypt\_key().
1419 Similarly to sign or verify a hash of a message the following two messages are provided. The idea is to hash your message
1420 then use these functions to RSA sign the hash.
1422 int rsa_sign_hash(const unsigned char *in, unsigned long inlen,
1423 unsigned char *out, unsigned long *outlen,
1426 int rsa_verify_hash(const unsigned char *sig, unsigned long siglen,
1427 const unsigned char *hash, int *stat, rsa_key *key);
1429 For ``rsa\_sign\_hash'' the input is intended to be the hash of a message the user wants to sign. The output is the
1430 RSA signed packet which ``rsa\_verify\_hash'' can verify. For the verification function ``sig'' is the RSA signature
1431 and ``hash'' is the hash of the message. The integer ``stat'' is set to non-zero if the signature is valid or zero
1434 To import/export RSA keys as a memory buffer (e.g. to store them to disk) call:
1436 int rsa_export(unsigned char *out, unsigned long *outlen,
1437 int type, rsa_key *key);
1439 int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
1442 The ``type'' parameter is {\bf PK\_PUBLIC}, {\bf PK\_PRIVATE} or {\bf PK\_PRIVATE\_OPTIMIZED} to export either a public or
1443 private key. The latter type will export a key with the optimized parameters. To free the memory used by an RSA key call:
1446 void rsa_free(rsa_key *key);
1449 Note that if the key fails to ``rsa\_import()'' you do not have to free the memory allocated for it.
1452 It is important that you match your RSA key size with the function you are performing. The internal padding for both
1453 signatures and encryption triple the size of the plaintext. This means to encrypt or sign
1454 a message of N bytes you must have a modulus of 1+3N bytes. Note that this doesn't affect the length of the plaintext
1455 you pass into functions like rsa\_encrypt(). This restriction applies only to data that is passed through the
1456 internal RSA routines directly directly.
1458 The following table gives the size requirements for various hashes.
1460 \begin{tabular}{|c|c|c|}
1461 \hline Name & Size of Message Digest (bytes) & RSA Key Size (bits)\\
1462 \hline SHA-512 & 64 & 1544\\
1463 \hline SHA-384 & 48 & 1160 \\
1464 \hline SHA-256 & 32 & 776\\
1465 \hline TIGER-192 & 24 & 584\\
1466 \hline SHA-1 & 20 & 488\\
1467 \hline MD5 & 16 & 392\\
1468 \hline MD4 & 16 & 392\\
1473 The symmetric ciphers will use at a maximum a 256-bit key which means at the least a 776-bit RSA key is
1474 required to use all of the symmetric ciphers with the RSA routines. If you want to use any of the large size
1475 message digests (SHA-512 or SHA-384) you will have to use a larger key. Or to be simple just make 2048-bit or larger
1476 keys. None of the hashes will have problems with such key sizes.
1478 \chapter{Diffie-Hellman Key Exchange}
1480 \section{Background}
1482 Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
1483 of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
1484 generates a large sub-group of prime order (for unique values of $x$).
1486 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
1487 ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
1488 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
1489 a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
1491 From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
1492 $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
1493 $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
1494 the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
1497 It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
1498 discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
1499 modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
1500 $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
1502 To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
1503 the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
1504 smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
1506 \section{Core Functions}
1508 This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
1509 provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
1510 called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first routine is to
1511 make a Diffie-Hellman private key pair:
1512 \index{dh\_make\_key()}
1514 int dh_make_key(prng_state *prng, int wprng,
1515 int keysize, dh_key *key);
1517 The ``keysize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 512 bytes which correspond
1518 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
1519 specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
1520 above 512 it will return an error. So if you pass ``keysize == 32'' it will use a 768 bit key but if you pass
1521 ``keysize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
1522 to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
1523 $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
1524 leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
1527 The next two routines are for exporting/importing Diffie-Hellman keys in a binary format. This is useful for transport
1528 over communication mediums.
1530 \index{dh\_export()} \index{dh\_import()}
1532 int dh_export(unsigned char *out, unsigned long *outlen,
1533 int type, dh_key *key);
1535 int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
1538 These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
1539 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
1542 void dh_free(dh_key *key);
1544 After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
1545 with the other user using:
1546 \index{dh\_shared\_secret()}
1548 int dh_shared_secret(dh_key *private_key,
1550 unsigned char *out, unsigned long *outlen);
1553 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
1554 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
1555 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
1557 \index{dh\_get\_size()}
1559 int dh_get_size(dh_key *key);
1561 This returns the size in bytes of the modulus chosen for that key.
1563 \subsection{Remarks on Usage}
1564 Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
1565 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.}:
1569 int establish_secure_socket(int sock, int mode, unsigned char *key,
1570 prng_state *prng, int wprng)
1572 unsigned char buf[4096], buf2[4096];
1573 unsigned long x, len;
1574 int res, errno, inlen;
1575 dh_key mykey, theirkey;
1577 /* make up our private key */
1578 if ((errno = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK) {
1582 /* export our key as public */
1584 if ((errno = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
1590 /* mode 0 so we send first */
1591 if (send(sock, buf, x, 0) != x) {
1597 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
1602 /* mode >0 so we send second */
1603 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
1608 if (send(sock, buf, x, 0) != x) {
1614 if ((errno = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
1619 /* make shared secret */
1621 if ((errno = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
1627 len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
1628 if ((errno = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
1633 /* clean up and return */
1639 zeromem(buf, sizeof(buf));
1640 zeromem(buf2, sizeof(buf2));
1646 \subsection{Remarks on The Snippet}
1647 When the above code snippet is done (assuming all went well) their will be a shared 128-bit key in the ``key'' array
1648 passed to ``establish\_secure\_socket()''.
1650 \section{Other Diffie-Hellman Functions}
1651 In order to test the Diffie-Hellman function internal workings (e.g. the primes and bases) their is a test function made
1658 This function returns {\bf CRYPT\_OK} if the bases and primes in the library are correct. There is one last helper
1662 void dh_sizes(int *low, int *high);
1664 Which stores the smallest and largest key sizes support into the two variables.
1667 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
1670 int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
1671 unsigned char *out, unsigned long *len,
1672 prng_state *prng, int wprng, int hash,
1675 int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
1676 unsigned char *outkey, unsigned long *keylen,
1679 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
1680 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the
1681 required data is placed in ``out'' by ``dh\_encrypt\_key()''. The hash must produce a message digest at least as large
1682 as the symmetric key you are trying to share.
1684 Similar to the RSA system you can sign and verify a hash of a message.
1686 int dh_sign_hash(const unsigned char *in, unsigned long inlen,
1687 unsigned char *out, unsigned long *outlen,
1688 prng_state *prng, int wprng, dh_key *key);
1690 int dh_verify_hash(const unsigned char *sig, unsigned long siglen,
1691 const unsigned char *hash, unsigned long hashlen,
1692 int *stat, dh_key *key);
1695 The ``dh\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a DH packet in ``out''.
1696 The ``dh\_verify\_hash'' function verifies the DH signature in ``sig'' against the hash in ``hash''. It sets ``stat''
1697 to non-zero if the signature passes or zero if it fails.
1699 \chapter{Elliptic Curve Cryptography}
1701 \section{Background}
1702 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
1703 Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
1704 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
1705 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
1706 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
1708 The curves in this library are taken from the following website:
1710 http://csrc.nist.gov/cryptval/dss.htm
1713 They are all curves over the integers modulo a prime. The curves have the basic equation that is:
1715 y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
1718 The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
1719 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
1720 range in order from $\approx 2^{192}$ points to $\approx 2^{521}$. According to the source document any key size greater
1721 than or equal to 256-bits is sufficient for long term security.
1723 \section{Core Functions}
1725 Like the DH routines there is a key structure ``ecc\_key'' used by the functions. There is a function to make a key:
1726 \index{ecc\_make\_key()}
1728 int ecc_make_key(prng_state *prng, int wprng,
1729 int keysize, ecc_key *key);
1732 The ``keysize'' is the size of the modulus in bytes desired. Currently directly supported values are 20, 24, 28, 32, 48 and 65 bytes which
1733 correspond to key sizes of 160, 192, 224, 256, 384 and 521 bits respectively. If you pass a key size that is between any key size
1734 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.
1735 To free the ram allocated by a key call:
1738 void ecc_free(ecc_key *key);
1741 To import and export a key there are:
1742 \index{ecc\_export()}
1743 \index{ecc\_import()}
1745 int ecc_export(unsigned char *out, unsigned long *outlen,
1746 int type, ecc_key *key);
1748 int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
1750 These two work exactly like there DH counterparts. Finally when you share your public key you can make a shared secret
1752 \index{ecc\_shared\_secret()}
1754 int ecc_shared_secret(ecc_key *private_key,
1755 ecc_key *public_key,
1756 unsigned char *out, unsigned long *outlen);
1758 Which works exactly like the DH counterpart, the ``private\_key'' is your own key and ``public\_key'' is the key the other
1759 user sent you. Note that this function stores both $x$ and $y$ co-ordinates of the shared
1760 elliptic point. You should hash the output to get a shared key in a more compact and useful form (most of the entropy is
1761 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
1763 \index{ecc\_get\_size()}
1765 int ecc_get_size(ecc_key *key);
1768 To test the ECC routines and to get the minimum and maximum key sizes there are these two functions:
1772 void ecc_sizes(int *low, int *high);
1774 Which both work like their DH counterparts.
1776 \section{ECC Packet}
1777 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
1780 int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
1781 unsigned char *out, unsigned long *len,
1782 prng_state *prng, int wprng, int hash,
1785 int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
1786 unsigned char *outkey, unsigned long *keylen,
1790 Where ``inkey'' is an input symmetric key of no more than 32 bytes. Essentially these routines created a random public key
1791 and find the hash of the shared secret. The message digest is than XOR'ed against the symmetric key. All of the required
1792 data is placed in ``out'' by ``ecc\_encrypt\_key()''. The hash chosen must produce a message digest at least as large
1793 as the symmetric key you are trying to share.
1795 There are also functions to sign and verify the hash of a message.
1797 int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
1798 unsigned char *out, unsigned long *outlen,
1799 prng_state *prng, int wprng, ecc_key *key);
1801 int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
1802 const unsigned char *hash, unsigned long hashlen,
1803 int *stat, ecc_key *key);
1806 The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``inlen'' and forms a ECC packet in ``out''.
1807 The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''. It sets ``stat''
1808 to non-zero if the signature passes or zero if it fails.
1811 \section{ECC Keysizes}
1812 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
1813 and in effect the signature will still work. With ECC keys the strength of the signature is limited by the size of
1814 the hash or the size of they key, whichever is smaller. For example, if you sign with SHA256 and a ECC-160 key in effect
1815 you have 160-bits of security (e.g. as if you signed with SHA-1).
1817 The library will not warn you if you make this mistake so it is important to check yourself before using the
1820 \chapter{Public Keyrings}
1821 \section{Introduction}
1822 In order to simplify the usage of the public key algorithms a set of keyring routines have been developed. They let the
1823 developer manage asymmetric keys by providing load, save, export, import routines as well as encrypt, decrypt, sign, verify
1824 routines in a unified API. That is all three types of PK systems can be used within the same keyring with the same API.
1826 To define types of keys there are four enumerations used globaly:
1836 To make use of the system the developer has to know how link-lists work. The main structure that the keyring routines use
1837 is the ``pk\_key'' defined as:
1840 typedef struct Pk_key {
1841 int key_type, /* PUBLIC, PRIVATE, PRIVATE_OPTIMIZED */
1842 system; /* RSA, ECC or DH ? */
1844 char name[MAXLEN], /* various info's about this key */
1846 description[MAXLEN];
1848 unsigned long ID; /* CRC32 of the name/email/description together */
1852 struct Pk_key *next; /* linked list chain */
1857 The list is chained via the ``next'' member and terminated with the node of the list that has ``system'' equal to
1860 \section{The Keyring API}
1861 To initialize a blank keyring the function ``kr\_init()'' is used.
1863 int kr_init(pk_key **pk);
1865 You pass it a pointer to a pointer of type ``pk\_key'' where it will allocate ram for one node of the keyring and sets the
1868 Now instead of calling the PK specific ``make\_key'' functions there is one function that can make all three types of keys.
1870 int kr_make_key(pk_key *pk, prng_state *prng, int wprng,
1871 int system, int keysize, const char *name,
1872 const char *email, const char *description);
1874 The ``name'', ``email'' and ``description'' parameters are simply little pieces of information that you can tag along with a
1875 key. They can each be either blank or any string less than 256 bytes. ``system'' is one of the enumeration elements, that
1876 is {\bf RSA\_KEY}, {\bf DH\_KEY} or {\bf ECC\_KEY}. ``keysize'' is the size of the key you desire which is regulated by
1877 the individual systems, for example, RSA keys are limited in keysize from 128 to 512 bytes.
1879 To find keys along a keyring there are two functions provided:
1881 pk_key *kr_find(pk_key *pk, unsigned long ID);
1883 pk_key *kr_find_name(pk_key *pk, const char *name);
1885 The first searches by the 32-bit ID provided and the latter checks the name against the keyring. They both return a pointer
1886 to the node in the ring of a match or {\bf NULL} if no match is found.
1888 To export or import a single node of a keyring the two functions are provided:
1890 int kr_export(pk_key *pk, unsigned long ID, int key_type,
1891 unsigned char *out, unsigned long *outlen);
1893 int kr_import(pk_key *pk, const unsigned char *in);
1895 The export function exports the key with an ID provided and of a specific type much like the normal PK export routines. The
1896 ``key\_type'' is one of {\bf PK\_PUBLIC} or {\bf PK\_PRIVATE}. In this function with RSA keys the type
1897 {\bf PK\_PRIVATE\_OPTIMIZED} is the same as the {\bf PK\_PRIVATE} type. The import function will read in a packet and
1898 add it to the keyring.
1900 To load and save whole keyrings from disk:
1902 int kr_load(pk_key **pk, FILE *in, symmetric_CTR *ctr);
1904 int kr_save(pk_key *pk, FILE *out, symmetric_CTR *ctr);
1906 Both take file pointers to allow the user to pre-append data to the stream. The ``ctr'' parameter should be setup with
1907 ``ctr\_start'' or set to NULL. This parameter lets the user encrypt the keyring as its written to disk, if it is set
1908 to NULL the data is written without being encrypted. The load function assumes the list has not been initialized yet
1909 and will reset the pointer given to it.
1911 There are the four encrypt, decrypt, sign and verify functions as well
1913 int kr_encrypt_key(pk_key *pk, unsigned long ID,
1914 const unsigned char *in, unsigned long inlen,
1915 unsigned char *out, unsigned long *outlen,
1916 prng_state *prng, int wprng, int hash);
1918 int kr_decrypt_key(pk_key *pk, const unsigned char *in,
1919 unsigned char *out, unsigned long *outlen);
1922 The kr\_encrypt\_key() routine is designed to encrypt a symmetric key with a specified users public key. The symmetric
1923 key is then used with a block cipher to encode the message. The recipient can call kr\_decrypt\_key() to get the original
1924 symmetric key back and decode the message. The hash specified must produce a message digest longer than symmetric key
1928 int kr_sign_hash(pk_key *pk, unsigned long ID,
1929 const unsigned char *in, unsigned long inlen,
1930 unsigned char *out, unsigned long *outlen,
1931 prng_state *prng, int wprng);
1933 int kr_verify_hash(pk_key *pk, const unsigned char *in,
1934 const unsigned char *hash, unsigned long hashlen,
1938 Similar to the two previous these are used to sign a message digest or verify one. This requires hashing the message
1939 first then passing the output in.
1941 To delete keys and clear rings there are:
1943 int kr_del(pk_key **_pk, unsigned long ID);
1944 int kr_clear(pk_key **pk);
1946 ``kr\_del'' will try to remove a key with a given ID from the ring and ``kr\_clear'' will completely empty a list and free
1947 the memory associated with it. Below is small example using the keyring API:
1951 #include <mycrypt.h>
1955 unsigned char buf[4096], buf2[4096];
1959 /* make a new list */
1960 if ((errno = kr_init(&kr)) != CRYPT_OK) {
1961 printf("kr_init: %s\n", error_to_string(errno));
1965 /* add a key to it */
1966 register_prng(&sprng_desc);
1967 if ((errno = kr_make_key(kr, NULL, find_prng("sprng"), RSA_KEY, 128,
1968 "TomBot", "tomstdenis@yahoo.com", "test key")) == CRYPT_OK) {
1969 printf("kr_make_key: %s\n", error_to_string(errno));
1973 /* export the first key */
1975 if ((errno = kr_export(kr, kr->ID, PK_PRIVATE, buf, &len)) != CRYPT_OK) {
1976 printf("kr_export: %s\n", error_to_string(errno));
1985 \chapter{$GF(2^w)$ Math Routines}
1987 The library provides a set of polynomial-basis $GF(2^w)$ routines to help facilitate algorithms such as ECC over such
1988 fields. Note that the current implementation of ECC in the library is strictly over the integers only. The routines
1989 are simple enough to use for other purposes outside of ECC.
1991 At the heart of all of the GF routines is the data type ``gf\_int'. It is simply a type definition for an array of
1992 $L$ 32-bit words. You can configure the maximum size $L$ of the ``gf\_int'' type by opening the file ``mycrypt.h'' and
1993 changing ``LSIZE''. Note that if you set it to $n$ then you can only multiply upto two $n \over 2$ bit polynomials without
1994 an overflow. The type ``gf\_intp'' is associated with a pointer to an ``unsigned long'' as required in the algorithms.
1996 There are no initialization routines for ``gf\_int'' variables and you can simply use them after declaration. There are five
1997 low level functions:
1998 \index{gf\_copy()} \index{gf\_zero()} \index{gf\_iszero()} \index{gf\_isone()}
2001 void gf_copy(gf_intp a, gf_intp b);
2002 void gf_zero(gf_intp a);
2003 int gf_iszero(gf_intp a);
2004 int gf_isone(gf_intp a);
2005 int gf_deg(gf_intp a);
2007 There are all fairly self-explanatory. ``gf\_copy(a, b)'' copies the contents of ``a'' into ``b''. ``gf\_zero()'' simply
2008 zeroes the entire polynomial. ``gf\_iszero()'' tests to see if the polynomial is all zero and ``gf\_isone()'' tests to see
2009 if the polynomial is equal to the multiplicative identity. ``gf\_deg()'' returns the degree of the polynomial or $-1$ if its
2012 There are five core math routines as well:
2013 \index{gf\_shl()} \index{gf\_shr()} \index{gf\_add()} \index{gf\_mul()} \index{gf\_div()}
2015 void gf_shl(gf_intp a, gf_intp b);
2016 void gf_shr(gf_intp a, gf_intp b);
2017 void gf_add(gf_intp a, gf_intp b, gf_intp c);
2018 void gf_mul(gf_intp a, gf_intp b, gf_intp c);
2019 void gf_div(gf_intp a, gf_intp b, gf_intp q, gf_intp r);
2022 Which are all fairly obvious. ``gf\_shl(a,b)'' multiplies the polynomial ``a'' by $x$ and stores it in ``b''.
2023 ``gf\_shl(a,b)'' divides the polynomial ``a'' by $x$ and stores it in ``b''. ``gf\_add(a,b,c)'' adds the polynomial
2024 ``a'' to ``b'' and stores the sum in ``c''. Similarly for ``gf\_mul(a,b,c)''. The ``gf\_div(a,b,q,r)'' function divides
2025 ``a'' by ``b'' and stores the quotient in ``q'' and the remainder in ``r''.
2027 There are six number theoretic functions as well:
2028 \index{gf\_mod()} \index{gf\_mulmod()} \index{gf\_invmod()} \index{gf\_gcd()} \index{gf\_is\_prime()}
2031 void gf_mod(gf_intp a, gf_intp m, gf_intp b);
2032 void gf_mulmod(gf_intp a, gf_intp b, gf_intp m, gf_intp c);
2033 void gf_invmod(gf_intp A, gf_intp M, gf_intp B);
2034 void gf_sqrt(gf_intp a, gf_intp m, gf_intp b);
2035 void gf_gcd(gf_intp A, gf_intp B, gf_intp c);
2036 int gf_is_prime(gf_intp a);
2039 Which all work similarly except for ``gf\_mulmod(a,b,m,c)'' which computes $c = ab\mbox{ }(\mbox{mod }m)$. The
2040 ``gf\_is\_prime()'' function returns one if the polynomial is primitive, otherwise it returns zero.
2042 Finally to read/store a ``gf\_int'' in a binary string use:
2043 \index{gf\_size()} \index{gf\_toraw()} \index{gf\_readraw()}
2045 int gf_size(gf_intp a);
2046 void gf_toraw(gf_intp a, unsigned char *dst);
2047 void gf_readraw(gf_intp a, unsigned char *str, int len);
2049 Where ``gf\_size()'' returns the size in bytes required for the data. ``gf\_toraw(a,b)'' stores the polynomial in ``b''
2050 in binary format (endian neutral). ``gf\_readraw(a,b,c)'' reads the binary string in ``b'' back. Note that the length
2051 you pass it must be the same as returned by ``gf\_size()'' or it will not load correctly.
2053 \chapter{Miscellaneous}
2054 \section{Base64 Encoding and Decoding}
2055 The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it
2056 encodes but the format used does not comply to any known standard. The characters used in the mappings are:
2058 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
2060 Those characters should are supported in virtually any 7-bit ASCII system which means they can be used for transport over
2061 common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
2062 where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
2063 original input. After the first four characters is the rest of the message.
2065 Often it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
2066 put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
2067 break up the first four characters.
2069 To encode a binary string in base64 call:
2070 \index{base64\_encode()} \index{base64\_decode()}
2072 int base64_encode(const unsigned char *in, unsigned long len,
2073 unsigned char *out, unsigned long *outlen);
2075 Where ``in'' is the binary string and ``out'' is where the ASCII output is placed. You must set the value of ``outlen'' prior
2076 to calling this function and it sets the length of the base64 output in ``outlen'' when it is done. To decode a base64
2079 int base64_decode(const unsigned char *in, unsigned long len,
2080 unsigned char *out, unsigned long *outlen);
2083 \section{The Multiple Precision Integer Library (MPI)}
2084 The library comes with a copy of LibTomMath which is a multiple precision integer library written by the
2085 author of LibTomCrypt. LibTomMath is a trivial to use ANSI C compatible large integer library which is free
2086 for all uses and is distributed freely.
2088 At the heart of all the functions is the data type ``mp\_int'' (defined in tommath.h). This data type is what
2089 will hold all large integers. In order to use an mp\_int one must initialize it first, for example:
2091 #include <mycrypt.h> /* mycrypt.h includes mpi.h automatically */
2102 If you are unfamiliar with the syntax of C the \& symbol is used to pass the address of ``bignum'' to the function. All
2103 LibTomMath functions require the address of the parameters. To free the memory of a mp\_int use (for example):
2108 The functions also have the basic form of one of the following:
2111 mp_XXX(mp_int *a, mp_int *b, mp_int *c);
2112 mp_XXX(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
2115 Where they perform some operation and store the result in the mp\_int variable passed on the far right.
2116 For example, to compute $c = a + b \mbox{ }(\mbox{mod }m)$ you would call:
2118 mp_addmod(&a, &b, &m, &c);
2121 \subsection{Binary Forms of ``mp\_int'' Variables}
2123 Often it is required to store a ``mp\_int'' in binary form for transport (e.g. exporting a key, packet
2124 encryption, etc.). LibTomMath includes two functions to help when exporting numbers:
2126 int mp_raw_size(mp_int *num);
2127 mp_toraw(&num, buf);
2130 The former function gives the size in bytes of the raw format and the latter function actually stores the raw data. All
2131 ``mp\_int'' numbers are stored in big endian form (like PKCS demands) with the first byte being the sign of the number. The
2132 ``rsa\_exptmod()'' function differs slightly since it will take the input in the form exactly as PKCS demands (without the
2133 leading sign byte). All other functions include the sign byte (since its much simpler just to include it). The sign byte
2134 must be zero for positive numbers and non-zero for negative numbers. For example,
2139 Represents the integer $255 \cdot 256^2 + 48 \cdot 256^1 + 4 \cdot 256^0$ or 16,723,972.
2141 To read a binary string back into a ``mp\_int'' call:
2143 mp_read_raw(mp_int *num, unsigned char *str, int len);
2145 Where ``num'' is where to store it, ``str'' is the binary string (including the leading sign byte) and ``len'' is the
2146 length of the binary string.
2148 \subsection{Primality Testing}
2149 \index{Primality Testing}
2150 The library includes primality testing and random prime functions as well. The primality tester will perform the test in
2151 two phases. First it will perform trial division by the first few primes. Second it will perform eight rounds of the
2152 Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
2153 composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
2154 the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
2155 $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
2157 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}.
2158 In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candiate
2159 is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
2160 math operations. As a result the routine can scan ahead to the next number required for testing with very little work
2163 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
2164 instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
2165 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
2166 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
2167 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
2168 not equal to $(p - 1)(rs - 1)$.
2170 These are not technically part of the LibTomMath library but this is the best place to document them.
2171 To test if a ``mp\_int'' is prime call:
2173 int is_prime(mp_int *N, int *result);
2175 This puts a one in ``result'' if the number is probably prime, otherwise it places a zero in it. It is assumed that if
2176 it returns an error that the value in ``result'' is undefined. To make
2177 a random prime call:
2179 int rand_prime(mp_int *N, unsigned long len, prng_state *prng, int wprng);
2181 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
2182 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
2183 ``len = -128'' to the function. Upon success it will return {\bf CRYPT\_OK} and ``N'' will contain an integer which
2184 is very likely prime.
2186 \chapter{Programming Guidelines}
2188 \section{Secure Pseudo Random Number Generators}
2189 Probably the singal most vulnerable point of any cryptosystem is the PRNG. Without one generating and protecting secrets
2190 would be impossible. The requirement that one be setup correctly is vitally important and to address this point the library
2191 does provide two RNG sources that will address the largest amount of end users as possible. The ``sprng'' PRNG provided
2192 provides and easy to access source of entropy for any application on a *NIX or Windows computer.
2194 However, when the end user is not on one of these platforms the application developer must address the issue of finding
2195 entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
2196 a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
2198 \section{Preventing Trivial Errors}
2199 Two simple ways to prevent trivial errors is to prevent overflows and to check the return values. All of the functions
2200 which output variable length strings will require you to pass the length of the destination. If the size of your output
2201 buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
2203 Also virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors as simple
2204 typos or such can cause algorithms to fail to work as desired.
2206 \section{Registering Your Algorithms}
2207 To avoid linking and other runtime errors it is important to register the ciphers, hashes and PRNGs you intend to use
2208 before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
2210 A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
2211 having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
2212 write the few functions required plus a descriptor. After registering your PRNG all of the library functions that
2213 need a PRNG can instantly take advantage of it.
2217 \subsection{Symmetric Ciphers}
2218 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
2219 is not a hard thing todo.
2221 \subsection{Assymetric Ciphers}
2222 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
2223 $n$ is estimated to be
2225 e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
2228 Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
2231 \begin{tabular}{|c|c|}
2232 \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
2233 \hline 512 & 63.92 \\
2234 \hline 768 & 76.50 \\
2235 \hline 1024 & 86.76 \\
2236 \hline 1536 & 103.37 \\
2237 \hline 2048 & 116.88 \\
2238 \hline 2560 & 128.47 \\
2239 \hline 3072 & 138.73 \\
2240 \hline 4096 & 156.49 \\
2245 The work factor for ECC keys is much higher since the best attack is still fully exponentional. Given a key of magnitude
2246 $n$ it requires $\sqrt n$ work. The following table sumarizes the work required:
2248 \begin{tabular}{|c|c|}
2249 \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
2255 \hline 521 & 260.5 \\
2260 Using the above tables the following suggestions for key sizes seems appropriate:
2262 \begin{tabular}{|c|c|c|}
2263 \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
2264 \hline Short term (less than a year) & 1024 & 160 \\
2265 \hline Short term (less than five years) & 1536 & 192 \\
2266 \hline Long Term (less than ten years) & 2560 & 256 \\
2271 \section{Thread Safety}
2272 The library is not thread safe but several simple precautions can be taken to avoid any problems. The registry functions
2273 such as register\_cipher() are not thread safe no matter what you do. Its best to call them from your programs initializtion
2274 code before threads are initiated.
2276 The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
2277 thread has its own state variables then they will not affect each other. This is fairly simple with symmetric ciphers
2278 and hashes. However, the keyring and PRNG support is something the threads will want to share. The simplest workaround
2279 is create semaphores or mutexes around calls to those functions.
2281 Since C does not have standard semaphores this support is not native to Libtomcrypt. Even a C based semaphore is not entire
2282 possible as some compilers may ignore the ``volatile'' keyword or have multiple processors. Provide your host application
2283 is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread
2284 safety issues within the library.
2286 \chapter{Configuring the Library}
2287 \section{Introduction}
2288 The library is fairly flexible about how it can be built, used and generally distributed. Additions are being made with
2289 each new release that will make the library even more flexible. Most options are placed in the makefile and others
2290 are in ``mycrypt\_cfg.h''. All are used when the library is built from scratch.
2292 For GCC platforms the file ``makefile'' is the makefile to be used. On MSVC platforms ``makefile.vc'' and on PS2 platforms
2295 \section{mycrypt\_cfg.h}
2296 The file ``mycrypt\_cfg.h'' is what lets you control what functionality you want to remove from the library. By default,
2297 everything the library has to offer it built.
2299 \subsubsection{ARGTYPE}
2300 This lets you control how the \_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
2301 NULL. There are three settings for ARGTYPE. When set to 0 it will have the default behaviour of printing a message to
2302 stderr and raising a SIGABRT signal. This is provided so all platforms that use libtomcrypt can have an error that functions
2303 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
2304 and no error checking will be performed.
2306 \subsubsection{Endianess}
2307 There are five macros related to endianess issues. For little endian platforms define, ENDIAN\_LITTLE. For big endian
2308 platforms define ENDIAN\_BIG. Similarly when the default word size of an ``unsigned long'' is 32-bits define ENDIAN\_32BITWORD
2309 or define ENDIAN\_64BITWORD when its 64-bits. If you do not define any of them the library will automatically use ENDIAN\_NEUTRAL
2310 which will work on all platforms. Currently the system will automatically detect GCC or MSVC on a windows platform as well
2311 as GCC on a PS2 platform.
2313 \section{The Configure Script}
2314 There are also options you can specify from the configure script or ``mycrypt\_config.h''.
2316 \subsubsection{X memory routines}
2317 The makefiles must define three macros denoted as XMALLOC, XCALLOC and XFREE which resolve to the name of the respective
2318 functions. This lets you substitute in your own memory routines. If you substitute in your own functions they must behave
2319 like the standard C library functions in terms of what they expect as input and output. By default the library uses the
2320 standard C routines.
2322 \subsubsection{X clock routines}
2323 The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
2324 the default clock() used with a replacement. By default the standard C library clock() function is used.
2326 \subsubsection{NO\_FILE}
2327 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
2328 functions and instead simply return CRYPT\_ERROR. This should help resolve any linker errors stemming from a lack of
2329 file I/O on embedded platforms.
2331 \subsubsection{CLEAN\_STACK}
2332 When this functions is defined the functions that store key material on the stack will clean up afterwards. Assumes that
2333 you have no memory paging with the stack.
2335 \subsubsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
2336 There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly self-explanatory.
2337 When they are defined the functionality is included otherwise it is not. There are some dependency issues which are
2338 noted in the file. For instance, Yarrow requires CTR chaining mode, a block cipher and a hash function.
2340 \subsubsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
2341 Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
2342 to allow some tradeoffs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
2343 requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
2344 defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
2345 tables at a cost of 4KB of memory. The cipher will be much faster as a result.
2347 When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
2348 useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
2349 will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
2350 it will not speed up the encryption or decryption functions.
2352 \subsubsection{SMALL\_CODE}
2353 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
2354 These variants are slower but can save quite a bit of code space.