www.usr.com/support/gpl/USR9107_release.1.4.tar.gz
[bcm963xx.git] / userapps / opensource / sshd / libtomcrypt / crypt.tex
index 26ad62c..cf1c37e 100755 (executable)
@@ -1,4 +1,4 @@
-\documentclass{book}
+\documentclass[a4paper]{book}
 \usepackage{hyperref}
 \usepackage{makeidx}
 \usepackage{amssymb}
 \def\gap{\vspace{0.5ex}}
 \makeindex
 \begin{document}
-\title{A Tiny Crypto Library, \\ LibTomCrypt \\ Version 0.86}
+\title{LibTomCrypt \\ Version 1.05}
 \author{Tom St Denis \\
-Algonquin College \\
 \\
-tomstdenis@iahu.ca \\
-http://libtomcrypt.org \\ \\
-Phone: 1-613-836-3160\\
-111 Banning Rd \\
-Kanata, Ontario \\
-K2L 1C3 \\
-Canada
+tomstdenis@gmail.com \\
+http://libtomcrypt.org
 }
 \maketitle
-\newpage
-\tableofcontents
-\chapter{Introduction}
-\section{What is the LibTomCrypt?}
-LibTomCrypt is a portable ANSI C cryptographic library that supports symmetric ciphers, one-way hashes, 
-pseudo-random number generators, public key cryptography (via RSA,DH or ECC/DH) and a plethora of support 
-routines.  It is designed to compile out of the box with the GNU C Compiler (GCC) version 2.95.3 (and higher) 
-and with MSVC version 6 in win32.
+This text and source code library are both hereby placed in the public domain.  This book has been 
+formatted for A4 paper using the \LaTeX{} {\em book} macro package.
 
-The library has been successfully tested on quite a few other platforms ranging from the ARM7TDMI in a 
-Gameboy Advanced to various PowerPC processors and even the MIPS processor in the PlayStation 2.  Suffice it
-to say the code is portable.
+\vspace{15cm}
 
-The library is designed so new ciphers/hashes/PRNGs can be added at runtime and the existing API (and helper API functions) will 
-be able to use the new designs automatically.  There exist self-check functions for each cipher and hash to ensure that
-they compile and execute to the published design specifications.  The library also performs extensive parameter error checking
-and will give verbose error messages when possible.
+\begin{flushright}Open Source.  Open Academia.  Open Minds.
 
-Essentially the library saves the time of having to implement the ciphers, hashes, prngs yourself.  Typically implementing
-useful cryptography is an error prone business which means anything that can save considerable time and effort is a good
-thing.
+\mbox{ }
 
-\subsection{What the library IS for?}
+Tom St Denis,
+
+Phone: 1-613-836-3160
+
+111 Banning Rd 
 
-The library typically serves as a basis for other protocols and message formats.  For example, it should be possible to 
-take the RSA routines out of this library, apply the appropriate message padding and get PKCS compliant RSA routines.  
-Similarly SSL protocols could be formed on top  of the low-level symmetric cipher functions.  The goal of this package is 
-to provide these low level core functions in a robust and easy to use fashion.
+Kanata, Ontario 
 
-The library also serves well as a toolkit for applications where they don't need to be OpenPGP, PKCS, etc. compliant.
-Included are fully operational public key routines for encryption, decryption, signature generation and verification.  
-These routines are fully portable but are not conformant to any known set of standards.  They are all based on established
-number theory and cryptography.  
+K2L 1C3 
 
-\subsection{What the library IS NOT for?}
+Canada
+\end{flushright}
+\newpage
+\tableofcontents
+\chapter{Introduction}
+\section{What is the LibTomCrypt?}
+LibTomCrypt is a portable ISO C cryptographic library that is meant to be a toolset for cryptographers who are 
+designing a cryptosystem.  It supports symmetric ciphers, one-way hashes, pseudo-random number generators, 
+public key cryptography (via PKCS \#1 RSA, DH or ECCDH) and a plethora of support 
+routines.  
 
-The library is not designed to be in anyway an implementation of the SSL, PKCS, P1363 or OpenPGP standards.  The library 
-is not designed to be compliant with any known form of API or programming hierarchy.  It is not a port of any other 
-library and it is not platform specific (like the MS CSP).  So if you're looking to drop in some buzzword 
-compliant crypto library this is not for you.  The library has been written from scratch to provide basic functions as 
-well as non-standard higher level functions.  
+The library was designed such that new ciphers/hashes/PRNGs can be added at runtime and the existing API 
+(and helper API functions) are able to use the new designs automatically.  There exists self-check functions for each 
+block cipher and hash function to ensure that they compile and execute to the published design specifications.  The library 
+also performs extensive parameter error checking to prevent any number of runtime exploits or errors.
 
-This is not to say that the library is a ``homebrew'' project.  All of the symmetric ciphers and one-way hash functions
-conform to published test vectors.  The public key functions are derived from publicly available material and the majority
-of the code has been reviewed by a growing community of developers.
+\subsection{What the library IS for?}
 
-\subsubsection{Why not?}
-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
-is quite simple too much money gets in the way.  When I tried to access the P1363 draft documents and was denied (it 
-requires a password) I realized that they're just a business anyways.  See what happens is a company will sit down and
-invent a ``standard''.  Then they try to sell it to as many people as they can.  All of a sudden this ``standard'' is 
-everywhere.  Then the standard is updated every so often to keep people dependent.  Then you become RSA.  If people are 
-supposed to support these standards they had better make them more accessible.
+The library serves as a toolkit for developers who have to solve cryptographic problems.  Out of the box LibTomCrypt
+does not process SSL or OpenPGP messages, it doesn't read x.591 certificates or write PEM encoded data.  It does, however,
+provide all of the tools required to build such functionality.  LibTomCrypt was designed to be a flexible library that 
+was not tied to any particular cryptographic problem.  
 
 \section{Why did I write it?}
 You may be wondering, ``Tom, why did you write a crypto library.  I already have one.''.  Well the reason falls into
@@ -127,24 +109,35 @@ The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or
 
 With this library all core functions (ciphers, hashes, prngs) have the {\bf exact} same prototype definition.  They all load
 and store data in a format independent of the platform.  This means if you encrypt with Blowfish on a PPC it should decrypt
-on an x86 with zero problems.  The consistent API also means that if you learn how to use blowfish with my library you 
+on an x86 with zero problems.  The consistent API also means that if you learn how to use Blowfish with my library you 
 know how to use Safer+ or RC6 or Serpent or ... as well.  With all of the core functions there are central descriptor tables 
 that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime.  That means your 
 application can support all ciphers/hashes/prngs without changing the source code.
 
+Not only did I strive to make a consistent and simple API to work with but I also strived to make the library
+configurable in terms of its build options.  Out of the box the library will build with any modern version of GCC
+without having to use configure scripts.  This means that the library will work with platforms where development
+tools may be limited (e.g. no autoconf).
+
+On top of making the build simple and the API approachable I've also strived for a reasonably high level of
+robustness and efficiency.  LibTomCrypt traps and returns a series of errors ranging from invalid
+arguments to buffer overflows/overruns.  It is mostly thread safe and has been clocked on various platforms
+with ``cycles per byte'' timings that are comparable (and often favourable) to other libraries such as OpenSSL and
+Crypto++.
+
 \subsection{Modular}
-The LibTomCrypt package has also been written to be very modular.  The block ciphers, one-way hashes and
-pseudo-random number generators (PRNG) are all used within the API through ``descriptor'' tables which 
+The LibTomCrypt package has also been written to be very modular.  The block ciphers, one--way hashes and
+pseudo--random number generators (PRNG) are all used within the API through ``descriptor'' tables which 
 are essentially structures with pointers to functions.  While you can still call particular functions
 directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
 usage of the library.
 
 For example, consider a hardware platform with a specialized RNG device.  Obviously one would like to tap
-that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has todo
+that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has to do
 is write a descriptor and the few support routines required for the device.  After that the rest of the 
-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
-invented.  It can be added to the library and used within applications with zero modifications to the
-end applications provided they are written properly.
+API can make use of it without change.  Similiarly imagine a few years down the road when AES2 
+(\textit{or whatever they call it}) has been invented.  It can be added to the library and used within applications 
+with zero modifications to the end applications provided they are written properly.
 
 This flexibility within the library means it can be used with any combination of primitive algorithms and 
 unlike libraries like OpenSSL is not tied to direct routines.  For instance, in OpenSSL there are CBC block
@@ -154,61 +147,35 @@ are not directly tied to the ciphers.  That is a new cipher can be added to the
 the key setup, ECB decrypt and encrypt and test vector routines.  After that all five chaining mode routines
 can make use of the cipher right away.
 
-
 \section{License}
 
 All of the source code except for the following files have been written by the author or donated to the project
-under the TDCAL license:
+under a public domain license:
 
 \begin{enumerate}
    \item rc2.c
-   \item safer.c
 \end{enumerate}
 
-`mpi.c'' was originally written 
-by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with my LibTomMath library.  
-``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.  ``safer.c'' 
-was written by Richard De Moliner (demoliner@isi.ee.ethz.ch) and is public domain.
+`mpi.c'' was originally written by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with 
+my LibTomMath library which is public domain.
+
+``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.  
 
-The rest of the code was written either by Tom St Denis or contributed to the project under the ``Tom Doesn't Care
-About Licenses'' (TDCAL) license.  Essentially this license grants the user unlimited distribution and usage (including
-commercial usage).  This means that you can use the package, you can re-distribute the package and even branch it.  I 
-still retain ownership over the name of the package.  If you want to branch the project you can use the code as a base
-but you must change the name.  The package is also royalty free which means you can use it in commercial products 
-without compensation towards the author.  I assume no risk from usage of the code nor do I guarantee it works as 
-desired or stated.  
+The project is hereby released as public domain.
 
 \section{Patent Disclosure}
 
 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice.  To the best
 of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.  
-They can be removed from a build by simply commenting out the two appropriate lines in the makefile script.  The rest
+They can be removed from a build by simply commenting out the two appropriate lines in ``tomcrypt\_custom.h''.  The rest
 of the ciphers and hashes are patent free or under patents that have since expired.
 
 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations.  This means you can use 
 the ciphers you just can't advertise that you are doing so.  
 
-\section{Building the library}
-
-To build the library on a GCC equipped platform simply type ``make'' at your command prompt.  It will build the library
-file ``libtomcrypt.a''.  
-
-To install the library copy all of the ``.h'' files into your ``\#include'' path and the single libtomcrypt.a file into 
-your library path.
-
-With MSVC you can build the library with ``nmake -f makefile.msvc''.  This will produce a ``tomcrypt.lib'' file which
-is the core library.  Copy the header files into your MSVC include path and the library in the lib path (typically
-under where VC98 is installed).
-
-\section{Building against the library}
-
-In the recent versions the build steps have changed.  The build options are now stored in ``mycrypt\_custom.h'' and
-no longer in the makefile.  If you change a build option in that file you must re-build the library from clean to
-ensure the build is intact.  The perl script ``config.pl'' will help setup the custom header and a custom makefile
-if you want one (the provided ``makefile'' will work with custom configs).
-
 \section{Thanks}
-I would like to give thanks to the following people (in no particular order) for helping me develop this project:
+I would like to give thanks to the following people (in no particular order) for helping me develop this project from
+early on:
 \begin{enumerate}
    \item Richard van de Laarschot
    \item Richard Heathfield
@@ -225,6 +192,9 @@ I would like to give thanks to the following people (in no particular order) for
    \item Christopher Imes
 \end{enumerate}
 
+There have been quite a few other people as well.  Please check the change log to see who else has contributed from
+time to time.
+
 \chapter{The Application Programming Interface (API)}
 \section{Introduction}
 \index{CRYPT\_ERROR} \index{CRYPT\_OK}
@@ -234,19 +204,20 @@ that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful
 if it failed.  Certain functions that return int will return $-1$ to indicate an error.  These functions will be explicitly
 commented upon.  When a function does return a CRYPT error code it can be translated into a string with
 
+\index{error\_to\_string()}
 \begin{verbatim}
-const char *error_to_string(int errno);
+const char *error_to_string(int err);
 \end{verbatim}
 
 An example of handling an error is:
 \begin{verbatim}
 void somefunc(void)
 {
-   int errno;
+   int err;
    
    /* call a cryptographic function */
-   if ((errno = some_crypto_function(...)) != CRYPT_OK) {
-      printf("A crypto error occured, %s\n", error_to_string(errno));
+   if ((err = some_crypto_function(...)) != CRYPT_OK) {
+      printf("A crypto error occured, %s\n", error_to_string(err));
       /* perform error handling */
    }
    /* continue on if no error occured */
@@ -257,24 +228,23 @@ There is no initialization routine for the library and for the most part the cod
 related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads.  Normally
 that is not an issue.
 
-To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``mycrypt.h'' like so:
+To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``tomcrypt.h'' like so:
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void) {
     return 0;
 }
 \end{verbatim}
 
-The header file ``mycrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and ``mpi.h''
-(the bignum library routines).
+The header file ``tomcrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and 
+``ltc\_tommath.h'' (the bignum library routines).
 
 \section{Macros}
 
 There are a few helper macros to make the coding process a bit easier.  The first set are related to loading and storing
 32/64-bit words in little/big endian format.  The macros are:
 
-\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L}
-\index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
+\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
 \begin{small}
 \begin{center}
 \begin{tabular}{|c|c|c|}
@@ -286,18 +256,25 @@ There are a few helper macros to make the coding process a bit easier.  The firs
      \hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
      \hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
      \hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
-     \hline BSWAP(x) & {\bf unsigned long} x & Swaps the byte order of x. \\
+     \hline BSWAP(x) & {\bf unsigned long} x & Swaps byte order (32--bits only) \\
      \hline
 \end{tabular}
 \end{center}
 \end{small}
 
-There are 32-bit cyclic rotations as well:
-\index{ROL} \index{ROR}
+There are 32 and 64-bit cyclic rotations as well:
+\index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c} 
 \begin{center}
 \begin{tabular}{|c|c|c|}
-     \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y$ \\
-     \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y$ \\
+     \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 31$ \\
+     \hline ROLc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 31$ \\
+     \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 31$ \\
+     \hline RORc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 31$ \\
+     \hline && \\
+     \hline ROL64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 63$ \\
+     \hline ROL64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 63$ \\
+     \hline ROR64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 63$ \\
+     \hline ROR64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 63$ \\
      \hline
 \end{tabular}
 \end{center}
@@ -308,19 +285,19 @@ must pass it the length of the buffer\footnote{Extensive error checking is not i
 the output will be stored.  For example:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void) {
     rsa_key key;
     unsigned char buffer[1024];
     unsigned long x;
-    int errno;
+    int err;
 
-    /* ... Make up the RSA key somehow */
+    /* ... Make up the RSA key somehow ... */
 
     /* lets export the key, set x to the size of the output buffer */
     x = sizeof(buffer);
-    if ((errno = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
-       printf("Export error: %s\n", error_to_string(errno));
+    if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
+       printf("Export error: %s\n", error_to_string(err));
        return -1;
     }
     
@@ -333,13 +310,17 @@ int main(void) {
 }
 \end{verbatim}
 \end{small}
-In the above example if the size of the RSA public key was more than 1024 bytes this function would not store anything in
-either ``buffer'' or ``x'' and simply return an error code.  If the function suceeds it stores the length of the output
-back into ``x'' so that the calling application will know how many bytes used.
+In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
+indicating a buffer overflow would have occurred.  If the function succeeds it stores the length of the output
+back into ``x'' so that the calling application will know how many bytes were used.
 
 \section{Functions that need a PRNG}
-Certain functions such as ``rsa\_make\_key()'' require a PRNG.  These functions do not setup the PRNG themselves so it is 
-the responsibility of the calling function to initialize the PRNG before calling them.
+\index{Pseudo Random Number Generator} \index{PRNG}
+Certain functions such as ``rsa\_make\_key()'' require a Pseudo Random Number Generator (PRNG).  These functions do not setup 
+the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
+
+Certain PRNG algorithms do not require a ``prng\_state'' argument (sprng for example).  The ``prng\_state'' argument
+may be passed as \textbf{NULL} in such situations.
 
 \section{Functions that use Arrays of Octets}
 Most functions require inputs that are arrays of the data type ``unsigned char''.  Whether it is a symmetric key, IV
@@ -354,29 +335,32 @@ type ``byte'' will be synonymous with an array of type ``unsigned char''.
 \chapter{Symmetric Block Ciphers}
 \section{Core Functions}
 
-Libtomcrypt provides several block ciphers all in a plain vanilla ECB block mode.  Its important to first note that you 
+LibTomCrypt provides several block ciphers with an ECB block mode interface.  It's important to first note that you 
 should never use the ECB modes directly to encrypt data.  Instead you should use the ECB functions to make a chaining mode
 or use one of the provided chaining modes.  All of the ciphers are written as ECB interfaces since it allows the rest of
 the API to grow in a modular fashion.
 
+\subsection{Key Scheduling}
 All ciphers store their scheduled keys in a single data type called ``symmetric\_key''.  This allows all ciphers to 
-have the same prototype and store their keys as  naturally as possible.  All ciphers provide five visible functions which
-are (given that XXX is the name of the cipher):
+have the same prototype and store their keys as naturally as possible.  This also removes the need for dynamic memory
+allocation and allows you to allocate a fixed sized buffer for storing scheduled keys.  All ciphers provide five visible 
+functions which are (given that XXX is the name of the cipher):
 \index{Cipher Setup}
 \begin{verbatim}
-int XXX_setup(const unsigned char *key, int keylen, int rounds, 
+int XXX_setup(const unsigned char *key, int keylen, int rounds,
               symmetric_key *skey);
 \end{verbatim}
 
 The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
 The number of rounds can be set to zero to use the default, which is generally a good idea.
 
-If the function returns successfully the variable ``skey'' will have a scheduled key stored in it.  Its important to note
-that you should only used this scheduled key with the intended cipher.  For example, if you call 
-``blowfish\_setup()'' do not pass the scheduled key onto ``rc5\_ecb\_encrypt()''.  All setup functions do not allocat
-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).
+If the function returns successfully the variable ``skey'' will have a scheduled key stored in it.  It's important to note
+that you should only used this scheduled key with the intended cipher.  For example, if you call ``blowfish\_setup()'' do not 
+pass the scheduled key onto ``rc5\_ecb\_encrypt()''.  All setup functions do not allocate memory off the heap so when you ar
+done with a key you can simply discard it (e.g. they can be on the stack).
 
-To encrypt or decrypt a block in ECB mode there are these two functions:
+\subsection{ECB Encryption and Decryption}
+To encrypt or decrypt a block in ECB mode there are these two function classes
 \index{Cipher Encrypt} \index{Cipher Decrypt}
 \begin{verbatim}
 void XXX_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
@@ -387,13 +371,20 @@ void XXX_ecb_decrypt(const unsigned char *ct, unsigned char *pt,
 \end{verbatim}
 These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
 which cipher you are using.} and store the result where you want it.  It is possible that the input and output buffer are 
-the same buffer.  For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and ``ct'' is the output.
-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}
+the same buffer.  For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and 
+``ct''\footnote{ct stands for ciphertext.} is the output.  For the decryption function it's the opposite.  To test a particular 
+cipher against test vectors\footnote{As published in their design papers.} call the self-test function
+\subsection{Self--Testing}
+\index{Cipher Testing}
 \begin{verbatim}
 int XXX_test(void);
 \end{verbatim}
 This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is 
-based upon.  Finally for each cipher there is a function which will help find a desired key size:
+based upon.  
+
+\subsection{Key Sizing}
+For each cipher there is a function which will help find a desired key size:
 \begin{verbatim}
 int XXX_keysize(int *keysize);
 \end{verbatim}
@@ -401,15 +392,15 @@ Essentially it will round the input keysize in ``keysize'' down to the next appr
 return {\bf CRYPT\_OK} if the key size specified is acceptable.  For example:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
-   int keysize, errno;
+   int keysize, err;
 
    /* now given a 20 byte key what keysize does Twofish want to use? */
    keysize = 20;
-   if ((errno = twofish_keysize(&keysize)) != CRYPT_OK) {
-      printf("Error getting key size: %s\n", error_to_string(errno));
+   if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
+      printf("Error getting key size: %s\n", error_to_string(err));
       return -1;
    }
    printf("Twofish suggested a key size of %d\n", keysize);
@@ -417,32 +408,58 @@ int main(void)
 }
 \end{verbatim}
 \end{small}
-This should indicate a keysize of sixteen bytes is suggested.  An example snippet that encodes a block with 
-Blowfish in ECB mode is below.
+This should indicate a keysize of sixteen bytes is suggested.  
+
+\subsection{Cipher Termination}
+When you are finished with a cipher you can de--initialize it with the done function.
+\begin{verbatim}
+void XXX_done(symmetric_key *skey);
+\end{verbatim}
+For the software based ciphers within LibTomCrypt this function will not do anything.  However, user supplied
+cipher descriptors may require calls to it for resource management.  To be compliant all functions which call a cipher
+setup function must also call the respective cipher done function when finished.
+
+\subsection{Simple Encryption Demonstration}
+An example snippet that encodes a block with Blowfish in ECB mode is below.
 
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 { 
    unsigned char pt[8], ct[8], key[8];
    symmetric_key skey;
-   int errno;
+   int err;
 
    /* ... key is loaded appropriately in ``key'' ... */
    /* ... load a block of plaintext in ``pt'' ... */
 
    /* schedule the key */
-   if ((errno = blowfish_setup(key, 8, 0, &skey)) != CRYPT_OK) {
-      printf("Setup error: %s\n", error_to_string(errno));
+   if ((err = blowfish_setup(key,     /* the key we will use */
+                               8,     /* key is 8 bytes (64-bits) long */
+                               0,     /* 0 == use default # of rounds */
+                           &skey)     /* where to put the scheduled key */
+       ) != CRYPT_OK) {
+      printf("Setup error: %s\n", error_to_string(err));
       return -1;
    }
 
    /* encrypt the block */
-   blowfish_ecb_encrypt(pt, ct, &skey);
+   blowfish_ecb_encrypt(pt,             /* encrypt this 8-byte array */
+                        ct,             /* store encrypted data here */ 
+                        &skey);         /* our previously scheduled key */
+                        
+   /* now ct holds the encrypted version of pt */                        
 
    /* decrypt the block */
-   blowfish_ecb_decrypt(ct, pt, &skey);
+   blowfish_ecb_decrypt(ct,             /* decrypt this 8-byte array */
+                        pt,             /* store decrypted data here */
+                        &skey);         /* our previously scheduled key */
+
+   /* now we have decrypted ct to the original plaintext in pt */                        
+
+   /* Terminate the cipher context */
+   blowfish_done(&skey);
 
    return 0;
 }
@@ -453,7 +470,7 @@ int main(void)
 \index{Symmetric Keys}
 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
 keys (mainly for test vectors anyways).  Ideally your application should be making at least 256 bit keys.  This is not
-because you're supposed to be paranoid.  Its because if your PRNG has a bias of any sort the more bits the better.  For
+because you're supposed to be paranoid.  It's because if your PRNG has a bias of any sort the more bits the better.  For
 example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
 total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$.  So if $\gamma$
 were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
@@ -461,31 +478,64 @@ only 53 bits of entropy.
 
 The number of rounds of most ciphers is not an option you can change.  Only RC5 allows you to change the number of
 rounds.  By passing zero as the number of rounds all ciphers will use their default number of rounds.  Generally the
-ciphers are configured such that the default number of rounds provide adequate security for the given block size.
+ciphers are configured such that the default number of rounds provide adequate security for the given block and key 
+size.
 
 \section{The Cipher Descriptors}
 \index{Cipher Descriptor}
 To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_descriptor''.  An element
 of this array has the following format:
 
+\begin{small}
 \begin{verbatim}
 struct _cipher_descriptor {
    char *name;
-   unsigned long min_key_length, max_key_length, 
-                 block_length, default_rounds;
-   int  (*setup)      (const unsigned char *key, int keylength, 
-                       int num_rounds, symmetric_key *skey);
-   void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, 
-                       symmetric_key *key);
-   void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt,
-                       symmetric_key *key);
-   int  (*test)       (void);
-   int  (*keysize)    (int *desired_keysize);
+   unsigned char ID;
+   int  min_key_length, 
+        max_key_length, 
+        block_length, 
+        default_rounds;
+   int  (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
+   void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
+   void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
+   int (*test)(void);
+   void (*done)(symmetric_key *skey);      
+   int  (*keysize)(int *keysize);
+
+   void (*accel_ecb_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, 
+                                   unsigned long blocks, symmetric_key *skey);
+   void (*accel_ecb_decrypt)(const unsigned char *ct, 
+                                   unsigned char *pt, 
+                                   unsigned long blocks, symmetric_key *skey);
+   void (*accel_cbc_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, 
+                                   unsigned long blocks, unsigned char *IV, 
+                                   symmetric_key *skey);
+   void (*accel_cbc_decrypt)(const unsigned char *ct, 
+                                   unsigned char *pt, 
+                                   unsigned long blocks, unsigned char *IV, 
+                                   symmetric_key *skey);
+   void (*accel_ctr_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, 
+                                   unsigned long blocks, unsigned char *IV, 
+                                   int mode, symmetric_key *skey);
+   void (*accel_ccm_memory)(
+       const unsigned char *key,    unsigned long keylen,
+       const unsigned char *nonce,  unsigned long noncelen,
+       const unsigned char *header, unsigned long headerlen,
+             unsigned char *pt,     unsigned long ptlen,
+             unsigned char *ct,
+             unsigned char *tag,    unsigned long *taglen,
+                       int  direction);
+
 };
 \end{verbatim}
+\end{small}
 
-Where ``name'' is the lower case ASCII version of the name.  The fields ``min\_key\_length'', ``max\_key\_length'' and
-``block\_length'' are all the number of bytes not bits.  As a good rule of thumb it is assumed that the cipher supports
+Where ``name'' is the lower case ASCII version of the name.  The fields ``min\_key\_length'' and ``max\_key\_length'' 
+are the minimum and maximum key sizes in bytes.  The ``block\_length'' member is the block size of the cipher
+in bytes.  As a good rule of thumb it is assumed that the cipher supports
 the min and max key lengths but not always everything in between.  The ``default\_rounds'' field is the default number
 of rounds that will be used.
 
@@ -494,42 +544,56 @@ marked when ``name'' equals {\bf NULL}.
 
 As of this release the current cipher\_descriptors elements are
 
+\index{Cipher descriptor table}
 \begin{small}
 \begin{center}
 \begin{tabular}{|c|c|c|c|c|c|}
-     \hline Name & Descriptor Name & Block Size (bytes) & Key Range (bytes) & Rounds \\
-     \hline Blowfish & blowfish\_desc & 8 & 8 ... 56 & 16 \\
+     \hline Name & Descriptor Name & Block Size & Key Range & Rounds \\
+     \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
      \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
-     \hline RC2 & rc2\_desc & 8 & 8 .. 128 & 16 \\
-     \hline RC5-32/12/b & rc5\_desc & 8 & 8 ... 128 & 12 ... 24 \\
-     \hline RC6-32/20/b & rc6\_desc & 16 & 8 ... 128 & 20 \\
+     \hline RC2 & rc2\_desc & 8 & 8 $\ldots$ 128 & 16 \\
+     \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
+     \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
      \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
-     \hline Safer K64   & safer\_k64\_desc & 8 & 8 & 6 .. 13 \\
-     \hline Safer SK64  & safer\_sk64\_desc & 8 & 8 & 6 .. 13 \\
-     \hline Safer K128  & safer\_k128\_desc & 8 & 16 & 6 .. 13 \\
-     \hline Safer SK128 & safer\_sk128\_desc & 8 & 16 & 6 .. 13 \\
      \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
+                & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
      \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
      \hline DES & des\_desc & 8 & 7 & 16 \\
      \hline 3DES (EDE mode) & des3\_desc & 8 & 21 & 16 \\
-     \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 .. 16 & 12, 16 \\
+     \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
      \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
+     \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
+     \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
+     \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
      \hline
 \end{tabular}
 \end{center}
 \end{small}
 
 \subsection{Notes}
-For the 64-bit SAFER famliy of ciphers (e.g K64, SK64, K128, SK128) the ecb\_encrypt() and ecb\_decrypt()
-functions are the same.  So if you want to use those functions directly just call safer\_ecb\_encrypt()
-or safer\_ecb\_decrypt() respectively.
-
+\begin{small}
+\begin{enumerate}
+\item
+For AES (also known as Rijndael) there are four descriptors which complicate issues a little.  The descriptors 
+rijndael\_desc and rijndael\_enc\_desc provide the cipher named ``rijndael''.  The descriptors aes\_desc and 
+aes\_enc\_desc provide the cipher name ``aes''.  Functionally both ``rijndael'' and ``aes'' are the same cipher.  The
+only difference is when you call find\_cipher() you have to pass the correct name.  The cipher descriptors with ``enc'' 
+in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
+and tables.  The decryption and self--test function pointers of both ``encrypt only'' descriptors are set to \textbf{NULL} and 
+should not be called.
+
+The ``encrypt only'' descriptors are useful for applications that only use the encryption function of the cipher.  Algorithms such
+as EAX, PMAC and OMAC only require the encryption function.  So far this ``encrypt only'' functionality has only been implemented for
+Rijndael as it makes the most sense for this cipher.
+
+\item
 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
 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
 byte string from the real 7/21 byte key.
 
+\item
 Note that ``Twofish'' has additional configuration options that take place at build time.  These options are found in
-the file ``mycrypt\_cfg.h''.  The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
+the file ``tomcrypt\_cfg.h''.  The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
 to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes.  This means that a scheduled
 key will require less ram but the resulting cipher will be slower.  The second option is ``TWOFISH\_TABLES'' which when
 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
@@ -537,20 +601,25 @@ by the polynomials 5B and EF used in the MDS multiplication.  As a result the co
 speed increase is useful when ``TWOFISH\_SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
 Twofish round function.
 
+\index{Twofish build options}
 \begin{small}
 \begin{center}
 \begin{tabular}{|l|l|l|}
 \hline TWOFISH\_SMALL & TWOFISH\_TABLES & Speed and Memory (per key) \\
 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
-\hline undefined & defined & As above, faster keysetup, larger code (1KB more). \\
+\hline undefined & defined & Faster keysetup, larger code. \\
 \hline defined & undefined & Very slow, 0.2KB of ram. \\
-\hline defined & defined & Somewhat faster, 0.2KB of ram, larger code. \\
+\hline defined & defined & Faster, 0.2KB of ram, larger code. \\
 \hline
 \end{tabular}
 \end{center}
 \end{small}
 
+\end{enumerate}
+\end{small}
+
 To work with the cipher\_descriptor array there is a function:
+\index{find\_cipher()}
 \begin{verbatim}
 int find_cipher(char *name)
 \end{verbatim}
@@ -558,12 +627,12 @@ Which will search for a given name in the array.  It returns negative one if the
 the location in the array where the cipher was found.  For example, to indirectly setup Blowfish you can also use:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    unsigned char key[8];
    symmetric_key skey;
-   int errno;
+   int err;
 
    /* you must register a cipher before you use it */
    if (register_cipher(&blowfish_desc)) == -1) {
@@ -572,8 +641,9 @@ int main(void)
    }
 
    /* generic call to function (assuming the key in key[] was already setup) */
-   if ((errno = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != CRYPT_OK) {
-      printf("Error setting up Blowfish: %s\n", error_to_string(errno));
+   if ((err = cipher_descriptor[find_cipher("blowfish")].setup(key, 8, 0, &skey)) != 
+       CRYPT_OK) {
+      printf("Error setting up Blowfish: %s\n", error_to_string(err));
       return -1;
    }
 
@@ -584,22 +654,24 @@ int main(void)
 
 A good safety would be to check the return value of ``find\_cipher()'' before accessing the desired function.  In order
 to use a cipher with the descriptor table you must register it first using:
+\index{register\_cipher()}
 \begin{verbatim}
 int register_cipher(const struct _cipher_descriptor *cipher);
 \end{verbatim}
 Which accepts a pointer to a descriptor and returns the index into the global descriptor table.  If an error occurs such
 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
 than once it will just return the index of the first copy.  To remove a cipher call:
+\index{unregister\_cipher()}
 \begin{verbatim}
 int unregister_cipher(const struct _cipher_descriptor *cipher);
 \end{verbatim}
 Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}.  Consider:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
-   int errno;
+   int err;
    
    /* register the cipher */
    if (register_cipher(&rijndael_desc) == -1) {
@@ -610,8 +682,8 @@ int main(void)
    /* use Rijndael */
 
    /* remove it */
-   if ((errno = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
-      printf("Error removing Rijndael: %s\n", error_to_string(errno));
+   if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
+      printf("Error removing Rijndael: %s\n", error_to_string(err));
       return -1;
    }
 
@@ -619,8 +691,7 @@ int main(void)
 }
 \end{verbatim}
 \end{small}
-This snippet is a small program that registers only Rijndael only.  Note you must register ciphers before
-using the PK code since all of the PK code (RSA, DH and ECC) rely heavily on the descriptor tables.
+This snippet is a small program that registers only Rijndael only.  
 
 \section{Symmetric Modes of Operations}
 \subsection{Background}
@@ -629,6 +700,7 @@ size of the cipher.  Given a key $k$, a plaintext $P$ and a cipher $E$ we shall
 $P$ under the key $k$ as $E_k(P)$.  In some modes there exists an initial vector denoted as $C_{-1}$.
 
 \subsubsection{ECB Mode}
+\index{ECB mode}
 ECB or Electronic Codebook Mode is the simplest method to use.  It is given as:
 \begin{equation}
 C_i = E_k(P_i)
@@ -637,6 +709,7 @@ This mode is very weak since it allows people to swap blocks and perform replay
 than once.
 
 \subsubsection{CBC Mode}
+\index{CBC mode}
 CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
 It is given as:
 \begin{equation}
@@ -645,6 +718,7 @@ C_i = E_k(P_i \oplus C_{i - 1})
 It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
 
 \subsubsection{CTR Mode}
+\index{CTR mode}
 CTR or Counter Mode is a mode which only uses the encryption function of the cipher.  Given a initial vector which is
 treated as a large binary counter the CTR mode is given as:
 \begin{eqnarray}
@@ -656,6 +730,7 @@ encrypted under the same key replay and swap attacks are infeasible.  CTR mode m
 as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
 
 \subsubsection{CFB Mode}
+\index{CFB mode}
 CFB or Ciphertext Feedback Mode is a mode akin to CBC.  It is given as:
 \begin{eqnarray}
 C_i = P_i \oplus C_{-1} \nonumber \\
@@ -666,6 +741,7 @@ to encrypt whole blocks at a time.  However, the library will buffer data allowi
 blocks without a delay.  When this mode is first setup it will initially encrypt the initial vector as required.
 
 \subsubsection{OFB Mode}
+\index{OFB mode}
 OFB or Output Feedback Mode is a mode akin to CBC as well.  It is given as:
 \begin{eqnarray}
 C_{-1} = E_k(C_{-1}) \nonumber \\
@@ -690,17 +766,24 @@ block of memory with either of the three modes.
 The ECB and CBC modes process blocks of the same size as the cipher at a time.  Therefore they are less flexible than the
 other modes.
 
-\subsection{Implementation}
+\subsection{Initialization}
 \index{CBC Mode} \index{CTR Mode}
 \index{OFB Mode} \index{CFB Mode}
 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages.  Assuming the mode 
 you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
-use that mode.  They have identical setup routines (except ECB mode for obvious reasons):
+use that mode.  They have identical setup routines (except CTR and ECB mode):
+\index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
 \begin{verbatim}
 int XXX_start(int cipher, const unsigned char *IV, 
               const unsigned char *key, int keylen, 
               int num_rounds, symmetric_XXX *XXX);
 
+int ctr_start(               int   cipher,
+              const unsigned char *IV,
+              const unsigned char *key,       int keylen,
+                             int  num_rounds, int ctr_mode,
+                   symmetric_CTR *ctr);
+
 int ecb_start(int cipher, const unsigned char *key, int keylen, 
               int num_rounds, symmetric_ECB *ecb);
 \end{verbatim}
@@ -712,37 +795,73 @@ of the cipher you choose.  It is important that the IV  be random for each uniqu
 parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call.  The final parameter 
 is a pointer to the structure you want to hold the information for the mode of operation.
 
-Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.  To 
-actually encrypt or decrypt the following routines are provided:
+
+In the case of CTR mode there is an additional parameter ``ctr\_mode'' which specifies the mode that the counter is to be used in.
+If \textbf{CTR\_COUNTER\_LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value.  Otherwise, if 
+\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value.
+
+The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.  
+
+\subsection{Encryption and Decryption}
+To actually encrypt or decrypt the following routines are provided:
+\index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()} 
+\index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
 \begin{verbatim}
 int XXX_encrypt(const unsigned char *pt, unsigned char *ct, 
-                symmetric_XXX *XXX);
-int XXX_decrypt(const unsigned char *ct, unsigned char *pt,
-                symmetric_XXX *XXX);
-
-int YYY_encrypt(const unsigned char *pt, unsigned char *ct, 
                 unsigned long len, symmetric_YYY *YYY);
-int YYY_decrypt(const unsigned char *ct, unsigned char *pt, 
+int XXX_decrypt(const unsigned char *ct, unsigned char *pt, 
                 unsigned long len, symmetric_YYY *YYY);
 \end{verbatim}
-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
-size of the buffer (as number of chars) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
+Where ``XXX'' is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.  
+
+In all cases ``len'' is the size of the buffer (as number of octets) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
 chunk sensitive.  That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
 and end up with the same ciphertext.  However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts.  All
 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
 
+In the ECB and CBC cases ``len'' must be a multiple of the ciphers block size.  In the CBC case you must manually pad the end of your message (either with
+zeroes or with whatever your protocol requires).
+
 To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
-and use the decrypt routine on all of the blocks.  When you are done working with either mode you should wipe the 
-memory (using ``zeromem()'') to help prevent the key from leaking.  For example:
+and use the decrypt routine on all of the blocks.
+
+\subsection{IV Manipulation}
+To change or read the IV of a previously initialized chaining mode use the following two functions.
+
+\index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
+\index{ctr\_setiv()} \index{ctr\_getiv()}
+\begin{verbatim}
+int XXX_getiv(unsigned char *IV, unsigned long *len, symmetric_XXX *XXX);
+int XXX_setiv(const unsigned char *IV, unsigned long len, symmetric_XXX *XXX);
+\end{verbatim}
+
+The XXX\_getiv() functions will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV 
+stored in ``len''.  The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified.  The length
+of the IV passed in must be the size of the ciphers block size.
+
+The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.  
+
+\subsection{Stream Termination}
+To terminate an open stream call the done function.
+
+\index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
+\begin{verbatim}
+int XXX_done(symmetric_XXX *XXX);
+\end{verbatim}
+
+This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
+
+\subsection{Examples}
+
 \newpage
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    unsigned char key[16], IV[16], buffer[512];
    symmetric_CTR ctr;
-   int x, errno;
+   int x, err;
 
    /* register twofish first */
    if (register_cipher(&twofish_desc) == -1) {
@@ -753,19 +872,55 @@ int main(void)
    /* somehow fill out key and IV */
 
    /* start up CTR mode */
-   if ((errno = ctr_start(find_cipher("twofish"), IV, key, 16, 0, &ctr)) != CRYPT_OK) {
-      printf("ctr_start error: %s\n", error_to_string(errno));
+   if ((err = ctr_start(
+        find_cipher("twofish"), /* index of desired cipher */
+                            IV, /* the initial vector */
+                           key, /* the secret key */
+                            16, /* length of secret key (16 bytes, 128 bits) */
+                             0, /* 0 == default # of rounds */
+     CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
+                         &ctr)  /* where to store initialized CTR state */
+      ) != CRYPT_OK) {
+      printf("ctr_start error: %s\n", error_to_string(err));
       return -1;
    }
 
    /* somehow fill buffer than encrypt it */
-   if ((errno = ctr_encrypt(buffer, buffer, sizeof(buffer), &ctr)) != CRYPT_OK) {
-      printf("ctr_encrypt error: %s\n", error_to_string(errno));
+   if ((err = ctr_encrypt(        buffer, /* plaintext */
+                                  buffer, /* ciphertext */
+                          sizeof(buffer), /* length of data to encrypt */
+                                   &ctr)  /* previously initialized CTR state */
+      ) != CRYPT_OK) {
+      printf("ctr_encrypt error: %s\n", error_to_string(err));
       return -1;
    }
 
    /* make use of ciphertext... */
 
+   /* now we want to decrypt so let's use ctr_setiv */
+   if ((err = ctr_setiv(  IV, /* the initial IV we gave to ctr_start */
+                          16, /* the IV is 16 bytes long */
+                        &ctr) /* the ctr state we wish to modify */
+       ) != CRYPT_OK) {
+      printf("ctr_setiv error: %s\n", error_to_string(err));
+      return -1;
+   }
+
+   if ((err = ctr_decrypt(        buffer, /* ciphertext */
+                                  buffer, /* plaintext */
+                          sizeof(buffer), /* length of data to encrypt */
+                                   &ctr)  /* previously initialized CTR state */
+      ) != CRYPT_OK) {
+      printf("ctr_decrypt error: %s\n", error_to_string(err));
+      return -1;
+   }
+
+   /* terminate the stream */
+   if ((err = ctr_done(&ctr)) != CRYPT_OK) {
+      printf("ctr_done error: %s\n", error_to_string(err));
+      return -1;
+   }
+
    /* clear up and return */
    zeromem(key, sizeof(key));
    zeromem(&ctr, sizeof(ctr));
@@ -775,6 +930,501 @@ int main(void)
 \end{verbatim}
 \end{small}
 
+\section{Encrypt and Authenticate Modes}
+
+\subsection{EAX Mode}
+LibTomCrypt provides support for a mode called EAX\footnote{See 
+M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the
+way it was intended to be used by the designers.  First a short description of what EAX mode is before I explain how to use it.  
+EAX is a mode that requires a cipher, CTR and OMAC support and provides encryption and authentication\footnote{Note that since EAX only requires OMAC and CTR you may use ``encrypt only'' cipher descriptors with this mode.}.  
+It is initialized with a random ``nonce'' that can be shared publicly as well as a ``header'' which can be fixed and public as well as a random 
+secret symmetric key.
+
+The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages).  It can
+be added at anytime during an EAX stream and is part of the authentication tag.  That is, changes in the meta-data can
+be detected by changes in the output tag.
+
+The mode can then process plaintext producing ciphertext as well as compute a partial checksum.  The actual checksum
+called a ``tag'' is only emitted when the message is finished.  In the interim though the user can process any arbitrary
+sized message block to send to the recipient as ciphertext.  This makes the EAX mode especially suited for streaming modes
+of operation.
+
+The mode is initialized with the following function.
+\index{eax\_init()}
+\begin{verbatim}
+int eax_init(eax_state *eax, int cipher, 
+             const unsigned char *key, unsigned long keylen,
+             const unsigned char *nonce, unsigned long noncelen,
+             const unsigned char *header, unsigned long headerlen);
+\end{verbatim}
+
+Where ``eax'' is the EAX state.  ``cipher'' is the index of the desired cipher in the descriptor table.  
+``key'' is the shared secret symmetric key of length ``keylen''.  ``nonce'' is the random public string of
+length ``noncelen''.  ``header'' is the random (or fixed or \textbf{NULL}) header for the message of length
+``headerlen''.
+
+When this function completes ``eax'' will be initialized such that you can now either have data decrypted or 
+encrypted in EAX mode.  Note that if ``headerlen'' is zero you may pass ``header'' as \textbf{NULL} to indicate
+there is no initial header data.
+
+To encrypt or decrypt data in a streaming mode use the following.
+\index{eax\_encrypt()} \index{eax\_decrypt()}
+\begin{verbatim}
+int eax_encrypt(eax_state *eax, const unsigned char *pt, 
+                unsigned char *ct, unsigned long length);
+
+int eax_decrypt(eax_state *eax, const unsigned char *ct, 
+                unsigned char *pt, unsigned long length);
+\end{verbatim}
+The function ``eax\_encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in
+``ct''.  Note that ``ct'' and ``pt'' may be the same region in memory.   This function will also send the ciphertext
+through the OMAC function.  The function ``eax\_decrypt'' decrypts ``ct'' and stores it in ``pt''.  This also allows 
+``pt'' and ``ct'' to be the same region in memory.  
+
+You cannot both encrypt or decrypt with the same ``eax'' context.  For bi-directional communication you
+will need to initialize two EAX contexts (preferably with different headers and nonces).  
+
+Note that both of these functions allow you to send the data in any granularity but the order is important.  While
+the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
+EAX stream with the following.
+
+\index{eax\_addheader()}
+\begin{verbatim}
+int eax_addheader(eax_state *eax, 
+                  const unsigned char *header, unsigned long length);
+\end{verbatim}
+
+This will add the ``length'' bytes from ``header'' to the given ``eax'' stream.  Once the message is finished the 
+``tag'' (checksum) may be computed with the following function.
+
+\index{eax\_done()}
+\begin{verbatim}
+int eax_done(eax_state *eax, 
+             unsigned char *tag, unsigned long *taglen);
+\end{verbatim}
+This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''.  The function
+then stores how many bytes of the tag were written out back into ``taglen''.
+
+The EAX mode code can be tested to ensure it matches the test vectors by calling the following function.
+\index{eax\_test()}
+\begin{verbatim}
+int eax_test(void);
+\end{verbatim}
+This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
+
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   int           err;
+   eax_state     eax;
+   unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
+   unsigned long taglen;
+
+   if (register_cipher(&rijndael_desc) == -1) {
+      printf("Error registering Rijndael");
+      return EXIT_FAILURE;
+   }
+
+   /* ... make up random nonce and key ... */
+
+   /* initialize context */
+   if ((err = eax_init(            &eax,  /* the context */
+                find_cipher("rijndael"),  /* cipher we want to use */
+                                  nonce,  /* our state nonce */
+                                     16,  /* none is 16 bytes */
+                              "TestApp",  /* example header, identifies this program */
+                                      7)  /* length of the header */
+       ) != CRYPT_OK) {
+      printf("Error eax_init: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* now encrypt data, say in a loop or whatever */
+   if ((err = eax_encrypt(     &eax,      /* eax context */
+                                 pt,      /* plaintext  (source) */
+                                 ct,      /* ciphertext (destination) */
+                          sizeof(pt)      /* size of plaintext */
+      ) != CRYPT_OK) {
+      printf("Error eax_encrypt: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* finish message and get authentication tag */
+   taglen = sizeof(tag);
+   if ((err = eax_done(   &eax,           /* eax context */
+                           tag,           /* where to put tag */
+                       &taglen            /* length of tag space */
+      ) != CRYPT_OK) {
+      printf("Error eax_done: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* now we have the authentication tag in "tag" and it's taglen bytes long */
+
+}
+\end{verbatim}
+                       
+You can also perform an entire EAX state on a block of memory in a single function call with the 
+following functions.
+
+
+\index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
+\begin{verbatim}
+int eax_encrypt_authenticate_memory(int cipher,
+    const unsigned char *key,    unsigned long keylen,
+    const unsigned char *nonce,  unsigned long noncelen,
+    const unsigned char *header, unsigned long headerlen,
+    const unsigned char *pt,     unsigned long ptlen,
+          unsigned char *ct,
+          unsigned char *tag,    unsigned long *taglen);
+
+int eax_decrypt_verify_memory(int cipher,
+    const unsigned char *key,    unsigned long keylen,
+    const unsigned char *nonce,  unsigned long noncelen,
+    const unsigned char *header, unsigned long headerlen,
+    const unsigned char *ct,     unsigned long ctlen,
+          unsigned char *pt,
+          unsigned char *tag,    unsigned long taglen,
+          int           *res);
+\end{verbatim}
+
+Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done().  The parameters
+have the same meaning as with those respective functions.  
+
+The only difference is eax\_decrypt\_verify\_memory() does not emit a tag.  Instead you pass it a tag as input and it compares it against
+the tag it computed while decrypting the message.  If the tags match then it stores a $1$ in ``res'', otherwise it stores a $0$.
+
+\subsection{OCB Mode}
+LibTomCrypt provides support for a mode called OCB\footnote{See 
+P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.}
+.  OCB is an encryption protocol that simultaneously provides authentication.  It is slightly faster to use than EAX mode
+but is less flexible.  Let's review how to initialize an OCB context.
+
+\index{ocb\_init()}
+\begin{verbatim}
+int ocb_init(ocb_state *ocb, int cipher, 
+             const unsigned char *key, unsigned long keylen, 
+             const unsigned char *nonce);
+\end{verbatim}
+
+This will initialize the ``ocb'' context using cipher descriptor ``cipher''.  It will use a ``key'' of length ``keylen''
+and the random ``nonce''.  Note that ``nonce'' must be a random (public) string the same length as the block ciphers
+block size (e.g. 16 bytes for AES).
+
+This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream.
+To encrypt or decrypt data use the following.
+
+\index{ocb\_encrypt()} \index{ocb\_decrypt()}
+\begin{verbatim}
+int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
+int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
+\end{verbatim}
+
+This will encrypt (or decrypt for the latter) a fixed length of data from ``pt'' to ``ct'' (vice versa for the latter).  
+They assume that ``pt'' and ``ct'' are the same size as the block cipher's block size.  Note that you cannot call 
+both functions given a single ``ocb'' state.  For bi-directional communication you will have to initialize two ``ocb''
+states (with different nonces).  Also ``pt'' and ``ct'' may point to the same location in memory.
+
+\subsubsection{State Termination}
+
+When you are finished encrypting the message you call the following function to compute the tag.
+
+\index{ocb\_done\_encrypt()}
+\begin{verbatim}
+int ocb_done_encrypt(ocb_state *ocb, 
+                     const unsigned char *pt, unsigned long ptlen,
+                           unsigned char *ct, 
+                           unsigned char *tag, unsigned long *taglen);
+\end{verbatim}
+
+This will terminate an encrypt stream ``ocb''.  If you have trailing bytes of plaintext that will not complete a block 
+you can pass them here.  This will also encrypt the ``ptlen'' bytes in ``pt'' and store them in ``ct''.  It will also
+store upto ``taglen'' bytes of the tag into ``tag''.
+
+Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen.  Also note that if you have 
+an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.  
+
+To terminate a decrypt stream and compared the tag you call the following.
+
+\index{ocb\_done\_decrypt()}
+\begin{verbatim}
+int ocb_done_decrypt(ocb_state *ocb, 
+                     const unsigned char *ct,  unsigned long ctlen,
+                           unsigned char *pt, 
+                     const unsigned char *tag, unsigned long taglen, 
+                           int *res);
+\end{verbatim}
+
+Similarly to the previous function you can pass trailing message bytes into this function.  This will compute the 
+tag of the message (internally) and then compare it against the ``taglen'' bytes of ``tag'' provided.  By default
+``res'' is set to zero.  If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
+message).
+
+\subsubsection{Packet Functions}
+To make life simpler the following two functions are provided for memory bound OCB.
+
+\index{ocb\_encrypt\_authenticate\_memory()}
+\begin{verbatim}
+int ocb_encrypt_authenticate_memory(int cipher,
+    const unsigned char *key,    unsigned long keylen,
+    const unsigned char *nonce,  
+    const unsigned char *pt,     unsigned long ptlen,
+          unsigned char *ct,
+          unsigned char *tag,    unsigned long *taglen);
+\end{verbatim}
+
+This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''.  The length ``ptlen''
+can be any arbitrary length.  
+
+\index{ocb\_decrypt\_verify\_memory()}
+\begin{verbatim}
+int ocb_decrypt_verify_memory(int cipher,
+    const unsigned char *key,    unsigned long keylen,
+    const unsigned char *nonce,  
+    const unsigned char *ct,     unsigned long ctlen,
+          unsigned char *pt,
+    const unsigned char *tag,    unsigned long taglen,
+          int           *res);
+\end{verbatim}
+
+Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set 
+appropriately.
+
+\subsection{CCM Mode}
+CCM is a NIST proposal for Encrypt+Authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.  Unlike EAX and OCB mode
+it is only meant for ``packet'' mode where the length of the input is known in advance.  Since it is a packet mode function CCM only has one 
+function that performs the protocol.
+
+\index{ccm\_memory()}
+\begin{verbatim}
+int ccm_memory(int cipher,
+    const unsigned char *key,    unsigned long keylen,
+    const unsigned char *nonce,  unsigned long noncelen,
+    const unsigned char *header, unsigned long headerlen,
+          unsigned char *pt,     unsigned long ptlen,
+          unsigned char *ct,
+          unsigned char *tag,    unsigned long *taglen,
+                    int  direction);
+\end{verbatim}
+
+This performs the ``CCM'' operation on the data.  The ``cipher'' variable indicates which cipher in the descriptor table to use.  It must have a 
+16--byte block size for CCM.  The key is ``key'' with a length of ``keylen'' octets.  The nonce or salt is ``nonce'' of
+length ``noncelen'' octets.  The header is meta--data you want to send with the message but not have encrypted, it is stored in ``header''
+of length ``headerlen'' octets.  The header can be zero octets long (if $headerlen = 0$ then you can pass ``header'' as \textbf{NULL}).  
+
+The plaintext is stored in ``pt'' and the ciphertext in ``ct''.  The length of both are expected to be equal and is passed in as ``ptlen''.  It is
+allowable that $pt = ct$.  The ``direction'' variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or 
+decryption (direction $=$ \textbf{CCM\_DECRYPT}) is to be performed.
+
+As implemented this copy of CCM cannot handle a header or plaintext longer than $2^{32} - 1$ octets long.  
+
+You can test the implementation of CCM with the following function.
+
+\index{ccm\_test()}
+\begin{verbatim}
+int ccm_test(void);
+\end{verbatim}
+
+This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors.
+
+\subsection{GCM Mode}
+Galois counter mode is an IEEE proposal for authenticated encryption.  Like EAX and OCB it can be used in a streaming capacity however, unlike EAX it cannot
+accept ``additional authentication data'' (meta--data) after plaintext has been processed.  This mode also only works with block ciphers with a sixteen
+byte block.
+
+A GCM stream is meant to be processed in three modes each one sequential serial.  First the initial vector (per session) data is processed.  This should be 
+unique to every session.  Next the the optional additional authentication data is processed and finally the plaintext.  
+
+\subsubsection{Initialization}
+To initialize the GCM context with a secret key call the following function.
+
+\index{gcm\_init()}
+\begin{verbatim}
+int gcm_init(gcm_state *gcm, int cipher,
+             const unsigned char *key, int keylen);
+\end{verbatim}
+This initializes the GCM state ``gcm'' for the given cipher indexed by ``cipher'' with a secret key ``key'' of length ``keylen'' octets.  The cipher chosen
+must have a 16--byte block size (e.g. AES).  
+
+\subsubsection{Initial Vector}
+After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector.  It should be unique per packet encrypted.
+
+\index{gcm\_add\_iv()}
+\begin{verbatim}
+int gcm_add_iv(gcm_state *gcm, 
+               const unsigned char *IV,     unsigned long IVlen);
+\end{verbatim}
+
+This adds the initial vector octets from ``IV'' of length ``IVlen'' to the GCM state ``gcm''.  You can call this function as many times as required
+to process the entire IV.  
+
+Note that the GCM protocols provides a ``shortcut'' for 12--byte IVs where no preprocessing is to be done.  If you want to minimize per packet latency it's ideal
+to only use 12--byte IVs.  You can just increment it like a counter for each packet and the CTR [privacy] will be ensured.
+
+\subsubsection{Additional Authentication Data}
+After the entire IV has been processed the additional authentication data can be processed.  Unlike the IV a packet/session does not require additional
+authentication data (AAD) for security.  The AAD is meant to be used as side--channel data you want to be authenticated with the packet.  Note that once
+you begin adding AAD to the GCM state you cannot return to adding IV data until the state is reset.
+
+\index{gcm\_add\_aad()}
+\begin{verbatim}
+int gcm_add_aad(gcm_state *gcm, 
+               const unsigned char *adata,     unsigned long adatalen);
+\end{verbatim}
+This adds the additional authentication data ``adata'' of length ``adatalen'' to the GCM state ``gcm''.
+
+\subsubsection{Plaintext Processing}
+After the AAD has been processed the plaintext (or ciphertext depending on the direction) can be processed.  
+
+\index{gcm\_process()}
+\begin{verbatim}
+int gcm_process(gcm_state *gcm,
+                     unsigned char *pt,     unsigned long ptlen,
+                     unsigned char *ct,
+                     int direction);
+\end{verbatim}
+This processes message data where ``pt'' is the plaintext and ``ct'' is the ciphertext.  The length of both are equal and stored in ``ptlen''.  Depending on the 
+mode ``pt'' is the input and ``ct'' is the output (or vice versa).  When ``direction'' equals \textbf{GCM\_ENCRYPT} the plaintext is read, encrypted and stored
+in the ciphertext buffer.  When ``direction'' equals \textbf{GCM\_DECRYPT} the opposite occurs.
+
+\subsubsection{State Termination}
+To terminate a GCM state and retrieve the message authentication tag call the following function.
+
+\index{gcm\_done()}
+\begin{verbatim}
+int gcm_done(gcm_state *gcm, 
+                     unsigned char *tag,    unsigned long *taglen);
+\end{verbatim}
+This terminates the GCM state ``gcm'' and stores the tag in ``tag'' of length ``taglen'' octets.
+
+\subsubsection{State Reset}
+The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
+it is very costly to have to call it repeatedly.  To aid in this endeavour the reset function has been provided.
+
+\index{gcm\_reset()}
+\begin{verbatim}
+int gcm_reset(gcm_state *gcm);
+\end{verbatim}
+
+This will reset the GCM state ``gcm'' to the state that gcm\_init() left it.  The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
+
+\subsubsection{One--Shot Packet}
+To process a single packet under any given key the following helper function can be used.
+
+\index{gcm\_memory()}
+\begin{verbatim}
+int gcm_memory(      int           cipher,
+               const unsigned char *key,    unsigned long keylen,
+               const unsigned char *IV,     unsigned long IVlen,
+               const unsigned char *adata,  unsigned long adatalen,
+                     unsigned char *pt,     unsigned long ptlen,
+                     unsigned char *ct, 
+                     unsigned char *tag,    unsigned long *taglen,
+                               int direction);
+\end{verbatim}
+
+This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
+message tag.  The definition of the variables is the same as it is for all the manual functions.
+
+If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
+
+\subsubsection{Example Usage}
+The following is an example usage of how to use GCM over multiple packets with a shared secret key.
+
+\begin{small}
+\begin{verbatim}
+#include <tomcrypt.h>
+
+int send_packet(const unsigned char *pt,  unsigned long ptlen,
+                const unsigned char *iv,  unsigned long ivlen,
+                const unsigned char *aad, unsigned long aadlen,
+                      gcm_state     *gcm)
+{
+   int           err;
+   unsigned long taglen;
+   unsigned char tag[16];
+
+   /* reset the state */
+   if ((err = gcm_reset(gcm)) != CRYPT_OK) {
+      return err;
+   }
+   /* Add the IV */
+   if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
+      return err;
+   }
+
+   /* Add the AAD (note: aad can be NULL if aadlen == 0) */
+   if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
+      return err;
+   }
+
+   /* process the plaintext */
+   if ((err = gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
+      return err;
+   }
+
+   /* Finish up and get the MAC tag */
+   taglen = sizeof(tag);
+   if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
+      return err;
+   }
+
+   /* ... send a header describing the lengths ... */
+
+   /* depending on the protocol and how IV is generated you may have to send it too... */
+   send(socket, iv, ivlen, 0);
+
+   /* send the aad */
+   send(socket, aad, aadlen, 0);
+
+   /* send the ciphertext */
+   send(socket, pt, ptlen, 0);
+
+   /* send the tag */
+   send(socket, tag, taglen, 0);
+
+   return CRYPT_OK;
+}
+
+int main(void)
+{
+   gcm_state     gcm;
+   unsigned char key[16], IV[12], pt[PACKET_SIZE];
+   int           err, x;
+   unsigned long ptlen; 
+   /* somehow fill key/IV with random values */
+   
+   /* register AES */
+   register_cipher(&aes_desc);
+
+   /* init the GCM state */
+   if ((err = gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
+      whine_and_pout(err);
+   }
+
+   /* handle us some packets */
+   for (;;) {
+       ptlen = make_packet_we_want_to_send(pt);
+
+       /* use IV as counter (12 byte counter) */
+       for (x = 11; x >= 0; x--) {
+           if (++IV[x]) {
+              break;
+           }
+       }
+
+       if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm)) != CRYPT_OK) {
+           whine_and_pout(err);
+       }
+   }
+   return EXIT_SUCCESS;
+}
+\end{verbatim}
+\end{small}
+
 \chapter{One-Way Cryptographic Hash Functions}
 \section{Core Functions}
 
@@ -788,7 +1438,7 @@ void XXX_init(hash_state *md);
 This simply sets up the hash to the default state governed by the specifications of the hash.  To add data to the 
 message being hashed call:
 \begin{verbatim}
-void XXX_process(hash_state *md, const unsigned char *in, unsigned long len);
+int XXX_process(hash_state *md, const unsigned char *in, unsigned long inlen);
 \end{verbatim}
 
 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 
@@ -806,7 +1456,7 @@ md5_process(&md, "hello world", 11);
 
 To finally get the message digest (the hash) call:
 \begin{verbatim}
-void XXX_done(hash_state *md, 
+int XXX_done(hash_state *md, 
               unsigned char *out);
 \end{verbatim}
 
@@ -823,7 +1473,7 @@ This will return {\bf CRYPTO\_OK} if the hash matches the test vectors, otherwis
 example snippet that hashes a message with md5 is given below.
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
     hash_state md;
@@ -844,7 +1494,6 @@ int main(void)
 \end{small}
 
 \section{Hash Descriptors}
-\index{Hash Descriptors}
 Like the set of ciphers the set of hashes have descriptors too.  They are stored in an array called ``hash\_descriptor'' and
 are defined by:
 \begin{verbatim}
@@ -852,9 +1501,10 @@ struct _hash_descriptor {
     char *name;
     unsigned long hashsize;    /* digest output size in bytes  */
     unsigned long blocksize;   /* the block size the hash uses */
-    void (*init)   (hash_state *);
-    void (*process)(hash_state *, const unsigned char *, unsigned long);
-    void (*done)   (hash_state *, unsigned char *);
+    void (*init)   (hash_state *hash);
+    int  (*process)(hash_state *hash, 
+                    const unsigned char *in, unsigned long inlen);
+    int  (*done)   (hash_state *hash, unsigned char *out);
     int  (*test)   (void);
 };
 \end{verbatim}
@@ -867,7 +1517,7 @@ position in the descriptor table of the hash.
 You can use the table to indirectly call a hash function that is chosen at runtime.  For example:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    unsigned char buffer[100], hash[MAXBLOCKSIZE];
@@ -915,32 +1565,30 @@ length.  This provides a simple size you can set your automatic arrays to that w
 There are three helper functions as well:
 \index{hash\_memory()} \index{hash\_file()}
 \begin{verbatim}
-int hash_memory(int hash, const unsigned char *data, 
-                unsigned long len, unsigned char *dst,
-                unsigned long *outlen);
+int hash_memory(int hash, 
+                const unsigned char *in,   unsigned long inlen, 
+                      unsigned char *out,  unsigned long *outlen);
 
 int hash_file(int hash, const char *fname, 
-              unsigned char *dst,
-              unsigned long *outlen);
+              unsigned char *out, unsigned long *outlen);
 
 int hash_filehandle(int hash, FILE *in, 
-                    unsigned char *dst, unsigned long *outlen);
+                    unsigned char *out, unsigned long *outlen);
 \end{verbatim}
 
 The ``hash'' parameter is the location in the descriptor table of the hash (\textit{e.g. the return of find\_hash()}).  
-The ``*outlen'' variable is used to keep track of the output size.  You
-must set it to the size of your output buffer before calling the functions.  When they complete succesfully they store
-the length of the message digest back in it.  The functions are otherwise straightforward.  The ``hash\_filehandle'' 
-function assumes that ``in'' is an file handle opened in binary mode.  It will hash to the end of file and not reset
-the file position when finished.
+The ``*outlen'' variable is used to keep track of the output size.  You must set it to the size of your output buffer before 
+calling the functions.  When they complete succesfully they store the length of the message digest back in it.  The functions 
+are otherwise straightforward.  The ``hash\_filehandle'' function assumes that ``in'' is an file handle opened in binary mode.  
+It will hash to the end of file and not reset the file position when finished.
 
 To perform the above hash with md5 the following code could be used:
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
-   int idx, errno;
+   int idx, err;
    unsigned long len;
    unsigned char out[MAXBLOCKSIZE];
 
@@ -955,8 +1603,8 @@ int main(void)
 
    /* call the hash */
    len = sizeof(out);
-   if ((errno = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
-      printf("Error hashing data: %s\n", error_to_string(errno));
+   if ((err = hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
+      printf("Error hashing data: %s\n", error_to_string(err));
       return -1;
    }
    return 0;
@@ -965,14 +1613,19 @@ int main(void)
 \end{small}
 
 The following hashes are provided as of this release:
+\index{Hash descriptor table}
 \begin{center}
 \begin{tabular}{|c|c|c|}
       \hline Name & Descriptor Name & Size of Message Digest (bytes) \\
+      \hline WHIRLPOOL & whirlpool\_desc & 64 \\
       \hline SHA-512 & sha512\_desc & 64 \\
       \hline SHA-384 & sha384\_desc & 48 \\
       \hline SHA-256 & sha256\_desc & 32 \\
+      \hline SHA-224 & sha224\_desc & 28 \\
       \hline TIGER-192 & tiger\_desc & 24 \\
       \hline SHA-1 & sha1\_desc & 20 \\
+      \hline RIPEMD-160 & rmd160\_desc & 20 \\
+      \hline RIPEMD-128 & rmd128\_desc & 16 \\
       \hline MD5 & md5\_desc & 16 \\
       \hline MD4 & md4\_desc & 16 \\
       \hline MD2 & md2\_desc & 16 \\
@@ -982,71 +1635,136 @@ The following hashes are provided as of this release:
 
 Similar to the cipher descriptor table you must register your hash algorithms before you can use them.  These functions
 work exactly like those of the cipher registration code.  The functions are:
+\index{register\_hash()} \index{unregister\_hash()}
 \begin{verbatim}
 int register_hash(const struct _hash_descriptor *hash);
 int unregister_hash(const struct _hash_descriptor *hash);
 \end{verbatim}
 
-\subsection{Notice}
-It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.  
-These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
-(e.g. Yarrow).
-
-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
-for all purposes you would normally use a hash for.
+\section{Cipher Hash Construction}
+\index{Cipher Hash Construction}
+An addition to the suite of hash functions is the ``Cipher Hash Construction'' or ``CHC'' mode.  In this mode
+applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use.  In 
+particular this allows a cryptosystem to be designed using very few moving parts.
 
-\section{Hash based Message Authenication Codes}
-Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short.  An HMAC
-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
-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
-eavesdropper will not be able to verify the authenticity of a message.  
+In order to use the CHC system the developer will have to take a few extra steps.  First the ``chc\_desc'' hash
+descriptor must be registered with register\_hash().  At this point the CHC hash cannot be used to hash
+data.  While it is in the hash system you still have to tell the CHC code which cipher to use.  This is accomplished
+via the chc\_register() function.
 
-The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key 
-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
-chars.  The initialization routine is:
-\begin{verbatim}
-int hmac_init(hmac_state *hmac, int hash, 
-              const unsigned char *key, unsigned long keylen);
-\end{verbatim}
-The ``hmac'' parameter is the state for the HMAC code.  ``hash'' is the index into the descriptor table of the hash you want
-to use to authenticate the message.  ``key'' is the pointer to the array of chars that make up the key.  ``keylen'' is the
-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:
+\index{chc\_register()}
 \begin{verbatim}
-int hmac_process(hmac_state *hmac, const unsigned char *buf,
-                  unsigned long len);
+int chc_register(int cipher);
+\end{verbatim}
+
+A cipher has to be registered with CHC (and also in the cipher descriptor tables with 
+register\_cipher()).  The chc\_register() function will bind a cipher to the CHC system.  Only one cipher can 
+be bound to the CHC hash at a time.  There are additional requirements for the system to work.
+
+\begin{enumerate}
+   \item The cipher must have a block size greater than 64--bits.  
+   \item The cipher must allow an input key the size of the block size.
+\end{enumerate}
+
+Example of using CHC with the AES block cipher.
+
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   int err; 
+
+   /* register cipher and hash */
+   if (register_cipher(&aes_enc_desc) == -1) {
+      printf("Could not register cipher\n");
+      return EXIT_FAILURE;
+   }
+   if (register_hash(&chc_desc) == -1) {
+      printf("Could not register hash\n");
+      return EXIT_FAILURE;
+   }
+
+   /* start chc with AES */
+   if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
+      printf("Error binding AES to CHC: %s\n", error_to_string(err));
+   }
+
+   /* now you can use chc_hash in any LTC function [aside from pkcs...] */
+   /* ... */
+\end{verbatim}
+
+
+\section{Notice}
+It is highly recommended that you \textbf{not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.  
+These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
+(e.g. Yarrow).
+
+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
+for all purposes you would normally use a hash for.
+
+\chapter{Message Authentication Codes}
+\section{HMAC Protocol}
+Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short.  An HMAC
+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
+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
+eavesdropper will not be able to verify the authenticity of a message.  
+
+The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key 
+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
+chars.  The initialization routine is:
+\index{hmac\_init()}
+\begin{verbatim}
+int hmac_init(hmac_state *hmac, int hash, 
+              const unsigned char *key, unsigned long keylen);
+\end{verbatim}
+The ``hmac'' parameter is the state for the HMAC code.  ``hash'' is the index into the descriptor table of the hash you want
+to use to authenticate the message.  ``key'' is the pointer to the array of chars that make up the key.  ``keylen'' is the
+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:
+\index{hmac\_process()}
+\begin{verbatim}
+int hmac_process(hmac_state *hmac, 
+                 const unsigned char *in, unsigned long inlen);
 \end{verbatim}
 ``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process.  ``len'' is the
 number of octets to process.  Like the hash process routines you can send the data in arbitrarly sized chunks. When you 
 are finished with the HMAC process you must call the following function to get the HMAC code:
+\index{hmac\_done()}
 \begin{verbatim}
-int  hmac_done(hmac_state *hmac, unsigned char *hash);
+int hmac_done(hmac_state *hmac, 
+              unsigned char *out, unsigned long *outlen);
 \end{verbatim}
-``hmac'' is the HMAC state you are working with.  ``hash'' is the array of octets where the HMAC code should be stored.  You
-must ensure that your destination array is the right size (or just make it of size MAXBLOCKSIZE to be sure).  
+``hmac'' is the HMAC state you are working with.  ``out'' is the array of octets where the HMAC code should be stored.  You must
+set ``outlen'' to the size of the destination buffer before calling this function.  It is updated with the length of the HMAC code
+produced (depending on which hash was picked).  If ``outlen'' is less than the size of the message digest (and ultimately
+the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first ``outlen'' bytes).
 
 There are two  utility functions provided to make using HMACs easier todo.  They accept the key and information about the
 message (file pointer, address in memory) and produce the HMAC result in one shot.  These are useful if you want to avoid
 calling the three step process yourself.
 
+\index{hmac\_memory()}
 \begin{verbatim}
-int hmac_memory(int hash, const unsigned char *key, unsigned long keylen,
-                const unsigned char *data, unsigned long len, 
-                unsigned char *dst, unsigned long *dstlen);
+int hmac_memory(int hash, 
+                const unsigned char *key, unsigned long  keylen,
+                const unsigned char *in,  unsigned long  inlen, 
+                      unsigned char *out, unsigned long *outlen);
 \end{verbatim}
-This will produce an HMAC code for the array of octets in ``data'' of length ``len''.  The index into the hash descriptor 
+This will produce an HMAC code for the array of octets in ``in'' of length ``inlen''.  The index into the hash descriptor 
 table must be provided in ``hash''.  It uses the key from ``key'' with a key length of ``keylen''.  
-The result is stored in the array of octets ``dst'' and the length in ``dstlen''.  The value of ``dstlen'' must be set
+The result is stored in the array of octets ``out'' and the length in ``outlen''.  The value of ``outlen'' must be set
 to the size of the destination buffer before calling this function.  Similarly for files there is the  following function:
+\index{hmac\_file()}
 \begin{verbatim}
-int hmac_file(int hash, const char *fname, const unsigned char *key,
-              unsigned long keylen, 
-              unsigned char *dst, unsigned long *dstlen);
+int hmac_file(int hash, const char *fname, 
+              const unsigned char *key, unsigned long  keylen, 
+                    unsigned char *out, unsigned long *outlen);
 \end{verbatim}
 ``hash'' is the index into the hash descriptor table of the hash you want to use.  ``fname'' is the filename to process.  
-``key'' is the array of octets to use as the key of length ``keylen''.  ``dst'' is the array of octets where the 
+``key'' is the array of octets to use as the key of length ``keylen''.  ``out'' is the array of octets where the 
 result should be stored.
 
 To test if the HMAC code is working there is the following function:
+\index{hmac\_test()}
 \begin{verbatim}
 int hmac_test(void);
 \end{verbatim}
@@ -1055,12 +1773,13 @@ HMAC system is given below.
 
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
-   int idx, errno;
+   int idx, err;
    hmac_state hmac;
    unsigned char key[16], dst[MAXBLOCKSIZE];
+   unsigned long dstlen;
 
    /* register SHA-1 */
    if (register_hash(&sha1_desc) == -1) {
@@ -1074,22 +1793,154 @@ int main(void)
    /* we would make up our symmetric key in "key[]" here */
 
    /* start the HMAC */
-   if ((errno = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
-      printf("Error setting up hmac: %s\n", error_to_string(errno));
+   if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
+      printf("Error setting up hmac: %s\n", error_to_string(err));
+      return -1;
+   }
+
+   /* process a few octets */
+   if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
+      printf("Error processing hmac: %s\n", error_to_string(err));
+      return -1;
+   }
+
+   /* get result (presumably to use it somehow...) */
+   dstlen = sizeof(dst);
+   if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
+      printf("Error finishing hmac: %s\n", error_to_string(err));
+      return -1;
+   }
+   printf("The hmac is %lu bytes long\n", dstlen);
+  
+   /* return */
+   return 0;
+}
+\end{verbatim}
+\end{small}
+
+\section{OMAC Support}
+OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an 
+algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES.  From an API 
+standpoint the OMAC routines work much like the HMAC routines do.  Instead in this case a cipher is used instead of a hash.  
+
+To start an OMAC state you call
+\index{omac\_init()}
+\begin{verbatim}
+int omac_init(omac_state *omac, int cipher, 
+              const unsigned char *key, unsigned long keylen);
+\end{verbatim}
+The ``omac'' variable is the state for the OMAC algorithm.  ``cipher'' is the index into the cipher\_descriptor table
+of the cipher\footnote{The cipher must have a 64 or 128 bit block size.  Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
+wish to use.  ``key'' and ``keylen'' are the keys used to authenticate the data.
+
+To send data through the algorithm call
+\index{omac\_process()}
+\begin{verbatim}
+int omac_process(omac_state *state, 
+                 const unsigned char *in, unsigned long inlen);
+\end{verbatim}
+This will send ``inlen'' bytes from ``in'' through the active OMAC state ``state''.  Returns \textbf{CRYPT\_OK} if the 
+function succeeds.  The function is not sensitive to the granularity of the data.  For example,
+
+\begin{verbatim}
+omac_process(&mystate, "hello",  5);
+omac_process(&mystate, " world", 6);
+\end{verbatim}
+
+Would produce the same result as,
+
+\begin{verbatim}
+omac_process(&mystate, "hello world",  11);
+\end{verbatim}
+
+When you are done processing the message you can call the following to compute the message tag.
+
+\index{omac\_done()}
+\begin{verbatim}
+int omac_done(omac_state *state, 
+              unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+Which will terminate the OMAC and output the \textit{tag} (MAC) to ``out''.  Note that unlike the HMAC and other code 
+``outlen'' can be smaller than the default MAC size (for instance AES would make a 16-byte tag).  Part of the OMAC 
+specification states that the output may be truncated.  So if you pass in $outlen = 5$ and use AES as your cipher than
+the output MAC code will only be five bytes long.  If ``outlen'' is larger than the default size it is set to the default
+size to show how many bytes were actually used.
+
+Similar to the HMAC code the file and memory functions are also provided.  To OMAC a buffer of memory in one shot use the 
+following function.
+
+\index{omac\_memory()}
+\begin{verbatim}
+int omac_memory(int cipher, 
+                const unsigned char *key, unsigned long keylen,
+                const unsigned char *in,  unsigned long inlen,
+                      unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the OMAC of ``inlen'' bytes of ``in'' using the key ``key'' of length ``keylen'' bytes and the cipher
+specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
+rules as omac\_done.
+
+To OMAC a file use
+\index{omac\_file()}
+\begin{verbatim}
+int omac_file(int cipher, 
+              const unsigned char *key, unsigned long keylen,
+              const char *filename, 
+                    unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+
+Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
+and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with 
+the same rules as omac\_done.
+
+To test if the OMAC code is working there is the following function:
+\index{omac\_test()}
+\begin{verbatim}
+int omac_test(void);
+\end{verbatim}
+Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.  Some example code for using the 
+OMAC system is given below.
+
+\begin{small}
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   int idx, err;
+   omac_state omac;
+   unsigned char key[16], dst[MAXBLOCKSIZE];
+   unsigned long dstlen;
+
+   /* register Rijndael */
+   if (register_cipher(&rijndael_desc) == -1) {
+      printf("Error registering Rijndael\n");
+      return -1;
+   }
+
+   /* get index of Rijndael in cipher descriptor table */
+   idx = find_cipher("rijndael");
+
+   /* we would make up our symmetric key in "key[]" here */
+
+   /* start the OMAC */
+   if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
+      printf("Error setting up omac: %s\n", error_to_string(err));
       return -1;
    }
 
    /* process a few octets */
-   if((errno = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
-      printf("Error processing hmac: %s\n", error_to_string(errno));
+   if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
+      printf("Error processing omac: %s\n", error_to_string(err));
       return -1;
    }
 
    /* get result (presumably to use it somehow...) */
-   if ((errno = hmac_done(&hmac, dst)) != CRYPT_OK) {
-      printf("Error finishing hmac: %s\n", error_to_string(errno));
+   dstlen = sizeof(dst);
+   if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
+      printf("Error finishing omac: %s\n", error_to_string(err));
       return -1;
    }
+   printf("The omac is %lu bytes long\n", dstlen);
   
    /* return */
    return 0;
@@ -1097,37 +1948,247 @@ int main(void)
 \end{verbatim}
 \end{small}
 
+\section{PMAC Support}
+The PMAC\footnote{J.Black, P.Rogaway, ``A Block--Cipher Mode of Operation for Parallelizable Message Authentication''} 
+protocol is another MAC algorithm that relies solely on a symmetric-key block cipher.  It uses essentially the same
+API as the provided OMAC code.  
+
+A PMAC state is initialized with the following.
+
+\index{pmac\_init()}
+\begin{verbatim}
+int pmac_init(pmac_state *pmac, int cipher, 
+              const unsigned char *key, unsigned long keylen);
+\end{verbatim}
+Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes.  The chosen cipher
+must have a 64 or 128 bit block size (e.x. AES).
+
+To MAC data simply send it through the process function.
+
+\index{pmac\_process()}
+\begin{verbatim}
+int pmac_process(pmac_state *state, 
+                 const unsigned char *in, unsigned long inlen);
+\end{verbatim}
+This will process ``inlen'' bytes of ``in'' in the given ``state''.  The function is not sensitive to the granularity of the
+data.  For example,
+
+\begin{verbatim}
+pmac_process(&mystate, "hello",  5);
+pmac_process(&mystate, " world", 6);
+\end{verbatim}
+
+Would produce the same result as,
+
+\begin{verbatim}
+pmac_process(&mystate, "hello world",  11);
+\end{verbatim}
+
+When a complete message has been processed the following function can be called to compute the message tag.
+
+\index{pmac\_done()}
+\begin{verbatim}
+int pmac_done(pmac_state *state, 
+              unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''.  Note that if ``outlen'' is larger
+than the size of the tag it is set to the amount of bytes stored in ``out''.
+
+Similar to the PMAC code the file and memory functions are also provided.  To PMAC a buffer of memory in one shot use the 
+following function.
+
+\index{pmac\_memory()}
+\begin{verbatim}
+int pmac_memory(int cipher, 
+                const unsigned char *key, unsigned long  keylen,
+                const unsigned char *in,  unsigned long  inlen,
+                      unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
+specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
+rules as omac\_done.
+
+To PMAC a file use
+\index{pmac\_file()}
+\begin{verbatim}
+int pmac_file(int cipher, 
+              const unsigned char *key, unsigned long keylen,
+              const char *filename, 
+              unsigned char *out, unsigned long *outlen);
+\end{verbatim}
+
+Which will PMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
+and the cipher specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with 
+the same rules as omac\_done.
+
+To test if the PMAC code is working there is the following function:
+\index{pmac\_test()}
+\begin{verbatim}
+int pmac_test(void);
+\end{verbatim}
+Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
+
+\section{Pelican MAC}
+Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a ``mixing function''.  It achieves a very high 
+rate of processing and is potentially very secure.  It requires AES to be enabled to function.  You do not have to register\_cipher() AES first though
+as it calls AES directly.
+
+\index{pelican\_init()}
+\begin{verbatim}
+int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
+\end{verbatim}
+This will initialize the Pelican state with the given AES key.  Once this has been done you can begin processing data.
+
+\index{pelican\_process()}
+\begin{verbatim}
+int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
+\end{verbatim}
+This will process ``inlen'' bytes of ``in'' through the Pelican MAC.  It's best that you pass in multiples of 16 bytes as it makes the
+routine more efficient but you may pass in any length of text.  You can call this function as many times as required to process
+an entire message.
+
+\index{pelican\_done()}
+\begin{verbatim}
+int pelican_done(pelican_state *pelmac, unsigned char *out);
+\end{verbatim}
+This terminates a Pelican MAC and writes the 16--octet tag to ``out''.
+
+\subsection{Example}
+
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   pelican_state pelstate;
+   unsigned char key[32], tag[16];
+   int           err;
+
+   /* somehow initialize a key */
+
+   /* initialize pelican mac */
+   if ((err = pelican_init(&pelstate,          /* the state */
+                           key,                /* user key */
+                           32                  /* key length in octets */
+                          )) != CRYPT_OK) {
+      printf("Error initializing Pelican: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* MAC some data */
+   if ((err = pelican_process(&pelstate,       /* the state */
+                              "hello world",   /* data to mac */        
+                              11               /* length of data */
+                              )) != CRYPT_OK) {
+      printf("Error processing Pelican: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* Terminate the MAC */
+   if ((err = pelican_done(&pelstate,       /* the state */
+                           tag              /* where to store the tag */
+                           )) != CRYPT_OK) {
+      printf("Error terminating Pelican: %s", error_to_string(err));
+      return EXIT_FAILURE;
+   }
+
+   /* tag[0..15] has the MAC output now */
+
+   return EXIT_SUCCESS;
+}
+\end{verbatim}
+
+
 \chapter{Pseudo-Random Number Generators}
 \section{Core Functions}
-
 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well.  A cryptographic PRNG is
 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)
 key generation.  There is a universal structure called ``prng\_state''.  To initialize a PRNG call:
+\index{PRNG start}
 \begin{verbatim}
 int XXX_start(prng_state *prng);
 \end{verbatim}
 
-This will setup the PRNG for future use and not seed it.  In order 
-for the PRNG to be cryptographically useful you must give it entropy.  Ideally you'd have some OS level source to tap 
-like in UNIX (see section 5.3).  To add entropy to the PRNG call:
+This will setup the PRNG for future use and not seed it.  In order for the PRNG to be cryptographically useful you must give it 
+entropy.  Ideally you'd have some OS level source to tap like in UNIX.  To add entropy to the PRNG call:
+\index{PRNG add\_entropy}
 \begin{verbatim}
-int XXX_add_entropy(const unsigned char *in, unsigned long len, 
+int XXX_add_entropy(const unsigned char *in, unsigned long inlen, 
                     prng_state *prng);
 \end{verbatim}
 
 Which returns {\bf CRYPTO\_OK} if the entropy was accepted.  Once you think you have enough entropy you call another
 function to put the entropy into action.
+\index{PRNG ready}
 \begin{verbatim}
 int XXX_ready(prng_state *prng);
 \end{verbatim}
 
 Which returns {\bf CRYPTO\_OK} if it is ready.  Finally to actually read bytes call:
+\index{PRNG read}
 \begin{verbatim}
-unsigned long XXX_read(unsigned char *out, unsigned long len,
+unsigned long XXX_read(unsigned char *out, unsigned long outlen,
                        prng_state *prng);
 \end{verbatim}
 
-Which returns the number of bytes read from the PRNG.
+Which returns the number of bytes read from the PRNG.  When you are finished with a PRNG state you call
+the following.
+
+\index{PRNG done}
+\begin{verbatim}
+void XXX_done(prng_state *prng);
+\end{verbatim}
+
+This will terminate a PRNG state and free any memory (if any) allocated.  To export a PRNG state
+so that you can later resume the PRNG call the following.
+
+\index{PRNG export}
+\begin{verbatim}
+int XXX_export(unsigned char *out, unsigned long *outlen, 
+               prng_state    *prng);
+\end{verbatim}
+
+This will write a ``PRNG state'' to the buffer ``out'' of length ``outlen'' bytes.  The idea of 
+the export is meant to be used as a ``seed file''.  That is, when the program starts up there will not likely
+be that much entropy available.   To import a state to seed a PRNG call the following function.
+
+\index{PRNG import}
+\begin{verbatim}
+int XXX_import(const unsigned char *in, unsigned long inlen, 
+                     prng_state     *prng);
+\end{verbatim}
+
+This will call the start and add\_entropy functions of the given PRNG.  It will use the state in
+``in'' of length ``inlen'' as the initial seed.  You must pass the same seed length as was exported
+by the corresponding export function.
+
+Note that importing a state will not ``resume'' the PRNG from where it left off.  That is, if you export
+a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not 
+specifically equal the 8 bytes you generated previously.
+
+When a program is first executed the normal course of operation is 
+
+\begin{enumerate}
+   \item Gather entropy from your sources for a given period of time or number of events.
+   \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
+\end{enumerate}
+
+When your program is finished you simply call the export function and save the state to a medium (disk,
+flash memory, etc).  The next time your application starts up you can detect the state, feed it to the 
+import function and go on your way.  It is ideal that (as soon as possible) after startup you export a
+fresh state.  This helps in the case that the program aborts or the machine is powered down without
+being given a chance to exit properly.  
+
+Note that even if you have a state to import it is important to add new entropy to the state.  However,
+there is less pressure to do so.  
+
+To test a PRNG for operational conformity call the following functions.
+
+\index{PRNG test}
+\begin{verbatim}
+int XXX_test(void);
+\end{verbatim}
+
+This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
 
 \subsection{Remarks}
 
@@ -1138,28 +2199,28 @@ checking is guaranteed to see if the entropy is sufficient or if the PRNG is eve
 
 \subsection{Example}
 
-Below is a simple snippet to read 10 bytes from yarrow.  Its important to note that this snippet is {\bf NOT} secure since
-the entropy added is not random.
+Below is a simple snippet to read 10 bytes from yarrow.  Its important to note that this snippet is 
+{\bf NOT} secure since the entropy added is not random.
 
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    prng_state prng;
    unsigned char buf[10];
-   int errno;
+   int err;
    
    /* start it */
-   if ((errno = yarrow_start(&prng)) != CRYPT_OK) {
-      printf("Start error: %s\n", error_to_string(errno));
+   if ((err = yarrow_start(&prng)) != CRYPT_OK) {
+      printf("Start error: %s\n", error_to_string(err));
    }
    /* add entropy */
-   if ((errno = yarrow_add_entropy("hello world", 11, &prng)) != CRYPT_OK) {
-      printf("Add_entropy error: %s\n", error_to_string(errno));
+   if ((err = yarrow_add_entropy("hello world", 11, &prng)) != CRYPT_OK) {
+      printf("Add_entropy error: %s\n", error_to_string(err));
    }
    /* ready and read */
-   if ((errno = yarrow_ready(&prng)) != CRYPT_OK) {
-      printf("Ready error: %s\n", error_to_string(errno));
+   if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
+      printf("Ready error: %s\n", error_to_string(err));
    }
    printf("Read %lu bytes from yarrow\n", yarrow_read(buf, 10, &prng));
    return 0;
@@ -1172,10 +2233,15 @@ PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_descrip
 \begin{verbatim}
 struct _prng_descriptor {
     char *name;
+    int  export_size;    /* size in bytes of exported state */
     int (*start)      (prng_state *);
     int (*add_entropy)(const unsigned char *, unsigned long, prng_state *);
     int (*ready)      (prng_state *);
     unsigned long (*read)(unsigned char *, unsigned long len, prng_state *);
+    void (*done)(prng_state *);
+    int (*export)(unsigned char *, unsigned long *, prng_state *);
+    int (*import)(const unsigned char *, unsigned long, prng_state *);
+    int (*test)(void);
 };
 \end{verbatim}
 
@@ -1189,39 +2255,105 @@ int register_prng(const struct _prng_descriptor *prng);
 int unregister_prng(const struct _prng_descriptor *prng);
 \end{verbatim}
 
-\subsubsection{PRNGs Provided}
-Currently Yarrow (yarrow\_desc), RC4 (rc4\_desc) and the secure RNG (sprng\_desc) are provided as PRNGs within the 
-library.  
+\subsection{PRNGs Provided}
+\begin{figure}[here]
+\begin{center}
+\begin{small}
+\begin{tabular}{|c|c|l|}
+\hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
+\hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
+\hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended) \\
+\hline RC4 & rc4\_desc & Stream Cipher \\
+\hline SOBER-128 & sober128\_desc & Stream Cipher (also very fast PRNG) \\
+\hline
+\end{tabular}
+\end{small}
+\end{center}
+\caption{List of Provided PRNGs}
+\end{figure}
+
+\subsubsection{Yarrow}
+Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources 
+(keyboard, mouse, interrupts, etc) and produce an unbounded string of random bytes.  
+
+\textit{Note:} This PRNG is still secure for most taskings but is no longer recommended.  Users
+should use Fortuna instead.
+
+\subsubsection{Fortuna}
 
-RC4 is provided with a PRNG interface because it is a stream cipher and not well suited for the symmetric block cipher
-interface.  You provide the key for RC4 via the rc4\_add\_entropy() function.  By calling rc4\_ready() the key will be used
-to setup the RC4 state for encryption or decryption.  The rc4\_read() function has been modified from RC4 since it will 
-XOR the output of the RC4 keystream generator against the input buffer you provide.  The following snippet will demonstrate
-how to encrypt a buffer with RC4:
+Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
+usage.  It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
+to work with most cipher and hash combos based on which you have chosen to build into the library.} while
+providing more security.  
 
+Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher 
+and SHA--256 hash function.  Technically Fortuna will work with any block cipher that accepts a 256--bit
+key and any hash that produces at least a 256--bit output.  However, to make the implementation simpler
+it has been fixed to those choices.
+
+Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being 
+added to the PRNG learn far less about the state than that of Yarrow.  Without getting into to many
+details Fortuna has the ability to recover from state determination attacks where the attacker starts
+to learn information from the PRNGs output about the internal state.  Yarrow on the other hand cannot 
+recover from that problem until new entropy is added to the pool and put to use through the ready() function.
+
+\subsubsection{RC4}
+
+RC4 is an old stream cipher that can also double duty as a PRNG in a pinch.  You ``key'' it by
+calling add\_entropy() and setup the key by calling ready().  You can only add upto 256 bytes via
+add\_entropy().  
+
+When you read from RC4 the output of the RC4 algorithm is XOR'd against your buffer you provide.  In this
+manner you can use rc4\_read() as an encrypt (and decrypt) function.  
+
+You really shouldn't use RC4 anymore.  This isn't because RC4 is weak (though biases are known to exist) just
+simply that faster alternatives exist.
+
+\subsubsection{SOBER-128}
+
+SOBER-128 is a stream cipher designed by the QUALCOMM Australia team.  Like RC4 you ``key'' it by 
+calling add\_entropy().  There is no need to call ready() for this PRNG as it does not do anything.  
+
+Note that this cipher has several oddities about how it operates.  The first time you call 
+add\_entropy() that sets the cipher's key.  Every other time you call the same function it sets
+the cipher's IV variable.  The IV mechanism allows you to encrypt several messages with the same
+key and not re--use the same key material.
+
+Unlike Yarrow and Fortuna all of the entropy (and hence security) of this algorithm rests in the data
+you pass it on the first call to add\_entropy().  All buffers sent to add\_entropy() must have a length
+that is a multiple of four bytes.
+
+Like RC4 the output of SOBER--128 is XOR'ed against the buffer you provide it.  In this manner you can use
+sober128\_read() as an encrypt (and decrypt) function.
+
+Since SOBER-128 has a fixed keying scheme and is very fast (faster than RC4) the ideal usage of SOBER-128 is to 
+key it from the output of Fortuna (or Yarrow) and use it to encrypt messages.  It is also ideal for
+simulations which need a high quality (and fast) stream of bytes.  
+
+\subsubsection{Example Usage}
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    prng_state prng;
    unsigned char buf[32];
-   int errno;
+   int err;
 
-   if ((errno = rc4_start(&prng)) != CRYPT_OK) {
-      printf("RC4 init error: %s\n", error_to_string(errno));
+   if ((err = rc4_start(&prng)) != CRYPT_OK) {
+      printf("RC4 init error: %s\n", error_to_string(err));
       exit(-1);
    }
 
    /* use ``key'' as the key */
-   if ((errno = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
-      printf("RC4 add entropy error: %s\n", error_to_string(errno));
+   if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
+      printf("RC4 add entropy error: %s\n", error_to_string(err));
       exit(-1);
    }
 
    /* setup RC4 for use */
-   if ((errno = rc4_ready(&prng)) != CRYPT_OK) {
-      printf("RC4 ready error: %s\n", error_to_string(errno));
+   if ((err = rc4_ready(&prng)) != CRYPT_OK) {
+      printf("RC4 ready error: %s\n", error_to_string(err));
       exit(-1);
    }
 
@@ -1269,12 +2401,12 @@ platform where the RNG doesn't work well.  Example usage of this function is giv
 
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    ecc_key mykey;
    prng_state prng;
-   int errno;
+   int err;
 
    /* register yarrow */
    if (register_prng(&yarrow_desc) == -1) {
@@ -1283,14 +2415,14 @@ int main(void)
    }
 
    /* setup the PRNG */
-   if ((errno = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
-      printf("Error setting up PRNG, %s\n", error_to_string(errno));
+   if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
+      printf("Error setting up PRNG, %s\n", error_to_string(err));
       return -1;
    }
 
    /* make a 192-bit ECC key */
-   if ((errno = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) {
-      printf("Error making key: %s\n", error_to_string(errno));
+   if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) {
+      printf("Error making key: %s\n", error_to_string(err));
       return -1;
    }
    return 0;
@@ -1306,11 +2438,11 @@ the previous example using this PRNG.
 
 \begin{small}
 \begin{verbatim}
-#include <mycrypt.h>
+#include <tomcrypt.h>
 int main(void)
 {
    ecc_key mykey;
-   int errno;
+   int err;
 
    /* register SPRNG */
    if (register_prng(&sprng_desc) == -1) {
@@ -1319,8 +2451,8 @@ int main(void)
    }
 
    /* make a 192-bit ECC key */
-   if ((errno = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) != CRYPT_OK) {
-      printf("Error making key: %s\n", error_to_string(errno));
+   if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey)) != CRYPT_OK) {
+      printf("Error making key: %s\n", error_to_string(err));
       return -1;
    }
    return 0;
@@ -1328,9 +2460,112 @@ int main(void)
 \end{verbatim}
 \end{small}
 
-\chapter{RSA Routines}
 
-\section{Background}
+
+\chapter{RSA Public Key Cryptography}
+
+\section{Introduction}
+RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography.  In the specifications are
+padding algorithms for encryption and signatures.  The standard includes the ``v2.1'' algorithms.
+To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS 
+respectively.  
+
+\section{PKCS \#1 Encryption}
+
+PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation.  As far as this portion of
+the library is concerned we are only dealing with th OAEP padding of the message.
+
+\subsection{OAEP Encoding}
+
+\index{pkcs\_1\_oaep\_encode()}
+\begin{alltt}
+int pkcs_1_oaep_encode(const unsigned char *msg,    unsigned long msglen,
+                       const unsigned char *lparam, unsigned long lparamlen,
+                             unsigned long modulus_bitlen, prng_state *prng,
+                             int           prng_idx,         int  hash_idx,
+                             unsigned char *out,    unsigned long *outlen);
+\end{alltt}
+
+This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded.  The ``lparam'' variable is an additional system specific
+tag that can be applied to the encoding.  This is useful to identify which system encoded the message.  If no variance is desired then
+``lparam'' can be set to \textbf{NULL}.  
+
+OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output.  This is passed as the parameter
+``modulus\_bitlen''.  ``hash\_idx'' is the index into the hash descriptor table of the hash desired.  PKCS \#1 allows any hash to be 
+used but both the encoder and decoder must use the same hash in order for this to succeed.  The size of hash output affects the maximum
+ sized input message.  ``prng\_idx'' and ``prng'' are the random number generator arguments required to randomize the padding process.  
+The padded message is stored in ``out'' along with the length in ``outlen''.
+
+If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for ``msg'' is 
+$m - 2h - 2$.  For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.  
+
+Note that when the message is padded it still has not been RSA encrypted.  You must pass the output of this function to 
+rsa\_exptmod() to encrypt it. 
+
+\subsection{OAEP Decoding}
+
+\index{pkcs\_1\_oaep\_decode()}
+\begin{alltt}
+int pkcs_1_oaep_decode(const unsigned char *msg,    unsigned long msglen,
+                       const unsigned char *lparam, unsigned long lparamlen,
+                             unsigned long modulus_bitlen, int hash_idx,
+                             unsigned char *out,    unsigned long *outlen,
+                             int           *res);
+\end{alltt}
+
+This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder.  ``msg'' is the 
+output of pkcs\_1\_oaep\_encode() of length ``msglen''.  ``lparam'' is the same system variable passed to the OAEP encoder.  If it does not
+match what was used during encoding this function will not decode the packet.  ``modulus\_bitlen'' is the size of the RSA modulus in bits
+and must match what was used during encoding.  Similarly the ``hash\_idx'' index into the hash descriptor table must match what was used
+during encoding.
+
+If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen'' and stores a 
+$1$ in ``res''.  If the packet is invalid it stores $0$ in ``res'' and if the function fails for another reason
+it returns an error code.  
+
+\section{PKCS \#1 Digital Signatures}
+
+\subsection{PSS Encoding}
+PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.  
+
+\index{pkcs\_1\_pss\_encode()}
+\begin{alltt}
+int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
+                            unsigned long saltlen,  prng_state   *prng,     
+                            int           prng_idx, int           hash_idx,
+                            unsigned long modulus_bitlen,
+                            unsigned char *out,     unsigned long *outlen);
+\end{alltt}
+
+This function assumes the message to be PSS encoded has previously been hashed.  The input hash ``msghash'' is of length 
+``msghashlen''.  PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.  
+``hash\_idx'' is the index into the hash descriptor table of the hash to use.  ``prng\_idx'' and ``prng'' are the random
+number generator information required for the salt.
+
+Similar to OAEP encoding ``modulus\_bitlen'' is the size of the RSA modulus (in bits).  It limits the size of the salt.  If $m$ is the length
+of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.  
+
+This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_exptmod().
+
+\subsection{PSS Decoding}
+
+To decode a PSS encoded signature block you have to use the following.
+
+\index{pkcs\_1\_pss\_decode()}
+\begin{alltt}
+int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
+                      const unsigned char *sig,     unsigned long siglen,
+                            unsigned long saltlen,  int           hash_idx,
+                            unsigned long modulus_bitlen, int    *res);
+\end{alltt}
+This will decode the PSS encoded message in ``sig'' of length ``siglen'' and compare it to values in ``msghash'' of length
+``msghashlen''.  If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero.  Otherwise, 
+it is set to zero.  The rest of the parameters are as in the PSS encode call.
+
+It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
+
+\section{RSA Operations}
+\subsection{Background}
 
 RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown 
 factorization.  Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
@@ -1360,7 +2595,7 @@ to have a forged signature for.  Simply get the signatures for $M_1$ and $M_2$ o
 together.  Similar tricks can be used to deduce plaintexts from ciphertexts.  It is important not only to sign 
 the hash of documents only but also to pad the inputs with data to remove such structure.  
 
-\section{Core Functions}
+\subsection{RSA Key Generation}
 
 For RSA routines a single ``rsa\_key'' structure is used.  To make a new RSA key call:
 \index{rsa\_make\_key()}
@@ -1379,101 +2614,159 @@ Note that the ``rsa\_make\_key()'' function allocates memory at runtime when you
 ``rsa\_free()'' (see below) when you are finished with the key.  If ``rsa\_make\_key()'' fails it will automatically 
 free the ram allocated itself.
 
-There are three types of RSA keys.  The types are {\bf PK\_PRIVATE\_OPTIMIZED}, {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}.  The first
-two are private keys where the ``optimized'' type uses the Chinese Remainder Theorem to speed up decryption/signatures.  By 
-default all new keys are of the ``optimized'' type.  The non-optimized private type is provided for backwards compatibility
-as well as to save space since the optimized key requires about four times as much memory.
+\index{PK\_PRIVATE} \index{PK\_PUBLIC}
+There are two types of RSA keys.  The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}.  The first type is a private 
+RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated
+and has been replaced by the PK\_PRIVATE type.} in the form of a RSAPrivateKey.  The second type is a public RSA key
+which only includes the modulus and public exponent.  It takes the form of a RSAPublicKey.
+
+\subsection{RSA Exponentiation}
 
 To do raw work with the RSA function call:
 \index{rsa\_exptmod()}
 \begin{verbatim}
-int rsa_exptmod(const unsigned char *in, unsigned long inlen, 
-                unsigned char *out, unsigned long *outlen, 
-                int which, rsa_key *key);
+int rsa_exptmod(const unsigned char *in,   unsigned long inlen,
+                      unsigned char *out,  unsigned long *outlen, 
+                      int which, prng_state *prng, int prng_idx,
+                      rsa_key *key);
 \end{verbatim}
 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
 in ``out'' and the size of the result in ``outlen''. ``which'' is set to {\bf PK\_PUBLIC} to use ``e'' 
 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
 
-\section{Packet Routines}
-To encrypt or decrypt a symmetric key using RSA the following functions are provided.  The idea is that you make up
-a random symmetric key and use that to encode your message.  By RSA encrypting the symmetric key you can send it to a
-recipient who can RSA decrypt it and symmetrically decrypt the message.
+Note that the output of his function is zero-padded as per PKCS \#1 specifications.  This allows this routine to 
+interoprate with PKCS \#1 padding functions properly.
+
+\subsection{RSA Key Encryption}
+Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
+To facilitate encrypting short keys the following functions have been provided.
+
+\index{rsa\_encrypt\_key()}
 \begin{verbatim}
-int rsa_encrypt_key(const unsigned char *inkey, unsigned long inlen,
-                          unsigned char *outkey, unsigned long *outlen,
-                          prng_state *prng, int wprng, rsa_key *key);
+int rsa_encrypt_key(const unsigned char *in,  unsigned long inlen,
+                          unsigned char *out, unsigned long *outlen,
+                    const unsigned char *lparam, unsigned long lparamlen,
+                    prng_state *prng, int prng_idx, int hash_idx, rsa_key *key);
 \end{verbatim}
-This function is used to RSA encrypt a symmetric to share with another user.  The symmetric key and its length are
-passed as ``inkey'' and ``inlen'' respectively.  The symmetric key is limited to a range of 8 to 32 bytes 
-(\textit{64 to 256 bits}).  The RSA encrypted packet is stored in ``outkey'' and will be of length ``outlen'' bytes.  The
-value of ``outlen'' must be originally set to the size of the output buffer. 
+This function will OAEP pad ``in'' of length inlen bytes then RSA encrypt it and store the ciphertext
+in ``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
+to pkcs\_1\_oaep\_encode().
 
+\index{rsa\_decrypt\_key()}
 \begin{verbatim}
-int rsa_decrypt_key(const unsigned char *in, unsigned long inlen, 
-                          unsigned char *outkey, unsigned long *keylen, 
-                          rsa_key *key);
+int rsa_decrypt_key(const unsigned char *in,  unsigned long inlen,
+                          unsigned char *out, unsigned long *outlen, 
+                    const unsigned char *lparam, unsigned long lparamlen,
+                          int            hash_idx, int *stat,
+                          rsa_key       *key);
 \end{verbatim}
+This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
+``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
+to pkcs\_1\_oaep\_decode().
+
+If the RSA decrypted data isn't a valid OAEP packet then ``stat'' is set to $0$.  Otherwise, it is set to $1$.
 
-This function will decrypt an RSA packet to retrieve the original symmetric key encrypted with rsa\_encrypt\_key().  
-Similarly to sign or verify a hash of a message the following two messages are provided.  The idea is to hash your message 
-then use these functions to RSA sign the hash.  
+\subsection{RSA Hash Signatures}
+Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes).  To facilitate this
+process the following functions have been provided.
+
+\index{rsa\_sign\_hash()}
 \begin{verbatim}
-int rsa_sign_hash(const unsigned char *in,  unsigned long inlen, 
-                        unsigned char *out, unsigned long *outlen, 
+int rsa_sign_hash(const unsigned char *in,   unsigned long  inlen, 
+                        unsigned char *out,  unsigned long *outlen, 
+                        prng_state    *prng,     int            prng_idx,
+                        int            hash_idx, unsigned long  saltlen,
                         rsa_key *key);
-
-int rsa_verify_hash(const unsigned char *sig, unsigned long siglen,
-                    const unsigned char *hash, int *stat, rsa_key *key);
 \end{verbatim}
-For ``rsa\_sign\_hash'' the input is intended to be the hash of a message the user wants to sign.  The output is the 
-RSA signed packet which ``rsa\_verify\_hash'' can verify.  For the verification function ``sig'' is the RSA signature
-and ``hash'' is the hash of the message.  The integer ``stat'' is set to non-zero if the signature is valid or zero 
-otherwise.
 
-To import/export RSA keys as a memory buffer (e.g. to store them to disk) call:
-\begin{verbatim}
-int rsa_export(unsigned char *out, unsigned long *outlen, 
-               int type, rsa_key *key);
+This will PSS encode the message hash ``in'' of length ``inlen''.  Next the PSS encoded message will be RSA ``signed'' and 
+the output is stored in ``out'' of length ``outlen''.  
 
-int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
-\end{verbatim}
 
-The ``type'' parameter is {\bf PK\_PUBLIC}, {\bf PK\_PRIVATE} or {\bf PK\_PRIVATE\_OPTIMIZED} to export either a public or 
-private key.  The latter type will export a key with the optimized parameters.  To free the memory used by an RSA key call:
-\index{rsa\_free()}
+\index{rsa\_verify\_hash()}
 \begin{verbatim}
-void rsa_free(rsa_key *key);
+int rsa_verify_hash(const unsigned char *sig,      unsigned long siglen,
+                    const unsigned char *msghash,  unsigned long msghashlen,
+                          int            hash_idx, unsigned long saltlen,
+                          int           *stat,     rsa_key      *key);
 \end{verbatim}
 
-Note that if the key fails to ``rsa\_import()'' you do not have to free the memory allocated for it.
+This will RSA ``verify'' the signature in ``sig'' of length ``siglen''.  Next the RSA decoded data is PSS decoded
+and the extracted hash is compared against the message hash ``msghash'' of length ``msghashlen''.
 
-\section{Remarks}
-It is important that you match your RSA key size with the function you are performing.  The internal padding for both
-signatures and encryption triple the size of the plaintext.  This means to encrypt or sign
-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 
-you pass into functions like rsa\_encrypt().  This restriction applies only to data that is passed through the
-internal RSA routines directly directly.
+If the RSA decoded data is not a valid PSS message or if the PSS decoded hash does not match the ``msghash'' 
+the value ``res'' is set to $0$.  Otherwise, if the function succeeds and signature is valid ``res'' is set
+to $1$.
 
-The following table gives the size requirements for various hashes.
-\begin{center}
-\begin{tabular}{|c|c|c|}
-      \hline Name & Size of Message Digest (bytes) & RSA Key Size (bits)\\
-      \hline SHA-512 & 64 & 1544\\
-      \hline SHA-384 & 48 & 1160 \\
-      \hline SHA-256 & 32 & 776\\
-      \hline TIGER-192 & 24 & 584\\
-      \hline SHA-1 & 20 & 488\\
-      \hline MD5 & 16 & 392\\
-      \hline MD4 & 16 & 392\\
-      \hline
-\end{tabular}
-\end{center}
+\begin{verbatim}
+#include <tomcrypt.h>
+int main(void)
+{
+   int           err, hash_idx, prng_idx, res;
+   unsigned long l1, l2;
+   unsigned char pt[16], pt2[16], out[1024];
+   rsa_key       key;
+
+   /* register prng/hash */
+   if (register_prng(&sprng_desc) == -1) {
+      printf("Error registering sprng");
+      return EXIT_FAILURE;
+   }
+
+   if (register_hash(&sha1_desc) == -1) {
+      printf("Error registering sha1");
+      return EXIT_FAILURE;
+   }
+   hash_idx = find_hash("sha1");
+   prng_idx = find_prng("sprng");
+
+   /* make an RSA-1024 key */
+   if ((err = rsa_make_key(NULL,     /* PRNG state */
+                           prng_idx, /* PRNG idx */
+                           1024/8,   /* 1024-bit key */
+                           65537,    /* we like e=65537 */
+                           &key)     /* where to store the key */
+       ) != CRYPT_OK) {
+       printf("rsa_make_key %s", error_to_string(err));
+       return EXIT_FAILURE;
+   }
+
+   /* fill in pt[] with a key we want to send ... */
+   l1 = sizeof(out);
+   if ((err = rsa_encrypt_key(pt,    /* data we wish to encrypt */
+                              16,    /* data is 16 bytes long */
+                             out,    /* where to store ciphertext */
+                             &l1,    /* length of ciphertext */
+                       "TestApp",    /* our lparam for this program */
+                               7,    /* lparam is 7 bytes long */
+                            NULL,    /* PRNG state */
+                        prng_idx,    /* prng idx */
+                        hash_idx,    /* hash idx */
+                            &key)    /* our RSA key */
+       ) != CRYPT_OK) {
+       printf("rsa_encrypt_key %s", error_to_string(err));
+       return EXIT_FAILURE;
+   }
+
+   /* now let's decrypt the encrypted key */
+   l2 = sizeof(pt2);
+   if ((err = rsa_decrypt_key(out, /* encrypted data */
+                               l1, /* length of ciphertext */
+                              pt2, /* where to put plaintext */
+                              &l2, /* plaintext length */
+                        "TestApp", /* lparam for this program */
+                                7, /* lparam is 7 bytes long */
+                         hash_idx, /* hash idx */
+                             &res, /* validity of data */
+                             &key) /* our RSA key */ 
+        ) != CRYPT_OK) {
+       printf("rsa_decrypt_key %s", error_to_string(err));
+       return EXIT_FAILURE;
+   }
+   /* if all went well pt == pt2, l2 == 16, res == 1 */
+}
+\end{verbatim}
 
-The symmetric ciphers will use at a maximum a 256-bit key which means at the least a 776-bit RSA key is 
-required to use all of the symmetric ciphers with the RSA routines. If you want to use any of the large size 
-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
-keys.  None of the hashes will have problems with such key sizes.
 
 \chapter{Diffie-Hellman Key Exchange}
 
@@ -1571,18 +2864,18 @@ int establish_secure_socket(int sock, int mode, unsigned char *key,
 {
    unsigned char buf[4096], buf2[4096];
    unsigned long x, len;
-   int res, errno, inlen;
+   int res, err, inlen;
    dh_key mykey, theirkey;
 
    /* make up our private key */
-   if ((errno = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK)  {
-      return errno;
+   if ((err = dh_make_key(prng, wprng, 128, &mykey)) != CRYPT_OK)  {
+      return err;
    }
 
    /* export our key as public */ 
    x = sizeof(buf);
-   if ((errno = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
-      res = errno;
+   if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
+      res = err;
       goto done2;
    }
 
@@ -1611,22 +2904,22 @@ int establish_secure_socket(int sock, int mode, unsigned char *key,
       }
    }
 
-   if ((errno = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) { 
-      res = errno;
+   if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) { 
+      res = err;
       goto done2;
    }
 
    /* make shared secret */
    x = sizeof(buf);
-   if ((errno = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
-      res = errno;
+   if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
+      res = err;
       goto done;
    }
  
    /* hash it */
    len = 16;        /* default is MD5 so "key" must be at least 16 bytes long */
-   if ((errno = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
-      res = errno;
+   if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
+      res = err;
       goto done;
    }
 
@@ -1666,22 +2959,24 @@ Which stores the smallest and largest key sizes support into the two variables.
 \section{DH Packet}
 Similar to the RSA related functions there are functions to encrypt or decrypt symmetric keys using the DH public key
 algorithms.  
+\index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
 \begin{verbatim}
-int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
+int dh_encrypt_key(const unsigned char *in,   unsigned long  inlen,
                          unsigned char *out,  unsigned long *len, 
                          prng_state *prng, int wprng, int hash, 
                          dh_key *key);
 
-int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
-                         unsigned char *outkey, unsigned long *keylen, 
+int dh_decrypt_key(const unsigned char *in,  unsigned long  inlen,
+                         unsigned char *out, unsigned long *outlen, 
                          dh_key *key);
 \end{verbatim}
-Where ``inkey'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
+Where ``in'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
 and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the 
 required data is placed in ``out'' by ``dh\_encrypt\_key()''.   The hash must produce a message digest at least as large
 as the symmetric key you are trying to share.
 
 Similar to the RSA system you can sign and verify a hash of a message.
+\index{dh\_sign\_hash()} \index{dh\_verify\_hash()}
 \begin{verbatim}
 int dh_sign_hash(const unsigned char *in,  unsigned long inlen,
                        unsigned char *out, unsigned long *outlen,
@@ -1720,6 +3015,33 @@ provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \app
 range in order from $\approx 2^{192}$ points to $\approx 2^{521}$.  According to the source document any key size greater
 than or equal to 256-bits is sufficient for long term security.  
 
+\section{Key Format}
+LibTomCrypt uses it's own format for ECC public and private keys.  While ANSI X9.62 partially specifies key formats (it covers public keys) it does it in a less
+than ideally simple manner.  In the case of LibTomCrypt it is meant \textbf{solely} for NIST $GF(p)$ curves.  The format of the keys is as follows:
+
+\begin{small}
+\begin{verbatim}
+ECCPublicKey ::= SEQUENCE {
+    flags       BIT STRING(1), -- public/private flag (always zero), 
+    keySize     INTEGER,       -- Curve size (in bits) divided by eight 
+                               -- and rounded down, e.g. 521 => 65
+    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
+    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
+}
+
+ECCPrivateKey ::= SEQUENCE {
+    flags       BIT STRING(1), -- public/private flag (always one), 
+    keySize     INTEGER,       -- Curve size (in bits) divided by eight 
+                               -- and rounded down, e.g. 521 => 65
+    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
+    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
+    secret.k    INTEGER,       -- The secret key scalar
+}
+\end{verbatim}
+\end{small}
+
+The first flags bit denotes whether the key is public (zero) or private (one).  
+
 \section{Core Functions}
 
 Like the DH routines there is a key structure ``ecc\_key'' used by the functions.  There is a function to make a key:
@@ -1729,8 +3051,8 @@ int ecc_make_key(prng_state *prng, int wprng,
                  int keysize, ecc_key *key);
 \end{verbatim}
 
-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
-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
+The ``keysize'' is the size of the modulus in bytes desired.  Currently directly supported values are 24, 28, 32, 48 and 65 bytes which
+correspond to key sizes of 192, 224, 256, 384 and 521 bits respectively.  If you pass a key size that is between any key size
 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.  
 To free the ram allocated by a key call:
 \index{ecc\_free()}
@@ -1776,23 +3098,38 @@ Which both work like their DH counterparts.
 \section{ECC Packet}
 Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
 algorithms.
+
+\index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
 \begin{verbatim}
-int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
-                          unsigned char *out,  unsigned long *len, 
+int ecc_encrypt_key(const unsigned char *in,   unsigned long  inlen,
+                          unsigned char *out,  unsigned long *outlen, 
                           prng_state *prng, int wprng, int hash, 
                           ecc_key *key);
 
-int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
-                          unsigned char *outkey, unsigned long *keylen, 
+int ecc_decrypt_key(const unsigned char *in,  unsigned long  inlen,
+                          unsigned char *out, unsigned long *outlen, 
                           ecc_key *key);
 \end{verbatim}
 
-Where ``inkey'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
+Where ``in'' is an input symmetric key of no more than 64 bytes.  Essentially these routines created a random public key
 and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the required
 data is placed in ``out'' by ``ecc\_encrypt\_key()''.   The hash chosen must produce a message digest at least as large
 as the symmetric key you are trying to share.
 
+\subsection{Encrypt Packet Format}
+
+The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
+
+\begin{verbatim}
+ECCEncrypt ::= SEQUENCE {
+   hashID        OBJECT IDENTIFIER, -- OID of hash used
+   pubkey        OCTET STRING     , -- Encapsulated ECCPublicKey (see above)
+   skey          OCTET STRING       -- xor of plaintext and "hash of shared secret"
+}
+\end{verbatim}
+
 There are also functions to sign and verify the hash of a message.
+\index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
 \begin{verbatim}
 int ecc_sign_hash(const unsigned char *in,  unsigned long inlen,
                         unsigned char *out, unsigned long *outlen,
@@ -1807,248 +3144,597 @@ The ``ecc\_sign\_hash'' function signs the message hash in ``in'' of length ``in
 The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''.  It sets ``stat''
 to non-zero if the signature passes or zero if it fails.
 
+\subsection{Signature Format}
+The signature code is an implementation of X9.62 EC-DSA and the output is comformant for GF(p) curves.
 
 \section{ECC Keysizes}
 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
 and in effect the signature will still work.  With ECC keys the strength of the signature is limited by the size of
-the hash or the size of they key, whichever is smaller.  For example, if you sign with SHA256 and a ECC-160 key in effect
-you have 160-bits of security (e.g. as if you signed with SHA-1).  
+the hash or the size of they key, whichever is smaller.  For example, if you sign with SHA256 and an ECC-192 key in effect
+you have 192-bits of security.  
 
 The library will not warn you if you make this mistake so it is important to check yourself before using the 
 signatures.
 
-\chapter{Public Keyrings}
+\chapter{Digital Signature Algorithm}
 \section{Introduction}
-In order to simplify the usage of the public key algorithms a set of keyring routines have been developed.  They let the 
-developer manage asymmetric keys by providing load, save, export, import routines as well as encrypt, decrypt, sign, verify
-routines in a unified API.  That is all three types of PK systems can be used within the same keyring with the same API.
+The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to 
+reduce the bandwidth of a signature.  For example, to have ``80-bits of security'' with ElGamal you need a group of 
+order at least 1024-bits.  With DSA you need a group of order at least 160-bits.  By comparison the ElGamal signature
+would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.  
+
+The API for the DSA is essentially the same as the other PK algorithms.  Except in the case of DSA no encryption or
+decryption routines are provided.  
+
+\section{Key Format}
+Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
+now so that others can interoperate with this library.
 
-To define types of keys there are four enumerations used globaly:
 \begin{verbatim}
-enum {
-   NON_KEY=0,
-   RSA_KEY,
-   DH_KEY,
-   ECC_KEY
-};
+DSAPublicKey ::= SEQUENCE {
+    publicFlags    BIT STRING(1), -- must be 0
+    g              INTEGER      , -- base generator, check that g^q mod p == 1
+                                  -- and that 1 < g < p - 1
+    p              INTEGER      , -- prime modulus 
+    q              INTEGER      , -- order of sub-group (must be prime)
+    y              INTEGER      , -- public key, specifically, g^x mod p, 
+                                  -- check that y^q mod p == 1
+                                  -- and that 1 < y < p - 1
+}
+
+DSAPrivateKey ::= SEQUENCE {
+    publicFlags    BIT STRING(1), -- must be 1
+    g              INTEGER      , -- base generator, check that g^q mod p == 1
+                                  -- and that 1 < g < p - 1
+    p              INTEGER      , -- prime modulus 
+    q              INTEGER      , -- order of sub-group (must be prime)
+    y              INTEGER      , -- public key, specifically, g^x mod p, 
+                                  -- check that y^q mod p == 1
+                                  -- and that 1 < y < p - 1
+    x              INTEGER        -- private key
+}
 \end{verbatim}
 
-To make use of the system the developer has to know how link-lists work.  The main structure that the keyring routines use 
-is the ``pk\_key'' defined as:
-\begin{small}
+The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys.  This makes the structure uniquely decodable and easy
+to work with.
+
+\section{Key Generation}
+To make a DSA key you must call the following function
 \begin{verbatim}
-typedef struct Pk_key {
-    int     key_type,             /* PUBLIC, PRIVATE, PRIVATE_OPTIMIZED */
-            system;               /* RSA, ECC or DH ?   */
+int dsa_make_key(prng_state *prng, int wprng, 
+                 int group_size, int modulus_size, 
+                 dsa_key *key);
+\end{verbatim}
+The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor.  ``group\_size'' and 
+``modulus\_size'' control the difficulty of forging a signature.  Both parameters are in bytes.  The larger the
+``group\_size'' the more difficult a forgery becomes upto a limit.  The value of $group\_size$ is limited by 
+$15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$.  Suggested values for the pairs are as follows.
 
-    char    name[MAXLEN],         /* various info's about this key */
-            email[MAXLEN],
-            description[MAXLEN];
+\begin{center}
+\begin{tabular}{|c|c|c|}
+\hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
+\hline 80  & 20 & 128 \\
+\hline 120 & 30 & 256 \\
+\hline 140 & 35 & 384 \\
+\hline 160 & 40 & 512 \\
+\hline
+\end{tabular}
+\end{center}
 
-    unsigned long ID;             /* CRC32 of the name/email/description together */
+When you are finished with a DSA key you can call the following function to free the memory used.
+\index{dsa\_free()}
+\begin{verbatim}
+void dsa_free(dsa_key *key);
+\end{verbatim}
+
+\section{Key Verification}
+Each DSA key is composed of the following variables.
+
+\begin{enumerate}
+  \item $q$ a small prime of magnitude $256^{group\_size}$.  
+  \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
+  \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$.  $h$ can be any non-trivial random 
+        value.  For this library they start at $h = 2$ and step until $g$ is not $1$.
+  \item $x$ a random secret (the secret key) in the range $1 < x < q$ 
+  \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
+\end{enumerate}
+
+A DSA key is considered valid if it passes all of the following tests.
+
+\begin{enumerate}
+   \item $q$ must be prime.
+   \item $p$ must be prime.
+   \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
+   \item $g$ must be less than $p$.
+   \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
+   \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
+   \item $1 < y < p - 1$
+   \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
+\end{enumerate}
+
+Tests one and two ensure that the values will at least form a field which is required for the signatures to  
+function.  Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
+forgery easier.  Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
+ensures that the generator actually generates a prime order group.  Tests seven and eight ensure that the public key
+is within range and belongs to a group of prime order.  Note that test eight does not prove that $g$ generated $y$ only
+that $y$ belongs to a multiplicative sub-group of order $q$. 
 
-    _pk_key key;
+The following function will perform these tests.
 
-    struct Pk_key  *next;         /* linked list chain */
-} pk_key;
+\index{dsa\_verify\_key()}
+\begin{verbatim}
+int dsa_verify_key(dsa_key *key, int *stat);
 \end{verbatim}
-\end{small}
 
-The list is chained via the ``next'' member and terminated with the node of the list that has ``system'' equal to 
-{\bf NON\_KEY}.
+This will test ``key'' and store the result in ``stat''.  If the result is $stat = 0$ the DSA key failed one of the tests
+and should not be used at all.  If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).
 
-\section{The Keyring API}
-To initialize a blank keyring the function ``kr\_init()'' is used.
+\section{Signatures}
+To generate a DSA signature call the following function
+
+\index{dsa\_sign\_hash()}
 \begin{verbatim}
-int kr_init(pk_key **pk);
+int dsa_sign_hash(const unsigned char *in,  unsigned long inlen,
+                        unsigned char *out, unsigned long *outlen,
+                        prng_state *prng, int wprng, dsa_key *key);
 \end{verbatim}
-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
-pointer.
 
-Now instead of calling the PK specific ``make\_key'' functions there is one function that can make all three types of keys.
+Which will sign the data in ``in'' of length ``inlen'' bytes.  The signature is stored in ``out'' and the size
+of the signature in ``outlen''.  If the signature is longer than the size you initially specify in ``outlen'' nothing
+is stored and the function returns an error code.  The DSA ``key'' must be of the \textbf{PK\_PRIVATE} persuasion.
+
+To verify a hash created with that function use the following function
+
+\index{dsa\_verify\_hash()} 
 \begin{verbatim}
-int kr_make_key(pk_key *pk, prng_state *prng, int wprng, 
-                int system, int keysize, const char *name,
-                const char *email, const char *description);
+int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
+                    const unsigned char *hash, unsigned long inlen, 
+                    int *stat, dsa_key *key);
 \end{verbatim}
-The ``name'', ``email'' and ``description'' parameters are simply little pieces of information that you can tag along with a
-key.  They can each be either blank or any string less than 256 bytes.  ``system'' is one of the enumeration elements, that
-is {\bf RSA\_KEY}, {\bf DH\_KEY} or {\bf ECC\_KEY}.  ``keysize'' is the size of the key you desire which is regulated by
-the individual systems, for example, RSA keys are limited in keysize from 128 to 512 bytes.
+Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.  
+It will set ``stat'' to $1$ if the signature is valid, otherwise it sets ``stat'' to $0$.  
 
-To find keys along a keyring there are two functions provided:
+\section{Import and Export}
+
+To export a DSA key so that it can be transported use the following function
+\index{dsa\_export()}
 \begin{verbatim}
-pk_key *kr_find(pk_key *pk, unsigned long ID);
+int dsa_export(unsigned char *out, unsigned long *outlen, 
+               int type, 
+               dsa_key *key);
+\end{verbatim}
+This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
+initialized to the maximum buffer size).  The ``type`` variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
+depending on whether you want to export a private or public copy of the DSA key.
 
-pk_key *kr_find_name(pk_key *pk, const char *name);
+To import an exported DSA key use the following function
+
+\index{dsa\_import()}
+\begin{verbatim}
+int dsa_import(const unsigned char *in, unsigned long inlen, 
+               dsa_key *key);
 \end{verbatim}
-The first searches by the 32-bit ID provided and the latter checks the name against the keyring.  They both return a pointer
-to the node in the ring of a match or {\bf NULL} if no match is found.
 
-To export or import a single node of a keyring the two functions are provided:
+This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''.  If the process fails the function
+will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).  
+
+\chapter{Standards Support}
+\section{ASN.1 Formats}
+LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols.  The data types
+are all provided with three basic functions with \textit{similar} prototypes.  One function has been dedicated to calculate the length in octets of a given
+format and two functions have been dedicated to encoding and decoding the format.  
+
+On top of the basic data types are the SEQUENCE and\footnote{Planned for LTC 1.06} SET data types which are collections of other ASN.1 types.  They are provided 
+in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure.  It is defined as 
+
+\index{ltc\_asn1\_list structure}
 \begin{verbatim}
-int kr_export(pk_key *pk, unsigned long ID, int key_type, 
-              unsigned char *out, unsigned long *outlen);
+typedef struct {
+   int           type;
+   void         *data;
+   unsigned long size;
+   int           used;
+} ltc_asn1_list;
+\end{verbatim}
+
+The ``type'' field is one of the following ASN.1 field definitions.  The ``data'' pointer is a void pointer to the data to be encoded (or the destination) and the 
+``size'' field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type).  The ``used'' field is primarily for the CHOICE decoder
+and reflects if the particular member of a list was the decoded data type.  To help build the lists in an orderly fashion the macro
+``LTC\_SET\_ASN1(list, index, Type, Data, Size)'' has been provided.
 
-int kr_import(pk_key *pk, const unsigned char *in);
+It will assign to the ``index''th position in the ``list'' the tripplet (Type, Data, Size).  An example usage would be:
+
+\begin{small}
+\begin{verbatim}
+...
+ltc_asn1_list   sequence[3];
+unsigned long   three=3;
+
+LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING,    "hello", 5);
+LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three,  1);
+LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL,           NULL,   0);
 \end{verbatim}
-The export function exports the key with an ID provided and of a specific type much like the normal PK export routines.  The
-``key\_type'' is one of {\bf PK\_PUBLIC} or {\bf PK\_PRIVATE}.  In this function with RSA keys the type 
-{\bf PK\_PRIVATE\_OPTIMIZED} is the same as the {\bf PK\_PRIVATE} type.  The import function will read in a packet and 
-add it to the keyring.  
+\end{small}
 
-To load and save whole keyrings from disk:
+The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
+
+\begin{small}
 \begin{verbatim}
-int kr_load(pk_key **pk, FILE *in, symmetric_CTR *ctr);
+...
+ltc_asn1_list   sequence[3];
+unsigned long   three=3;
+int             x=0;
+LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING,    "hello", 5);
+LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three,  1);
+LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL,           NULL,   0);
+\end{verbatim}
+\end{small}
+
+\begin{figure}[here]
+\begin{center}
+\begin{small}
+\begin{tabular}{|l|l|}
+\hline \textbf{Definition}           & \textbf{ASN.1 Type} \\
+\hline LTC\_ASN1\_EOL                & End of a ASN.1 list structure. \\
+\hline LTC\_ASN1\_INTEGER            & INTEGER (uses mp\_int) \\
+\hline LTC\_ASN1\_SHORT\_INTEGER     & INTEGER (32--bit using unsigned long) \\
+\hline LTC\_ASN1\_BIT\_STRING        & BIT STRING (one bit per char) \\
+\hline LTC\_ASN1\_OCTET\_STRING      & OCTET STRING (one octet per char) \\
+\hline LTC\_ASN1\_NULL               & NULL \\
+\hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER (words are in unsigned long) \\
+\hline LTC\_ASN1\_IA5\_STRING        & IA5 STRING (one octet per char) \\
+\hline LTC\_ASN1\_PRINTABLE\_STRING  & PRINTABLE STIRNG (one octet per char) \\
+\hline LTC\_ASN1\_UTCTIME            & UTCTIME (see ltc\_utctime structure) \\
+\hline LTC\_ASN1\_SEQUENCE           & SEQUENCE OF \\
+\hline LTC\_ASN1\_CHOICE             & CHOICE \\
+\hline
+\end{tabular}
+\caption{List of ASN.1 Supported Types}
+\end{small}
+\end{center}
+\end{figure}
+
+\subsection{SEQUENCE Type}
+The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
 
-int kr_save(pk_key *pk, FILE *out, symmetric_CTR *ctr);
+\subsubsection{SEUQNECE Encoding}
+To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers.  The encoding is performed
+with the following function.
+
+\index{der\_encode\_sequence()}
+\begin{verbatim}
+int der_encode_sequence(ltc_asn1_list *list, unsigned long inlen,
+                        unsigned char *out,  unsigned long *outlen);
 \end{verbatim}
-Both take file pointers to allow the user to pre-append data to the stream.  The ``ctr'' parameter should be setup with 
-``ctr\_start'' or set to NULL.  This parameter lets the user encrypt the keyring as its written to disk, if it is set
-to NULL the data is written without being encrypted.  The load function assumes the list has not been initialized yet 
-and will reset the pointer given to it.
+This encodes a sequence of items pointed to by ``list'' where the list has ``inlen'' items in it.  The SEQUENCE will be encoded to ``out'' and of length ``outlen''.  The
+function will terminate when it reads all the items out of the list (upto ``inlen'') or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
+
+The ``data'' pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
+verbatim to the dependent encoder.  The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions.  In these cases
+the ``data'' pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
+
+\subsubsection{SEQUENCE Decoding}
+
+\index{der\_decode\_sequence()}
+
+Decoding a SEQUENCE is similar to encoding.  You set up an array of \textbf{ltc\_asn1\_list} where in this case the ``size'' member is the maximum size 
+(in certain cases).  For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the ``size'' field is updated after successful decoding to reflect how many
+units of the respective type has been loaded.  
 
-There are the four encrypt, decrypt, sign and verify functions as well
 \begin{verbatim}
-int kr_encrypt_key(pk_key *pk, unsigned long ID, 
-                   const unsigned char *in, unsigned long inlen,
-                   unsigned char *out, unsigned long *outlen,
-                   prng_state *prng, int wprng, int hash);
+int der_decode_sequence(const unsigned char *in,   unsigned long  inlen,
+                              ltc_asn1_list *list, unsigned long  outlen);
+\end{verbatim}
+
+This will decode upto ``outlen'' items from the input buffer ``in'' of length ``inlen'' octets.  The function will stop (gracefully) when it runs out of items to decode.
+It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occured.
+
+For the following types the ``size'' field will be updated to reflect the number of units read of the given type.
+\begin{enumerate}
+   \item BIT STRING
+   \item OCTET STRING
+   \item OBJECT IDENTIFIER
+   \item IA5 STRING
+   \item PRINTABLE STRING
+\end{enumerate}
+
+\subsubsection{SEQUENCE Length}
 
-int kr_decrypt_key(pk_key *pk, const unsigned char *in,
-                   unsigned char *out, unsigned long *outlen);
+The length of a SEQUENCE can be determined with the following function.
+
+\index{der\_length\_sequence()}
+\begin{verbatim}
+int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
+                        unsigned long *outlen);
 \end{verbatim}
 
-The kr\_encrypt\_key() routine is designed to encrypt a symmetric key with a specified users public key.  The symmetric
-key is then used with a block cipher to encode the message.  The recipient can call kr\_decrypt\_key() to get the original
-symmetric key back and decode the message.  The hash specified must produce a message digest longer than symmetric key 
-provided.  
+This will get the encoding size for the given ``list'' of length ``inlen'' and store it in ``outlen''.  
+
+\subsubsection{SEQUENCE Multiple Argument Lists}
+
+For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
+
+\index{der\_encode\_sequence\_multi()}
+\index{der\_decode\_sequence\_multi()}
 
 \begin{verbatim}
-int kr_sign_hash(pk_key *pk, unsigned long ID, 
-                 const unsigned char *in, unsigned long inlen,
-                 unsigned char *out, unsigned long *outlen,
-                 prng_state *prng, int wprng);
+int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
+int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
+\end{verbatim}
+
+These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
+
+The list of items are specified as a triple of the form ``(type, size, data)''  where ``type'' is an \textbf{int}, ``size'' is a \textbf{unsigned long}
+and ``data'' is \textbf{void} pointer.  The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
 
-int kr_verify_hash(pk_key *pk, const unsigned char *in, 
-                   const unsigned char *hash, unsigned long hashlen,
-                   int *stat);
+It's ideal that you cast the ``size'' values to unsigned long to ensure that the proper data type is passed to the function.  Constants such as ``1'' without
+a cast or prototype are of type \textbf{int} by default.  Appending \textit{UL} or prepending \textit{(unsigned long)} is enough to cast it to the correct type.
+
+\subsection{ASN.1 INTEGER}
+
+To encode or decode INTEGER data types use the following functions.
+
+\index{der\_encode\_integer()}
+\index{der\_decode\_integer()}
+\index{der\_length\_integer()}
+\begin{verbatim}
+int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
+int der_decode_integer(const unsigned char *in, unsigned long inlen, mp_int *num);
+int der_length_integer(mp_int *num, unsigned long *len);
 \end{verbatim}
 
-Similar to the two previous these are used to sign a message digest or verify one.  This requires hashing the message
-first then passing the output in. 
+These will encode or decode a signed INTEGER data type using the ``mp\_int'' data type to store the large INTEGER.  To encode smaller values without allocating
+an mp\_int to store the value the ``short'' INTEGER functions were made available.
 
-To delete keys and clear rings there are:
+\index{der\_encode\_short\_integer()}
+\index{der\_decode\_short\_integer()}
+\index{der\_length\_short\_integer()}
 \begin{verbatim}
-int kr_del(pk_key **_pk, unsigned long ID);
-int kr_clear(pk_key **pk);
+int der_encode_short_integer(unsigned long  num, 
+                             unsigned char *out, unsigned long *outlen);
+
+int der_decode_short_integer(const unsigned char *in,  unsigned long inlen, 
+                                   unsigned long *num);
+
+int der_length_short_integer(unsigned long num, unsigned long *outlen);
 \end{verbatim}
-``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
-the memory associated with it.  Below is small example using the keyring API:
 
-\begin{small}
+These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits).  For values in the range $0 \dots 2^{32} - 1$ the integer 
+and short integer functions can encode and decode each others outputs.  
+
+\subsection{ASN.1 BIT STRING}
+
+\index{der\_encode\_bit\_string()}
+\index{der\_decode\_bit\_string()}
+\index{der\_length\_bit\_string()}
 \begin{verbatim}
-#include <mycrypt.h>
-int main(void)
-{
-   pk_key *kr;
-   unsigned char buf[4096], buf2[4096];
-   unsigned long len;
-   int errno;
+int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
 
-   /* make a new list */
-   if ((errno = kr_init(&kr)) != CRYPT_OK) {
-      printf("kr_init: %s\n", error_to_string(errno));
-      exit(-1);
-   }
+int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
 
-   /* add a key to it */
-   register_prng(&sprng_desc);
-   if ((errno = kr_make_key(kr, NULL, find_prng("sprng"), RSA_KEY, 128, 
-                "TomBot", "tomstdenis@yahoo.com", "test key")) == CRYPT_OK) {
-      printf("kr_make_key: %s\n", error_to_string(errno));
-      exit(-1);
-   }
+int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
+\end{verbatim}
 
-   /* export the first key */
-   len = sizeof(buf);
-   if ((errno = kr_export(kr, kr->ID, PK_PRIVATE, buf, &len)) != CRYPT_OK) {
-      printf("kr_export: %s\n", error_to_string(errno));
-      exit(-1);
-   }
+These will encode or decode a BIT STRING data type.  The bits are passed in (or read out) using one \textbf{char} per bit.  A non--zero value will be interpretted
+as a one bit and a zero value a zero bit.
 
-   /* ... */
-}  
+\subsection{ASN.1 OCTET STRING}
+
+\index{der\_encode\_octet\_string()}
+\index{der\_decode\_octet\_string()}
+\index{der\_length\_octet\_string()}
+\begin{verbatim}
+int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
+                                  unsigned char *out, unsigned long *outlen);
+
+int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
+                                  unsigned char *out, unsigned long *outlen);
+
+int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
 \end{verbatim}
-\end{small}
 
-\chapter{$GF(2^w)$ Math Routines}
+These will encode or decode an OCTET STRING data type.  The octets are stored using one \textbf{char} each.  
+
+\subsection{ASN.1 OBJECT IDENTIFIER}
+
+\index{der\_encode\_object\_identifier()}
+\index{der\_decode\_object\_identifier()}
+\index{der\_length\_object\_identifier()}
+\begin{verbatim}
+int der_encode_object_identifier(unsigned long *words, unsigned long  nwords,
+                                 unsigned char *out,   unsigned long *outlen);
+
+int der_decode_object_identifier(const unsigned char *in,    unsigned long  inlen,
+                                       unsigned long *words, unsigned long *outlen);
+
+int der_length_object_identifier(unsigned long *words, unsigned long nwords, 
+                                 unsigned long *outlen);
+\end{verbatim}
+
+These will encode or decode an OBJECT IDENTIFIER object.  The words of the OID are stored in individual \textbf{unsigned long} elements and must be in the range
+$0 \ldots 2^{32} - 1$.  
+
+\subsection{ASN.1 IA5 STRING}
+
+\index{der\_encode\_ia5\_string()}
+\index{der\_decode\_ia5\_string()}
+\index{der\_length\_ia5\_string()}
+\begin{verbatim}
+int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
+
+int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
+
+int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, 
+                                unsigned long *outlen);
+\end{verbatim}
 
-The library provides a set of polynomial-basis $GF(2^w)$ routines to help facilitate algorithms such as ECC over such
-fields.  Note that the current implementation of ECC in the library is strictly over the integers only.  The routines
-are simple enough to use for other purposes outside of ECC.  
+These will encode or decode an IA5 STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
+to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
+say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
+that the build platform honours the runtime platforms character conventions.
 
-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 
-$L$ 32-bit words.  You can configure the maximum size $L$ of the ``gf\_int'' type by opening the file ``mycrypt.h'' and 
-changing ``LSIZE''.  Note that if you set it to $n$ then you can only multiply upto two $n \over 2$ bit polynomials without
-an overflow.  The type ``gf\_intp'' is associated with a pointer to an ``unsigned long'' as required in the algorithms.
+If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
 
-There are no initialization routines for ``gf\_int'' variables and you can simply use them after declaration.  There are five
-low level functions:
-\index{gf\_copy()} \index{gf\_zero()} \index{gf\_iszero()} \index{gf\_isone()} 
-\index{gf\_deg()} 
+\subsection{ASN.1 PRINTABLE STRING}
+
+\index{der\_encode\_printable\_string()}
+\index{der\_decode\_printable\_string()}
+\index{der\_length\_printable\_string()}
 \begin{verbatim}
-void gf_copy(gf_intp a, gf_intp b);
-void gf_zero(gf_intp a);
-int gf_iszero(gf_intp a);
-int gf_isone(gf_intp a);
-int gf_deg(gf_intp a);
+int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
+
+int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
+                                unsigned char *out, unsigned long *outlen);
+
+int der_length_printable_string(const unsigned char *octets, unsigned long noctets, 
+                                unsigned long *outlen);
 \end{verbatim}
-There are all fairly self-explanatory.  ``gf\_copy(a, b)'' copies the contents of ``a'' into ``b''.  ``gf\_zero()'' simply
-zeroes the entire polynomial.  ``gf\_iszero()'' tests to see if the polynomial is all zero and ``gf\_isone()'' tests to see
-if the polynomial is equal to the multiplicative identity.  ``gf\_deg()'' returns the degree of the polynomial or $-1$ if its
-a zero polynomial.
 
-There are five core math routines as well:
-\index{gf\_shl()} \index{gf\_shr()} \index{gf\_add()} \index{gf\_mul()} \index{gf\_div()} 
+These will encode or decode an PRINTABLE STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
+to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
+say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
+that the build platform honours the runtime platforms character conventions.
+
+If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
+
+\subsection{ASN.1 UTCTIME}
+
+The UTCTIME type is to store a date and time in ASN.1 format.  It uses the following structure to organize the time.
+
 \begin{verbatim}
-void gf_shl(gf_intp a, gf_intp b);
-void gf_shr(gf_intp a, gf_intp b);
-void gf_add(gf_intp a, gf_intp b, gf_intp c);
-void gf_mul(gf_intp a, gf_intp b, gf_intp c);
-void gf_div(gf_intp a, gf_intp b, gf_intp q, gf_intp r);
+typedef struct {
+   unsigned YY, /* year    00--99 */
+            MM, /* month   01--12 */
+            DD, /* day     01--31 */
+            hh, /* hour    00--23 */
+            mm, /* minute  00--59 */
+            ss, /* second  00--59 */
+            off_dir, /* timezone offset direction 0 == +, 1 == - */
+            off_hh, /* timezone offset hours */
+            off_mm; /* timezone offset minutes */
+} ltc_utctime;
 \end{verbatim}
 
-Which are all fairly obvious.  ``gf\_shl(a,b)'' multiplies the polynomial ``a'' by $x$ and stores it in ``b''.  
-``gf\_shl(a,b)'' divides the polynomial ``a'' by $x$ and stores it in ``b''.  ``gf\_add(a,b,c)'' adds the polynomial
-``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
-``a'' by ``b'' and stores the quotient in ``q'' and the remainder in ``r''.
+The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When ``off\_dir'' is zero the time will be added otherwise it 
+will be subtracted.  
+
+For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of 2005, June 20th, 22:04:00 with a time offset of +05h00.  
 
-There are six number theoretic functions as well:
-\index{gf\_mod()} \index{gf\_mulmod()} \index{gf\_invmod()} \index{gf\_gcd()} \index{gf\_is\_prime()} 
-\index{gf\_sqrt()}
+\index{der\_encode\_utctime()}
+\index{der\_decode\_utctime()}
+\index{der\_length\_utctime()}
 \begin{verbatim}
-void gf_mod(gf_intp a, gf_intp m, gf_intp b);
-void gf_mulmod(gf_intp a, gf_intp b, gf_intp m, gf_intp c);
-void gf_invmod(gf_intp A, gf_intp M, gf_intp B);
-void gf_sqrt(gf_intp a, gf_intp m, gf_intp b);
-void gf_gcd(gf_intp A, gf_intp B, gf_intp c);
-int gf_is_prime(gf_intp a);
+int der_encode_utctime(ltc_utctime *utctime, 
+                       unsigned char *out,   unsigned long *outlen);
+
+int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
+                             ltc_utctime   *out);
+
+int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
 \end{verbatim}
 
-Which all work similarly except for  ``gf\_mulmod(a,b,m,c)'' which computes $c = ab\mbox{ }(\mbox{mod }m)$.  The 
-``gf\_is\_prime()'' function returns one if the polynomial is primitive, otherwise it returns zero.
+The encoder will store time in one of the two ASN.1 formats, either ``YYMMDDhhmmssZ'' or ``YYMMDDhhmmss$\pm$hhmm'' and perform minimal error checking on the 
+input.  The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
+
+It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
+
+\subsection{ASN.1 CHOICE}
 
-Finally to read/store a ``gf\_int'' in a binary string use:
-\index{gf\_size()} \index{gf\_toraw()} \index{gf\_readraw()} 
+The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a ``ltc\_asn1\_list''.  There is no encoder for the CHOICE type, only a 
+decoder.  The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet.  The list can contain any ASN.1 data
+type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.  
+
+There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.  
+
+\index{der\_decode\_choice()}
 \begin{verbatim}
-int gf_size(gf_intp a);
-void gf_toraw(gf_intp a, unsigned char *dst);
-void gf_readraw(gf_intp a, unsigned char *str, int len);
+int der_decode_choice(const unsigned char *in,   unsigned long *inlen,
+                            ltc_asn1_list *list, unsigned long  outlen);
 \end{verbatim}
-Where ``gf\_size()'' returns the size in bytes required for the data.  ``gf\_toraw(a,b)'' stores the polynomial in ``b''
-in binary format (endian neutral).  ``gf\_readraw(a,b,c)'' reads the binary string in ``b'' back.  Note that the length 
-you pass it must be the same as returned by ``gf\_size()'' or it will not load correctly.
+
+This will decode the input in the ``in'' field of length ``inlen''.  It uses the provided ASN.1 list specified in the ``list'' field which has ``outlen'' elements.  
+The ``inlen'' field will be updated with the length of the decoded data type as well as the respective entry in the ``list'' field will have the ``used'' flag 
+set to non--zero to reflect it was the data type decoded.
+
+\section{Password Based Cryptography}
+\subsection{PKCS \#5}
+\index{PKCS \#5}
+In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted.   PKCS \#5
+is made up of two algorithms, Algorithm One and Algorithm Two.  Algorithm One is the older fairly limited algorithm which has been implemented
+for completeness.  Algorithm Two is a bit more modern and more flexible to work with.
+
+\subsection{Algorithm One}
+Algorithm One accepts as input a password, an 8--byte salt and an iteration counter.  The iteration counter is meant to act as delay for
+people trying to brute force guess the password.  The higher the iteration counter the longer the delay.  This algorithm also requires a hash 
+algorithm and produces an output no longer than the output of the hash.  
+
+\index{pkcs\_5\_alg1()}
+\begin{alltt}
+int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, 
+                const unsigned char *salt, 
+                int iteration_count,  int hash_idx,
+                unsigned char *out,   unsigned long *outlen)
+\end{alltt}
+Where ``password'' is the users password.  Since the algorithm allows binary passwords you must also specify the length in ``password\_len''.  
+The ``salt'' is a fixed size 8--byte array which should be random for each user and session.  The ``iteration\_count'' is the delay desired
+on the password.  The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table.  
+
+The output of length upto ``outlen'' is stored in ``out''.  If ``outlen'' is initially larger than the size of the hash functions output
+it is set to the number of bytes stored.  If it is smaller than not all of the hash output is stored in ``out''.
+
+\subsection{Algorithm Two}
+
+Algorithm Two is the recommended algorithm for this task.  It allows variable length salts and can produce outputs larger than the 
+hash functions output.  As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
+from a single password and invokation of this algorithm.
+
+\index{pkcs\_5\_alg2()}
+\begin{alltt}
+int pkcs_5_alg2(const unsigned char *password, unsigned long password_len, 
+                const unsigned char *salt,     unsigned long salt_len,
+                int iteration_count,           int hash_idx,
+                unsigned char *out,            unsigned long *outlen)
+\end{alltt}
+Where ``password'' is the users password.  Since the algorithm allows binary passwords you must also specify the length in ``password\_len''.  
+The ``salt'' is an array of size ``salt\_len''.  It should be random for each user and session.  The ``iteration\_count'' is the delay desired
+on the password.  The ``hash\_idx'' is the index of the hash you wish to use in the descriptor table.   The output of length upto 
+``outlen'' is stored in ``out''.
+
+\begin{alltt}
+/* demo to show how to make session state material from a password */
+#include <tomcrypt.h>
+int main(void)
+\{
+    unsigned char password[100], salt[100],
+                  cipher_key[16], cipher_iv[16],
+                  mac_key[16], outbuf[48];
+    int           err, hash_idx;
+    unsigned long outlen, password_len, salt_len;
+
+    /* register hash and get it's idx .... */
+
+    /* get users password and make up a salt ... */
+
+    /* create the material (100 iterations in algorithm) */
+    outlen = sizeof(outbuf);
+    if ((err = pkcs_5_alg2(password, password_len, salt, salt_len, 
+                           100, hash_idx, outbuf, &outlen)) != CRYPT_OK) \{
+       /* error handle */
+    \}
+
+    /* now extract it */
+    memcpy(cipher_key, outbuf, 16);
+    memcpy(cipher_iv,  outbuf+16, 16);
+    memcpy(mac_key,    outbuf+32, 16);
+
+    /* use material (recall to store the salt in the output) */
+\}
+\end{alltt}
 
 \chapter{Miscellaneous}
 \section{Base64 Encoding and Decoding}
@@ -2088,7 +3774,7 @@ for all uses and is distributed freely.
 At the heart of all the functions is the data type ``mp\_int'' (defined in tommath.h).  This data type is what 
 will hold all large integers.  In order to use an mp\_int one must initialize it first, for example:
 \begin{verbatim}
-#include <mycrypt.h> /* mycrypt.h includes mpi.h automatically */
+#include <tomcrypt.h> /* tomcrypt.h includes mpi.h automatically */
 int main(void)
 { 
    mp_int bignum;
@@ -2247,7 +3933,6 @@ $n$ it requires $\sqrt n$ work.  The following table sumarizes the work required
 \begin{center}
 \begin{tabular}{|c|c|}
     \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
-    \hline 160 & 80  \\
     \hline 192 & 96  \\
     \hline 224 & 112 \\
     \hline 256 & 128 \\
@@ -2283,18 +3968,67 @@ possible as some compilers may ignore the ``volatile'' keyword or have multiple
 is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread
 safety issues within the library.
 
-\chapter{Configuring the Library}
+\chapter{Configuring and Building the Library}
 \section{Introduction}
 The library is fairly flexible about how it can be built, used and generally distributed.  Additions are being made with
-each new release that will make the library even more flexible.  Most options are placed in the makefile and others
-are in ``mycrypt\_cfg.h''.  All are used when the library is built from scratch.
+each new release that will make the library even more flexible.  Each of the classes of functions can be disabled during
+the build process to make a smaller library.  This is particularly useful for shared libraries.
+
+\section{Building a Static Library}
+The library can be built as a static library which is generally the simplest and most portable method of 
+building the library.  With a CC or GCC equipped platform you can issue the following
+
+\begin{alltt}
+make install_lib
+\end{alltt}
+
+Which will build the library and install it in /usr/lib (as well as the headers in /usr/include).  The destination
+directory of the library and headers can be changed by editing ``makefile''.  The variable LIBNAME controls
+where the library is to be installed and INCNAME controls where the headers are to be installed.  A developer can 
+then use the library by including ``tomcrypt.h'' in their program and linking against ``libtomcrypt.a''.
 
-For GCC platforms the file ``makefile'' is the makefile to be used.  On MSVC platforms ``makefile.vc'' and on PS2 platforms
-``makefile.ps2''.
+A static library can also be built with the Intel C Compiler  (ICC) by issuing the following
 
-\section{mycrypt\_cfg.h}
-The file ``mycrypt\_cfg.h'' is what lets you control what functionality you want to remove from the library.  By default,
-everything the library has to offer it built.  
+\begin{alltt}
+make -f makefile.icc install
+\end{alltt}
+
+This will also build ``libtomcrypt.a'' except that it will use ICC.  Additionally Microsoft's Visual C 6.00 can be used
+by issuing
+
+\begin{alltt}
+nmake -f makefile.msvc
+\end{alltt}
+
+You will have to manually copy ``tomcrypt.lib'' and the headers to your MSVC lib/inc directories.
+
+\subsection{MPI Control}
+If you already have LibTomMath installed you can safely remove it from the build.  By commenting the line
+in the appropriate makefile which starts with 
+
+\begin{alltt}
+MPIOBJECT=mpi
+\end{alltt}
+
+Simply place a \# at the start and re-build the library.  To properly link applications you will have to also
+link in LibTomMath.  Removing MPI has the benefit of cutting down the library size as well potentially have access
+to the latest mpi.
+
+\section{Building a Shared Library}
+LibTomCrypt can also be built as a shared library (.so, .dll, etc...).  With non-Windows platforms the assumption
+of the presence of gcc and ``libtool'' has been made.  These are fairly common on Unix/Linux/BSD platforms.  To
+build a .so shared library issue 
+
+\begin{alltt}
+make -f makefile.shared
+\end{alltt}
+This will use libtool and gcc to build a shared library ``libtomcrypt.la'' as well as a static library ``libtomcrypt.a''
+and install them into /usr/lib (and the headers into /usr/include).  To link your application you should use the 
+libtool program in ``--mode=link''.
+
+\section{tomcrypt\_cfg.h}
+The file ``tomcrypt\_cfg.h'' is what lets you control various high level macros which control the behaviour 
+of the library. 
 
 \subsubsection{ARGTYPE}
 This lets you control how the \_ARGCHK macro will behave.  The macro is used to check pointers inside the functions against
@@ -2307,37 +4041,43 @@ and no error checking will be performed.
 There are five macros related to endianess issues.  For little endian platforms define, ENDIAN\_LITTLE.  For big endian
 platforms define ENDIAN\_BIG.  Similarly when the default word size of an ``unsigned long'' is 32-bits define ENDIAN\_32BITWORD
 or define ENDIAN\_64BITWORD when its 64-bits.  If you do not define any of them the library will automatically use ENDIAN\_NEUTRAL
-which will work on all platforms.  Currently the system will automatically detect GCC or MSVC on a windows platform as well
-as GCC on a PS2 platform.
+which will work on all platforms.
+
+Currently LibTomCrypt will detect x86-32 and x86-64 running GCC as well as x86-32 running MSVC.  
 
 \section{The Configure Script}
-There are also options you can specify from the configure script or ``mycrypt\_config.h''.  
+There are also options you can specify from the configure script or ``tomcrypt\_custom.h''.  
 
-\subsubsection{X memory routines}
-The makefiles must define three macros denoted as XMALLOC, XCALLOC and XFREE which resolve to the name of the respective
-functions.  This lets you substitute in your own memory routines.  If you substitute in your own functions they must behave
-like the standard C library functions in terms of what they expect as input and output.  By default the library uses the
-standard C routines.
+\subsection{X memory routines}
+At the top of tomcrypt\_custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to 
+the name of the respective functions.  This lets you substitute in your own memory routines.  If you substitute in 
+your own functions they must behave like the standard C library functions in terms of what they expect as input and 
+output.  By default the library uses the standard C routines.
 
-\subsubsection{X clock routines}
+\subsection{X clock routines}
 The rng\_get\_bytes() function can call a function that requires the clock() function.  These macros let you override
 the default clock() used with a replacement.  By default the standard C library clock() function is used.
 
-\subsubsection{NO\_FILE}
+\subsection{NO\_FILE}
 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 
-functions and instead simply return CRYPT\_ERROR.  This should help resolve any linker errors stemming from a lack of
+functions and instead simply return CRYPT\_NOP.  This should help resolve any linker errors stemming from a lack of
 file I/O on embedded platforms.
 
-\subsubsection{CLEAN\_STACK}
-When this functions is defined the functions that store key material on the stack will clean up afterwards.  Assumes that
-you have no memory paging with the stack.
+\subsection{CLEAN\_STACK}
+When this functions is defined the functions that store key material on the stack will clean up afterwards.  
+Assumes that you have no memory paging with the stack.
 
-\subsubsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
-There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly self-explanatory.  
-When they are defined the functionality is included otherwise it is not.  There are some dependency issues which are
-noted in the file.  For instance, Yarrow requires CTR chaining mode, a block cipher and a hash function.
+\subsection{LTC\_TEST}
+When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.
+When this has been undefined the tests are removed and if called will return CRYPT\_NOP.
 
-\subsubsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
+\subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
+There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly 
+self-explanatory.  When they are defined the functionality is included otherwise it is not.  There are some 
+dependency issues which are noted in the file.  For instance, Yarrow requires CTR chaining mode, a block 
+cipher and a hash function.
+
+\subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
 Twofish is a 128-bit symmetric block cipher that is provided within the library.  The cipher itself is flexible enough
 to allow some tradeoffs in the implementation.  When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish 
 requires only 200 bytes of memory.  This is achieved by not pre-computing the substitution boxes.  Having this 
@@ -2349,8 +4089,475 @@ useful when TWOFISH\_SMALL is defined as the table values are computed on the fl
 will increase by approximately 500 bytes.  If this is defined but TWOFISH\_SMALL is not the cipher will still work but
 it will not speed up the encryption or decryption functions.
 
-\subsubsection{SMALL\_CODE}
+\subsection{GCM\_TABLES}
+When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.  
+It also increases the initialization time and isn't suitable when you are going to use a key a few times only.  
+
+\subsection{SMALL\_CODE}
 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
 These variants are slower but can save quite a bit of code space.
 
+\subsection{LTC\_FAST}
+This mode (autodetected with x86\_32,x86\_64 platforms with GCC or MSVC) configures various routines such as ctr\_encrypt() or 
+cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type.  This has the benefit of 
+cutting down the overhead of the respective functions.  
+
+This mode does have one downside.  It can cause unaligned reads from memory if you are not careful with the functions.  This is why
+it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed.  Technically LTC\_FAST
+is not ``portable'' since unaligned accesses are not covered by the ISO C specifications.
+
+In practice however, you can use it on pretty much any platform (even MIPS) with care.
+
+By design the ``fast'' mode functions won't get unaligned on their own.  For instance, if you call ctr\_encrypt() right after calling
+ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only.  However, if you 
+call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used.  This will
+cause the ctr routine to first use up the remaining pad bytes.  Then if there are enough plaintext bytes left it will use 
+whole word XOR operations.  These operations will be unaligned.
+
+The simplest precaution is to make sure you process all data in power of two blocks and handle ``remainder'' at the end.  e.g. If you are 
+CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.  
+
+If you do plan on using the ``LTC\_FAST'' mode you have to also define a ``LTC\_FAST\_TYPE'' macro which resolves to an optimal sized
+data type you can perform integer operations with.  Ideally it should be four or eight bytes since it must properly divide the size 
+of your block cipher (e.g. 16 bytes for AES).  This means sadly if you're on a platform with 57--bit words (or something) you can't 
+use this mode.  So sad.
+
+\subsection{LTC\_PTHREAD}
+When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables.  Note that 
+it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
+
+Generally the rule of thumb is to setup the tables once at startup and then leave them be.  This added build flag simply makes updating
+the tables safer.
+
+\section{MPI Tweaks}
+\subsection{RSA Only Tweak}
+If you plan on only using RSA with moduli in the range of 1024 to 2560 bits you can enable a series of tweaks
+to reduce the library size.  Follow these steps
+
+\begin{enumerate}
+   \item Undefine MDSA, MECC and MDH from tomcrypt\_custom.h
+   \item Undefine LTM\_ALL  from tommath\_superclass.h
+   \item Define SC\_RSA\_1 from tommath\_superclass.h
+   \item Rebuild the library.
+\end{enumerate}
+
+\chapter{Optimizations}
+\section{Introduction}
+The entire API was designed with plug and play in mind at the low level.  That is you can swap out any cipher, hash or PRNG and dependent API will not require
+updating.  This has the nice benefit that I can add ciphers not have to re--write large portions of the API.  For the most part LibTomCrypt has also been written
+to be highly portable and easy to build out of the box on pretty much any platform.  As such there are no assembler inlines throughout the code, I make no assumptions
+about the platform, etc...
+
+That works well for most cases but there are times where time is of the essence.  This API also allows optimized routines to be dropped in--place of the existing
+portable routines.  For instance, hand optimized assembler versions of AES could be provided and any existing function that uses the cipher could automatically use
+the optimized code without re--writing.  This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
+
+At the heart of this flexibility is the ``descriptor'' system.  A descriptor is essentially just a C ``struct'' which describes the algorithm and provides pointers
+to functions that do the work.  For a given class of operation (e.g. cipher, hash, prng) the functions have identical prototypes which makes development simple.  In most
+dependent routines all a developer has to do is register\_XXX() the descriptor and they're set.
+
+\section{Ciphers}
+The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
+
+\begin{small}
+\begin{verbatim}
+struct ltc_cipher_descriptor {
+   /** name of cipher */
+   char *name;
+   /** internal ID */
+   unsigned char ID;
+   /** min keysize (octets) */
+   int  min_key_length, 
+   /** max keysize (octets) */
+        max_key_length, 
+   /** block size (octets) */
+        block_length, 
+   /** default number of rounds */
+        default_rounds;
+   /** Setup the cipher 
+      @param key         The input symmetric key
+      @param keylen      The length of the input key (octets)
+      @param num_rounds  The requested number of rounds (0==default)
+      @param skey        [out] The destination of the scheduled key
+      @return CRYPT_OK if successful
+   */
+   int  (*setup)(const unsigned char *key, int keylen, 
+                 int num_rounds, symmetric_key *skey);
+   /** Encrypt a block
+      @param pt      The plaintext
+      @param ct      [out] The ciphertext
+      @param skey    The scheduled key
+   */
+   void (*ecb_encrypt)(const unsigned char *pt, 
+                             unsigned char *ct, symmetric_key *skey);
+   /** Decrypt a block
+      @param ct      The ciphertext
+      @param pt      [out] The plaintext
+      @param skey    The scheduled key
+   */
+   void (*ecb_decrypt)(const unsigned char *ct, 
+                             unsigned char *pt, symmetric_key *skey);
+   /** Test the block cipher
+       @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
+   */
+   int (*test)(void);
+   /** Determine a key size
+       @param keysize    [in/out] The size of the key desired and the suggested size
+       @return CRYPT_OK if successful
+   */
+   int  (*keysize)(int *keysize);
+
+/** Accelerators **/
+   /** Accelerated ECB encryption 
+       @param pt      Plaintext
+       @param ct      Ciphertext
+       @param blocks  The number of complete blocks to process
+       @param skey    The scheduled key context
+   */
+   void (*accel_ecb_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, unsigned long blocks, 
+                             symmetric_key *skey);
+
+   /** Accelerated ECB decryption 
+       @param pt      Plaintext
+       @param ct      Ciphertext
+       @param blocks  The number of complete blocks to process
+       @param skey    The scheduled key context
+   */
+   void (*accel_ecb_decrypt)(const unsigned char *ct, 
+                                   unsigned char *pt, unsigned long blocks, 
+                             symmetric_key *skey);
+
+   /** Accelerated CBC encryption 
+       @param pt      Plaintext
+       @param ct      Ciphertext
+       @param blocks  The number of complete blocks to process
+       @param IV      The initial value (input/output)
+       @param skey    The scheduled key context
+   */
+   void (*accel_cbc_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, unsigned long blocks, 
+                                   unsigned char *IV, symmetric_key *skey);
+
+   /** Accelerated CBC decryption 
+       @param pt      Plaintext
+       @param ct      Ciphertext
+       @param blocks  The number of complete blocks to process
+       @param IV      The initial value (input/output)
+       @param skey    The scheduled key context
+   */
+   void (*accel_cbc_decrypt)(const unsigned char *ct, 
+                                   unsigned char *pt, unsigned long blocks, 
+                                   unsigned char *IV, symmetric_key *skey);
+
+   /** Accelerated CTR encryption 
+       @param pt      Plaintext
+       @param ct      Ciphertext
+       @param blocks  The number of complete blocks to process
+       @param IV      The initial value (input/output)
+       @param mode    little or big endian counter (mode=0 or mode=1)
+       @param skey    The scheduled key context
+   */
+   void (*accel_ctr_encrypt)(const unsigned char *pt, 
+                                   unsigned char *ct, unsigned long blocks, 
+                                   unsigned char *IV, int mode, symmetric_key *skey);
+
+   /** Accelerated CCM packet (one-shot)
+       @param key        The secret key to use
+       @param keylen     The length of the secret key (octets)
+       @param nonce      The session nonce [use once]
+       @param noncelen   The length of the nonce
+       @param header     The header for the session
+       @param headerlen  The length of the header (octets)
+       @param pt         [out] The plaintext
+       @param ptlen      The length of the plaintext (octets)
+       @param ct         [out] The ciphertext
+       @param tag        [out] The destination tag
+       @param taglen     [in/out] The max size and resulting size of the authentication tag
+       @param direction  Encrypt or Decrypt direction (0 or 1)
+       @return CRYPT_OK if successful
+   */
+   void (*accel_ccm_memory)(
+       const unsigned char *key,    unsigned long keylen,
+       const unsigned char *nonce,  unsigned long noncelen,
+       const unsigned char *header, unsigned long headerlen,
+             unsigned char *pt,     unsigned long ptlen,
+             unsigned char *ct,
+             unsigned char *tag,    unsigned long *taglen,
+                       int  direction);
+
+   /** Accelerated GCM packet (one shot)
+       @param key               The secret key
+       @param keylen            The length of the secret key
+       @param IV                The initial vector 
+       @param IVlen             The length of the initial vector
+       @param adata             The additional authentication data (header)
+       @param adatalen          The length of the adata
+       @param pt                The plaintext
+       @param ptlen             The length of the plaintext (ciphertext length is the same)
+       @param ct                The ciphertext
+       @param tag               [out] The MAC tag
+       @param taglen            [in/out] The MAC tag length
+       @param direction         Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
+   */
+   void (*accel_gcm_memory)(
+       const unsigned char *key,    unsigned long keylen,
+       const unsigned char *IV,     unsigned long IVlen,
+       const unsigned char *adata,  unsigned long adatalen,
+             unsigned char *pt,     unsigned long ptlen,
+             unsigned char *ct, 
+             unsigned char *tag,    unsigned long *taglen,
+                       int direction);
+
+};
+\end{verbatim}
+\end{small}
+
+\subsection{Name}
+The ``name'' parameter specifies the name of the cipher.  This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
+tables.
+
+\subsection{Internal ID}
+This is a single byte Internal ID you can use to distingish ciphers from each other.
+
+\subsection{Key Lengths}
+The minimum key length is ``min\_key\_length'' and is measured in octets.  Similarly the maximum key length is ``max\_key\_length''.  They can be equal
+and both must valid key sizes for the cipher.  Values in between are not assumed to be valid though they may be.
+
+\subsection{Block Length}
+The size of the ciphers plaintext or ciphertext is ``block\_length'' and is measured in octets.
+
+\subsection{Rounds}
+Some ciphers allow different number of rounds to be used.  Usually you just use the default.  The default round count is ``default\_rounds''.
+
+\subsection{Setup}
+To initialize a cipher (for ECB mode) the function setup() was provided.  It accepts an array of key octets ``key'' of length ``keylen'' octets.  The user
+can specify the number of rounds they want through ``num\_rounds'' where $num\_rounds = 0$ means use the default.  The destination of a scheduled key is stored
+in ``skey''.
+
+Inside the ``symmetric\_key'' union there is a ``void *data'' which you can use to allocate data if you need a data structure that doesn't fit with the existing
+ones provided.  Just make sure in your ``done()'' function that you free the allocated memory.
+
+\subsection{Single block ECB}
+To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided.  The plaintext and ciphertext buffers are allowed to overlap so you 
+must make sure you do not overwrite the output before you are finished with the input.
+
+\subsection{Testing}
+The test() function is used to self--test the ``device''.  It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly.
+
+\subsection{Key Sizing}
+Occasionally a function will want to find a suitable key size to use since the input is oddly sized.  The keysize() function is for this case.  It accepts a 
+pointer to an integer which represents the desired size.  The function then has to match it to the exact or a lower key size that is valid for the cipher.  For
+example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer.  It must not round up and must return an error if the keysize
+ cannot be mapped to a valid key size for the cipher.
+
+\subsection{Acceleration}
+The next set of functions cover the accelerated functionality of the cipher descriptor.  Any combination of these functions may be set to \textbf{NULL} to indicate
+it is not supported.  In those cases the software fallbacks are used (using the single ECB block routines).
+
+\subsubsection{Accelerated ECB}
+These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks.  These functions are accessed
+through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers.  The ``blocks'' count is the number of complete blocks to process.
+
+\subsubsection{Accelerated CBC} 
+These two functions are meant for accelerated CBC encryption.  These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
+The ``blocks'' value is the number of complete blocks to process.  The ``IV'' is the CBC initial vector.  It is an input upon calling this function and must be
+updated by the function before returning.  
+
+\subsubsection{Accelerated CTR}
+This function is meant for accelerated CTR encryption.  It is accessible through the accel\_ctr\_encrypt pointer.
+The ``blocks'' value is the number of complete blocks to process.  The ``IV'' is the CTR counter vector.  It is an input upon calling this function and must be
+updated by the function before returning.  The ``mode'' value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or 
+little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.
+
+This function (and the way it's called) differs from the other two since ctr\_encrypt() allows any size input plaintext.  The accelerator will only be
+called if the following conditions are met.
+
+\begin{enumerate}
+   \item The accelerator is present
+   \item The CTR pad is empty
+   \item The remaining length of the input to process is greater than or equal to the block size.
+\end{enumerate}
+
+The ``CTR pad'' is empty when a multiple (including zero) blocks of text have been processed.  That is, if you pass in seven bytes to AES--CTR mode you would have to 
+pass in a minimum of nine extra bytes before the accelerator could be called.  The CTR accelerator must increment the counter (and store it back into the 
+buffer provided) before encrypting it to create the pad.  
+
+The accelerator will only be used to encrypt whole blocks.  Partial blocks are always handled in software.
+
+\subsubsection{Accelerated CCM}
+This function is meant for accelerated CCM encryption or decryption.  It processes the entire packet in one call.  Note that the setup() function will not
+be called prior to this.  This function must handle scheduling the key provided on its own.
+
+\subsubsection{Accelerated GCM}
+This function is meant for accelerated GCM encryption or decryption.  It processes the entire packet in one call.  Note that the setup() function will not
+be called prior to this.  This function must handle scheduling the key provided on its own.
+
+\section{One--Way Hashes}
+The hash functions are accessed through the ltc\_hash\_descriptor structure.
+
+\begin{small}
+\begin{verbatim}
+struct ltc_hash_descriptor {
+    /** name of hash */
+    char *name;
+    /** internal ID */
+    unsigned char ID;
+    /** Size of digest in octets */
+    unsigned long hashsize;
+    /** Input block size in octets */
+    unsigned long blocksize;
+    /** ASN.1 OID */
+    unsigned long OID[16];
+    /** Length of DER encoding */
+    unsigned long OIDlen;
+    /** Init a hash state
+      @param hash   The hash to initialize
+      @return CRYPT_OK if successful
+    */
+    int (*init)(hash_state *hash);
+    /** Process a block of data 
+      @param hash   The hash state
+      @param in     The data to hash
+      @param inlen  The length of the data (octets)
+      @return CRYPT_OK if successful
+    */
+    int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
+    /** Produce the digest and store it
+      @param hash   The hash state
+      @param out    [out] The destination of the digest
+      @return CRYPT_OK if successful
+    */
+    int (*done)(hash_state *hash, unsigned char *out);
+    /** Self-test
+      @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
+    */
+    int (*test)(void);
+};
+\end{verbatim}
+\end{small}
+
+\subsection{Name}
+This is the name the hash is known by and what find\_hash() will look for.
+
+\subsection{Internal ID}
+This is the internal ID byte used to distinguish the hash from other hashes.
+
+\subsection{Digest Size}
+The ``hashsize'' variable indicates the length of the output in octets.
+
+\subsection{Block Size}
+The `blocksize'' variable indicates the length of input (in octets) that the hash processes in a given
+invokation.
+
+\subsection{OID Identifier}
+This is the universal ASN.1 Object Identifier for the hash.
+
+\subsection{Initialization}
+The init function initializes the hash and prepares it to process message bytes.
+
+\subsection{Process}
+This processes message bytes.  The algorithm must accept any length of input that the hash would allow.  The input is not
+guaranteed to be a multiple of the block size in length.
+
+\subsection{Done}
+The done function terminates the hash and returns the message digest.
+
+\subsection{Acceleration}
+A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.  
+
+\section{Pseudo--Random Number Generators}
+The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
+
+\begin{small}
+\begin{verbatim}
+struct ltc_prng_descriptor {
+    /** Name of the PRNG */
+    char *name;
+    /** size in bytes of exported state */
+    int  export_size;
+    /** Start a PRNG state
+        @param prng   [out] The state to initialize
+        @return CRYPT_OK if successful
+    */
+    int (*start)(prng_state *prng);
+    /** Add entropy to the PRNG
+        @param in         The entropy
+        @param inlen      Length of the entropy (octets)\
+        @param prng       The PRNG state
+        @return CRYPT_OK if successful
+    */
+    int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
+    /** Ready a PRNG state to read from
+        @param prng       The PRNG state to ready
+        @return CRYPT_OK if successful
+    */
+    int (*ready)(prng_state *prng);
+    /** Read from the PRNG
+        @param out     [out] Where to store the data
+        @param outlen  Length of data desired (octets)
+        @param prng    The PRNG state to read from
+        @return Number of octets read
+    */
+    unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
+    /** Terminate a PRNG state
+        @param prng   The PRNG state to terminate
+        @return CRYPT_OK if successful
+    */
+    int (*done)(prng_state *prng);
+    /** Export a PRNG state  
+        @param out     [out] The destination for the state
+        @param outlen  [in/out] The max size and resulting size of the PRNG state
+        @param prng    The PRNG to export
+        @return CRYPT_OK if successful
+    */
+    int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
+    /** Import a PRNG state
+        @param in      The data to import
+        @param inlen   The length of the data to import (octets)
+        @param prng    The PRNG to initialize/import
+        @return CRYPT_OK if successful
+    */
+    int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
+    /** Self-test the PRNG
+        @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
+    */
+    int (*test)(void);
+};
+\end{verbatim}
+\end{small}
+
+\subsection{Name}
+The name by which find\_prng() will find the PRNG.
+
+\subsection{Export Size}
+When an PRNG state is to be exported for future use you specify the space required in this variable.
+
+\subsection{Start}
+Initialize the PRNG and make it ready to accept entropy.
+
+\subsection{Entropy Addition}
+Add entropy to the PRNG state.  The exact behaviour of this function depends on the particulars of the PRNG.
+
+\subsection{Ready}
+This function makes the PRNG ready to read from by processing the entropy added.  The behaviour of this function depends
+on the specific PRNG used.
+
+\subsection{Read}
+Read from the PRNG and return the number of bytes read.  This function does not have to fill the buffer but it is best 
+if it does as many protocols do not retry reads and will fail on the first try.
+
+\subsection{Done}
+Terminate a PRNG state.  The behaviour of this function depends on the particular PRNG used.
+
+\subsection{Exporting and Importing}
+An exported PRNG state is data that the PRNG can later import to resume activity.  They're not meant to resume ``the same session''
+but should at least maintain the same level of state entropy.
+
+\input{crypt.ind}
+
 \end{document}
+
+% $Source: /cvs/libtom/libtomcrypt/crypt.tex,v $   
+% $Revision: 1.39 $   
+% $Date: 2005/06/27 13:08:28 $