~ubuntu-branches/ubuntu/utopic/dropbear/utopic-proposed

« back to all changes in this revision

Viewing changes to libtomcrypt/crypt.tex

  • Committer: Bazaar Package Importer
  • Author(s): Matt Johnston
  • Date: 2005-12-08 19:20:21 UTC
  • mfrom: (1.2.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20051208192021-nyp9rwnt77nsg6ty
Tags: 0.47-1
* New upstream release.
* SECURITY: Fix incorrect buffer sizing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
47
47
\def\gap{\vspace{0.5ex}}
48
48
\makeindex
49
49
\begin{document}
50
 
\title{LibTomCrypt \\ Version 0.99}
 
50
\title{LibTomCrypt \\ Version 1.05}
51
51
\author{Tom St Denis \\
52
52
\\
53
 
tomstdenis@iahu.ca \\
 
53
tomstdenis@gmail.com \\
54
54
http://libtomcrypt.org
55
55
}
56
56
\maketitle
57
57
This text and source code library are both hereby placed in the public domain.  This book has been 
58
58
formatted for A4 paper using the \LaTeX{} {\em book} macro package.
59
59
 
60
 
\vspace{10cm}
 
60
\vspace{15cm}
61
61
 
62
62
\begin{flushright}Open Source.  Open Academia.  Open Minds.
63
63
 
79
79
\tableofcontents
80
80
\chapter{Introduction}
81
81
\section{What is the LibTomCrypt?}
82
 
LibTomCrypt is a portable ANSI C cryptographic library that supports symmetric ciphers, one-way hashes, 
83
 
pseudo-random number generators, public key cryptography (via RSA,DH or ECC/DH) and a plethora of support 
84
 
routines.  It is designed to compile out of the box with the GNU C Compiler (GCC) version 2.95.3 (and higher) 
85
 
and with MSVC version 6 in win32.
86
 
 
87
 
The library has been successfully tested on quite a few other platforms ranging from the ARM7TDMI in a 
88
 
Gameboy Advanced to various PowerPC processors and even the MIPS processor in the PlayStation 2.  Suffice it
89
 
to say the code is portable.
90
 
 
91
 
The library is designed so new ciphers/hashes/PRNGs can be added at runtime and the existing API (and helper API functions) will 
92
 
be able to use the new designs automatically.  There exist self-check functions for each cipher and hash to ensure that
93
 
they compile and execute to the published design specifications.  The library also performs extensive parameter error checking
94
 
and will give verbose error messages when possible.
95
 
 
96
 
Essentially the library saves the time of having to implement the ciphers, hashes, prngs yourself.  Typically implementing
97
 
useful cryptography is an error prone business which means anything that can save considerable time and effort is a good
98
 
thing.
 
82
LibTomCrypt is a portable ISO C cryptographic library that is meant to be a toolset for cryptographers who are 
 
83
designing a cryptosystem.  It supports symmetric ciphers, one-way hashes, pseudo-random number generators, 
 
84
public key cryptography (via PKCS \#1 RSA, DH or ECCDH) and a plethora of support 
 
85
routines.  
 
86
 
 
87
The library was designed such that new ciphers/hashes/PRNGs can be added at runtime and the existing API 
 
88
(and helper API functions) are able to use the new designs automatically.  There exists self-check functions for each 
 
89
block cipher and hash function to ensure that they compile and execute to the published design specifications.  The library 
 
90
also performs extensive parameter error checking to prevent any number of runtime exploits or errors.
99
91
 
100
92
\subsection{What the library IS for?}
101
93
 
102
 
The library typically serves as a basis for other protocols and message formats.  For example, it should be possible to 
103
 
take the RSA routines out of this library, apply the appropriate message padding and get PKCS compliant RSA routines.  
104
 
Similarly SSL protocols could be formed on top  of the low-level symmetric cipher functions.  The goal of this package is 
105
 
to provide these low level core functions in a robust and easy to use fashion.
106
 
 
107
 
The library also serves well as a toolkit for applications where they don't need to be OpenPGP, PKCS, etc. compliant.
108
 
Included are fully operational public key routines for encryption, decryption, signature generation and verification.  
109
 
These routines are fully portable but are not conformant to any known set of standards\footnote{With the exception of 
110
 
the RSA code which is based on the PKCS \#1 standards.}.  They are all based on established
111
 
number theory and cryptography.  
112
 
 
113
 
\subsection{What the library IS NOT for?}
114
 
 
115
 
The library is not designed to be in anyway an implementation of the SSL or OpenPGP standards.  The library 
116
 
is not designed to be compliant with any known form of API or programming hierarchy.  It is not a port of any other 
117
 
library and it is not platform specific (like the MS CSP).  So if you're looking to drop in some buzzword 
118
 
compliant crypto library this is not for you.  The library has been written from scratch to provide basic functions as 
119
 
well as non-standard higher level functions.  
120
 
 
121
 
This is not to say that the library is a ``homebrew'' project.  All of the symmetric ciphers and one-way hash functions
122
 
conform to published test vectors.  The public key functions are derived from publicly available material and the majority
123
 
of the code has been reviewed by a growing community of developers.
124
 
 
125
 
\subsubsection{Why not?}
126
 
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
127
 
is quite simple too much money gets in the way.  When I tried to access the P1363 draft documents and was denied (it 
128
 
requires a password) I realized that they're just a business anyways.  See what happens is a company will sit down and
129
 
invent a ``standard''.  Then they try to sell it to as many people as they can.  All of a sudden this ``standard'' is 
130
 
everywhere.  Then the standard is updated every so often to keep people dependent.  Then you become RSA.  If people are 
131
 
supposed to support these standards they had better make them more accessible.
 
94
The library serves as a toolkit for developers who have to solve cryptographic problems.  Out of the box LibTomCrypt
 
95
does not process SSL or OpenPGP messages, it doesn't read x.591 certificates or write PEM encoded data.  It does, however,
 
96
provide all of the tools required to build such functionality.  LibTomCrypt was designed to be a flexible library that 
 
97
was not tied to any particular cryptographic problem.  
132
98
 
133
99
\section{Why did I write it?}
134
100
You may be wondering, ``Tom, why did you write a crypto library.  I already have one.''.  Well the reason falls into
143
109
 
144
110
With this library all core functions (ciphers, hashes, prngs) have the {\bf exact} same prototype definition.  They all load
145
111
and store data in a format independent of the platform.  This means if you encrypt with Blowfish on a PPC it should decrypt
146
 
on an x86 with zero problems.  The consistent API also means that if you learn how to use blowfish with my library you 
 
112
on an x86 with zero problems.  The consistent API also means that if you learn how to use Blowfish with my library you 
147
113
know how to use Safer+ or RC6 or Serpent or ... as well.  With all of the core functions there are central descriptor tables 
148
114
that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime.  That means your 
149
115
application can support all ciphers/hashes/prngs without changing the source code.
150
116
 
 
117
Not only did I strive to make a consistent and simple API to work with but I also strived to make the library
 
118
configurable in terms of its build options.  Out of the box the library will build with any modern version of GCC
 
119
without having to use configure scripts.  This means that the library will work with platforms where development
 
120
tools may be limited (e.g. no autoconf).
 
121
 
 
122
On top of making the build simple and the API approachable I've also strived for a reasonably high level of
 
123
robustness and efficiency.  LibTomCrypt traps and returns a series of errors ranging from invalid
 
124
arguments to buffer overflows/overruns.  It is mostly thread safe and has been clocked on various platforms
 
125
with ``cycles per byte'' timings that are comparable (and often favourable) to other libraries such as OpenSSL and
 
126
Crypto++.
 
127
 
151
128
\subsection{Modular}
152
 
The LibTomCrypt package has also been written to be very modular.  The block ciphers, one-way hashes and
153
 
pseudo-random number generators (PRNG) are all used within the API through ``descriptor'' tables which 
 
129
The LibTomCrypt package has also been written to be very modular.  The block ciphers, one--way hashes and
 
130
pseudo--random number generators (PRNG) are all used within the API through ``descriptor'' tables which 
154
131
are essentially structures with pointers to functions.  While you can still call particular functions
155
132
directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
156
133
usage of the library.
157
134
 
158
135
For example, consider a hardware platform with a specialized RNG device.  Obviously one would like to tap
159
 
that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has todo
 
136
that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has to do
160
137
is write a descriptor and the few support routines required for the device.  After that the rest of the 
161
 
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
162
 
invented.  It can be added to the library and used within applications with zero modifications to the
163
 
end applications provided they are written properly.
 
138
API can make use of it without change.  Similiarly imagine a few years down the road when AES2 
 
139
(\textit{or whatever they call it}) has been invented.  It can be added to the library and used within applications 
 
140
with zero modifications to the end applications provided they are written properly.
164
141
 
165
142
This flexibility within the library means it can be used with any combination of primitive algorithms and 
166
143
unlike libraries like OpenSSL is not tied to direct routines.  For instance, in OpenSSL there are CBC block
170
147
the key setup, ECB decrypt and encrypt and test vector routines.  After that all five chaining mode routines
171
148
can make use of the cipher right away.
172
149
 
173
 
 
174
150
\section{License}
175
151
 
176
152
All of the source code except for the following files have been written by the author or donated to the project
178
154
 
179
155
\begin{enumerate}
180
156
   \item rc2.c
181
 
   \item safer.c
182
157
\end{enumerate}
183
158
 
184
 
`mpi.c'' was originally written by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with my LibTomMath
185
 
library.
 
159
`mpi.c'' was originally written by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with 
 
160
my LibTomMath library which is public domain.
186
161
 
187
 
``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.  ``safer.c''
188
 
was written by Richard De Moliner (demoliner@isi.ee.ethz.ch) and seems to be free for use.
 
162
``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.  
189
163
 
190
164
The project is hereby released as public domain.
191
165
 
193
167
 
194
168
The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice.  To the best
195
169
of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.  
196
 
They can be removed from a build by simply commenting out the two appropriate lines in ``mycrypt\_custom.h''.  The rest
 
170
They can be removed from a build by simply commenting out the two appropriate lines in ``tomcrypt\_custom.h''.  The rest
197
171
of the ciphers and hashes are patent free or under patents that have since expired.
198
172
 
199
173
The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations.  This means you can use 
221
195
There have been quite a few other people as well.  Please check the change log to see who else has contributed from
222
196
time to time.
223
197
 
224
 
 
225
198
\chapter{The Application Programming Interface (API)}
226
199
\section{Introduction}
227
200
\index{CRYPT\_ERROR} \index{CRYPT\_OK}
255
228
related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads.  Normally
256
229
that is not an issue.
257
230
 
258
 
To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``mycrypt.h'' like so:
 
231
To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``tomcrypt.h'' like so:
259
232
\begin{verbatim}
260
 
#include <mycrypt.h>
 
233
#include <tomcrypt.h>
261
234
int main(void) {
262
235
    return 0;
263
236
}
264
237
\end{verbatim}
265
238
 
266
 
The header file ``mycrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and ``mpi.h''
267
 
(the bignum library routines).
 
239
The header file ``tomcrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'', ``ctype.h'' and 
 
240
``ltc\_tommath.h'' (the bignum library routines).
268
241
 
269
242
\section{Macros}
270
243
 
271
244
There are a few helper macros to make the coding process a bit easier.  The first set are related to loading and storing
272
245
32/64-bit words in little/big endian format.  The macros are:
273
246
 
274
 
\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L}
275
 
\index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
 
247
\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
276
248
\begin{small}
277
249
\begin{center}
278
250
\begin{tabular}{|c|c|c|}
284
256
     \hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
285
257
     \hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
286
258
     \hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
287
 
     \hline BSWAP(x) & {\bf unsigned long} x & Swaps the byte order of x. \\
 
259
     \hline BSWAP(x) & {\bf unsigned long} x & Swaps byte order (32--bits only) \\
288
260
     \hline
289
261
\end{tabular}
290
262
\end{center}
291
263
\end{small}
292
264
 
293
 
There are 32-bit cyclic rotations as well:
294
 
\index{ROL} \index{ROR}
 
265
There are 32 and 64-bit cyclic rotations as well:
 
266
\index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c} 
295
267
\begin{center}
296
268
\begin{tabular}{|c|c|c|}
297
 
     \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y$ \\
298
 
     \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y$ \\
 
269
     \hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 31$ \\
 
270
     \hline ROLc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 31$ \\
 
271
     \hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 31$ \\
 
272
     \hline RORc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 31$ \\
 
273
     \hline && \\
 
274
     \hline ROL64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 63$ \\
 
275
     \hline ROL64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 63$ \\
 
276
     \hline ROR64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 63$ \\
 
277
     \hline ROR64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 63$ \\
299
278
     \hline
300
279
\end{tabular}
301
280
\end{center}
306
285
the output will be stored.  For example:
307
286
\begin{small}
308
287
\begin{verbatim}
309
 
#include <mycrypt.h>
 
288
#include <tomcrypt.h>
310
289
int main(void) {
311
290
    rsa_key key;
312
291
    unsigned char buffer[1024];
313
292
    unsigned long x;
314
293
    int err;
315
294
 
316
 
    /* ... Make up the RSA key somehow */
 
295
    /* ... Make up the RSA key somehow ... */
317
296
 
318
297
    /* lets export the key, set x to the size of the output buffer */
319
298
    x = sizeof(buffer);
331
310
}
332
311
\end{verbatim}
333
312
\end{small}
334
 
In the above example if the size of the RSA public key was more than 1024 bytes this function would not store anything in
335
 
either ``buffer'' or ``x'' and simply return an error code.  If the function suceeds it stores the length of the output
336
 
back into ``x'' so that the calling application will know how many bytes used.
 
313
In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
 
314
indicating a buffer overflow would have occurred.  If the function succeeds it stores the length of the output
 
315
back into ``x'' so that the calling application will know how many bytes were used.
337
316
 
338
317
\section{Functions that need a PRNG}
339
 
Certain functions such as ``rsa\_make\_key()'' require a PRNG.  These functions do not setup the PRNG themselves so it is 
340
 
the responsibility of the calling function to initialize the PRNG before calling them.
 
318
\index{Pseudo Random Number Generator} \index{PRNG}
 
319
Certain functions such as ``rsa\_make\_key()'' require a Pseudo Random Number Generator (PRNG).  These functions do not setup 
 
320
the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
 
321
 
 
322
Certain PRNG algorithms do not require a ``prng\_state'' argument (sprng for example).  The ``prng\_state'' argument
 
323
may be passed as \textbf{NULL} in such situations.
341
324
 
342
325
\section{Functions that use Arrays of Octets}
343
326
Most functions require inputs that are arrays of the data type ``unsigned char''.  Whether it is a symmetric key, IV
352
335
\chapter{Symmetric Block Ciphers}
353
336
\section{Core Functions}
354
337
 
355
 
Libtomcrypt provides several block ciphers all in a plain vanilla ECB block mode.  Its important to first note that you 
 
338
LibTomCrypt provides several block ciphers with an ECB block mode interface.  It's important to first note that you 
356
339
should never use the ECB modes directly to encrypt data.  Instead you should use the ECB functions to make a chaining mode
357
340
or use one of the provided chaining modes.  All of the ciphers are written as ECB interfaces since it allows the rest of
358
341
the API to grow in a modular fashion.
359
342
 
 
343
\subsection{Key Scheduling}
360
344
All ciphers store their scheduled keys in a single data type called ``symmetric\_key''.  This allows all ciphers to 
361
 
have the same prototype and store their keys as  naturally as possible.  All ciphers provide five visible functions which
362
 
are (given that XXX is the name of the cipher):
 
345
have the same prototype and store their keys as naturally as possible.  This also removes the need for dynamic memory
 
346
allocation and allows you to allocate a fixed sized buffer for storing scheduled keys.  All ciphers provide five visible 
 
347
functions which are (given that XXX is the name of the cipher):
363
348
\index{Cipher Setup}
364
349
\begin{verbatim}
365
350
int XXX_setup(const unsigned char *key, int keylen, int rounds,
369
354
The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
370
355
The number of rounds can be set to zero to use the default, which is generally a good idea.
371
356
 
372
 
If the function returns successfully the variable ``skey'' will have a scheduled key stored in it.  Its important to note
373
 
that you should only used this scheduled key with the intended cipher.  For example, if you call 
374
 
``blowfish\_setup()'' do not pass the scheduled key onto ``rc5\_ecb\_encrypt()''.  All setup functions do not allocate 
375
 
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).
 
357
If the function returns successfully the variable ``skey'' will have a scheduled key stored in it.  It's important to note
 
358
that you should only used this scheduled key with the intended cipher.  For example, if you call ``blowfish\_setup()'' do not 
 
359
pass the scheduled key onto ``rc5\_ecb\_encrypt()''.  All setup functions do not allocate memory off the heap so when you are 
 
360
done with a key you can simply discard it (e.g. they can be on the stack).
376
361
 
377
 
To encrypt or decrypt a block in ECB mode there are these two functions:
 
362
\subsection{ECB Encryption and Decryption}
 
363
To encrypt or decrypt a block in ECB mode there are these two function classes
378
364
\index{Cipher Encrypt} \index{Cipher Decrypt}
379
365
\begin{verbatim}
380
366
void XXX_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
385
371
\end{verbatim}
386
372
These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
387
373
which cipher you are using.} and store the result where you want it.  It is possible that the input and output buffer are 
388
 
the same buffer.  For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and ``ct'' is the output.
389
 
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}
 
374
the same buffer.  For the encrypt function ``pt''\footnote{pt stands for plaintext.} is the input and 
 
375
``ct''\footnote{ct stands for ciphertext.} is the output.  For the decryption function it's the opposite.  To test a particular 
 
376
cipher against test vectors\footnote{As published in their design papers.} call the self-test function
 
377
 
 
378
\subsection{Self--Testing}
 
379
\index{Cipher Testing}
390
380
\begin{verbatim}
391
381
int XXX_test(void);
392
382
\end{verbatim}
393
383
This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is 
394
 
based upon.  Finally for each cipher there is a function which will help find a desired key size:
 
384
based upon.  
 
385
 
 
386
\subsection{Key Sizing}
 
387
For each cipher there is a function which will help find a desired key size:
395
388
\begin{verbatim}
396
389
int XXX_keysize(int *keysize);
397
390
\end{verbatim}
399
392
return {\bf CRYPT\_OK} if the key size specified is acceptable.  For example:
400
393
\begin{small}
401
394
\begin{verbatim}
402
 
#include <mycrypt.h>
 
395
#include <tomcrypt.h>
403
396
int main(void)
404
397
{
405
398
   int keysize, err;
415
408
}
416
409
\end{verbatim}
417
410
\end{small}
418
 
This should indicate a keysize of sixteen bytes is suggested.  An example snippet that encodes a block with 
419
 
Blowfish in ECB mode is below.
 
411
This should indicate a keysize of sixteen bytes is suggested.  
 
412
 
 
413
\subsection{Cipher Termination}
 
414
When you are finished with a cipher you can de--initialize it with the done function.
 
415
\begin{verbatim}
 
416
void XXX_done(symmetric_key *skey);
 
417
\end{verbatim}
 
418
For the software based ciphers within LibTomCrypt this function will not do anything.  However, user supplied
 
419
cipher descriptors may require calls to it for resource management.  To be compliant all functions which call a cipher
 
420
setup function must also call the respective cipher done function when finished.
 
421
 
 
422
\subsection{Simple Encryption Demonstration}
 
423
An example snippet that encodes a block with Blowfish in ECB mode is below.
420
424
 
421
425
\begin{small}
422
426
\begin{verbatim}
423
 
#include <mycrypt.h>
 
427
#include <tomcrypt.h>
424
428
int main(void)
425
429
426
430
   unsigned char pt[8], ct[8], key[8];
444
448
   blowfish_ecb_encrypt(pt,             /* encrypt this 8-byte array */
445
449
                        ct,             /* store encrypted data here */ 
446
450
                        &skey);         /* our previously scheduled key */
 
451
                        
 
452
   /* now ct holds the encrypted version of pt */                        
447
453
 
448
454
   /* decrypt the block */
449
455
   blowfish_ecb_decrypt(ct,             /* decrypt this 8-byte array */
450
456
                        pt,             /* store decrypted data here */
451
457
                        &skey);         /* our previously scheduled key */
452
458
 
 
459
   /* now we have decrypted ct to the original plaintext in pt */                        
 
460
 
 
461
   /* Terminate the cipher context */
 
462
   blowfish_done(&skey);
 
463
 
453
464
   return 0;
454
465
}
455
466
\end{verbatim}
459
470
\index{Symmetric Keys}
460
471
As a general rule of thumb do not use symmetric keys under 80 bits if you can.  Only a few of the ciphers support smaller
461
472
keys (mainly for test vectors anyways).  Ideally your application should be making at least 256 bit keys.  This is not
462
 
because you're supposed to be paranoid.  Its because if your PRNG has a bias of any sort the more bits the better.  For
 
473
because you're supposed to be paranoid.  It's because if your PRNG has a bias of any sort the more bits the better.  For
463
474
example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
464
475
total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$.  So if $\gamma$
465
476
were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
467
478
 
468
479
The number of rounds of most ciphers is not an option you can change.  Only RC5 allows you to change the number of
469
480
rounds.  By passing zero as the number of rounds all ciphers will use their default number of rounds.  Generally the
470
 
ciphers are configured such that the default number of rounds provide adequate security for the given block size.
 
481
ciphers are configured such that the default number of rounds provide adequate security for the given block and key 
 
482
size.
471
483
 
472
484
\section{The Cipher Descriptors}
473
485
\index{Cipher Descriptor}
474
486
To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_descriptor''.  An element
475
487
of this array has the following format:
476
488
 
 
489
\begin{small}
477
490
\begin{verbatim}
478
491
struct _cipher_descriptor {
479
492
   char *name;
480
 
   unsigned long min_key_length, max_key_length, 
481
 
                 block_length, default_rounds;
482
 
   int  (*setup)      (const unsigned char *key, int keylength, 
483
 
                       int num_rounds, symmetric_key *skey);
484
 
   void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, 
485
 
                       symmetric_key *key);
486
 
   void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt,
487
 
                       symmetric_key *key);
488
 
   int  (*test)       (void);
489
 
   int  (*keysize)    (int *desired_keysize);
 
493
   unsigned char ID;
 
494
   int  min_key_length, 
 
495
        max_key_length, 
 
496
        block_length, 
 
497
        default_rounds;
 
498
   int  (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
 
499
   void (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
 
500
   void (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
 
501
   int (*test)(void);
 
502
   void (*done)(symmetric_key *skey);      
 
503
   int  (*keysize)(int *keysize);
 
504
 
 
505
   void (*accel_ecb_encrypt)(const unsigned char *pt, 
 
506
                                   unsigned char *ct, 
 
507
                                   unsigned long blocks, symmetric_key *skey);
 
508
   void (*accel_ecb_decrypt)(const unsigned char *ct, 
 
509
                                   unsigned char *pt, 
 
510
                                   unsigned long blocks, symmetric_key *skey);
 
511
   void (*accel_cbc_encrypt)(const unsigned char *pt, 
 
512
                                   unsigned char *ct, 
 
513
                                   unsigned long blocks, unsigned char *IV, 
 
514
                                   symmetric_key *skey);
 
515
   void (*accel_cbc_decrypt)(const unsigned char *ct, 
 
516
                                   unsigned char *pt, 
 
517
                                   unsigned long blocks, unsigned char *IV, 
 
518
                                   symmetric_key *skey);
 
519
   void (*accel_ctr_encrypt)(const unsigned char *pt, 
 
520
                                   unsigned char *ct, 
 
521
                                   unsigned long blocks, unsigned char *IV, 
 
522
                                   int mode, symmetric_key *skey);
 
523
   void (*accel_ccm_memory)(
 
524
       const unsigned char *key,    unsigned long keylen,
 
525
       const unsigned char *nonce,  unsigned long noncelen,
 
526
       const unsigned char *header, unsigned long headerlen,
 
527
             unsigned char *pt,     unsigned long ptlen,
 
528
             unsigned char *ct,
 
529
             unsigned char *tag,    unsigned long *taglen,
 
530
                       int  direction);
 
531
 
490
532
};
491
533
\end{verbatim}
 
534
\end{small}
492
535
 
493
 
Where ``name'' is the lower case ASCII version of the name.  The fields ``min\_key\_length'', ``max\_key\_length'' and
494
 
``block\_length'' are all the number of bytes not bits.  As a good rule of thumb it is assumed that the cipher supports
 
536
Where ``name'' is the lower case ASCII version of the name.  The fields ``min\_key\_length'' and ``max\_key\_length'' 
 
537
are the minimum and maximum key sizes in bytes.  The ``block\_length'' member is the block size of the cipher
 
538
in bytes.  As a good rule of thumb it is assumed that the cipher supports
495
539
the min and max key lengths but not always everything in between.  The ``default\_rounds'' field is the default number
496
540
of rounds that will be used.
497
541
 
511
555
     \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
512
556
     \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
513
557
     \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
514
 
     \hline Safer K64   & safer\_k64\_desc & 8 & 8 & 6 $\ldots$ 13 \\
515
 
     \hline Safer SK64  & safer\_sk64\_desc & 8 & 8 & 6 $\ldots$ 13 \\
516
 
     \hline Safer K128  & safer\_k128\_desc & 8 & 16 & 6 $\ldots$ 13 \\
517
 
     \hline Safer SK128 & safer\_sk128\_desc & 8 & 16 & 6 $\ldots$ 13 \\
518
558
     \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
519
559
                & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
520
560
     \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
523
563
     \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
524
564
     \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
525
565
     \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
 
566
     \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
 
567
     \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
526
568
     \hline
527
569
\end{tabular}
528
570
\end{center}
545
587
Rijndael as it makes the most sense for this cipher.
546
588
 
547
589
\item
548
 
For the 64-bit SAFER famliy of ciphers (e.g K64, SK64, K128, SK128) the ecb\_encrypt() and ecb\_decrypt()
549
 
functions are the same.  So if you want to use those functions directly just call safer\_ecb\_encrypt()
550
 
or safer\_ecb\_decrypt() respectively.
551
 
 
552
 
\item
553
590
Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
554
591
fact used for the purposes of encryption.  My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
555
592
byte string from the real 7/21 byte key.
556
593
 
557
594
\item
558
595
Note that ``Twofish'' has additional configuration options that take place at build time.  These options are found in
559
 
the file ``mycrypt\_cfg.h''.  The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
 
596
the file ``tomcrypt\_cfg.h''.  The first option is ``TWOFISH\_SMALL'' which when defined will force the Twofish code
560
597
to not pre-compute the Twofish ``$g(X)$'' function as a set of four $8 \times 32$ s-boxes.  This means that a scheduled
561
598
key will require less ram but the resulting cipher will be slower.  The second option is ``TWOFISH\_TABLES'' which when
562
599
defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
590
627
the location in the array where the cipher was found.  For example, to indirectly setup Blowfish you can also use:
591
628
\begin{small}
592
629
\begin{verbatim}
593
 
#include <mycrypt.h>
 
630
#include <tomcrypt.h>
594
631
int main(void)
595
632
{
596
633
   unsigned char key[8];
631
668
Which returns {\bf CRYPT\_OK} if it removes it otherwise it returns {\bf CRYPT\_ERROR}.  Consider:
632
669
\begin{small}
633
670
\begin{verbatim}
634
 
#include <mycrypt.h>
 
671
#include <tomcrypt.h>
635
672
int main(void)
636
673
{
637
674
   int err;
729
766
The ECB and CBC modes process blocks of the same size as the cipher at a time.  Therefore they are less flexible than the
730
767
other modes.
731
768
 
732
 
\subsection{Implementation}
 
769
\subsection{Initialization}
733
770
\index{CBC Mode} \index{CTR Mode}
734
771
\index{OFB Mode} \index{CFB Mode}
735
772
The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages.  Assuming the mode 
736
773
you want is XXX there is a structure called ``symmetric\_XXX'' that will contain the information required to
737
 
use that mode.  They have identical setup routines (except ECB mode for obvious reasons):
 
774
use that mode.  They have identical setup routines (except CTR and ECB mode):
738
775
\index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
739
776
\begin{verbatim}
740
777
int XXX_start(int cipher, const unsigned char *IV, 
741
778
              const unsigned char *key, int keylen, 
742
779
              int num_rounds, symmetric_XXX *XXX);
743
780
 
 
781
int ctr_start(               int   cipher,
 
782
              const unsigned char *IV,
 
783
              const unsigned char *key,       int keylen,
 
784
                             int  num_rounds, int ctr_mode,
 
785
                   symmetric_CTR *ctr);
 
786
 
744
787
int ecb_start(int cipher, const unsigned char *key, int keylen, 
745
788
              int num_rounds, symmetric_ECB *ecb);
746
789
\end{verbatim}
752
795
parameters ``key'', ``keylen'' and ``num\_rounds'' are the same as in the XXX\_setup() function call.  The final parameter 
753
796
is a pointer to the structure you want to hold the information for the mode of operation.
754
797
 
755
 
Both routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.  To 
756
 
actually encrypt or decrypt the following routines are provided:
 
798
 
 
799
In the case of CTR mode there is an additional parameter ``ctr\_mode'' which specifies the mode that the counter is to be used in.
 
800
If \textbf{CTR\_COUNTER\_LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value.  Otherwise, if 
 
801
\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value.
 
802
 
 
803
The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise they return an error code.  
 
804
 
 
805
\subsection{Encryption and Decryption}
 
806
To actually encrypt or decrypt the following routines are provided:
757
807
\index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()} 
758
808
\index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
759
809
\begin{verbatim}
760
810
int XXX_encrypt(const unsigned char *pt, unsigned char *ct, 
761
 
                symmetric_XXX *XXX);
762
 
int XXX_decrypt(const unsigned char *ct, unsigned char *pt,
763
 
                symmetric_XXX *XXX);
 
811
                unsigned long len, symmetric_YYY *YYY);
 
812
int XXX_decrypt(const unsigned char *ct, unsigned char *pt, 
 
813
                unsigned long len, symmetric_YYY *YYY);
 
814
\end{verbatim}
 
815
Where ``XXX'' is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.  
764
816
 
765
 
int YYY_encrypt(const unsigned char *pt, unsigned char *ct, 
766
 
                unsigned long len, symmetric_YYY *YYY);
767
 
int YYY_decrypt(const unsigned char *ct, unsigned char *pt, 
768
 
                unsigned long len, symmetric_YYY *YYY);
769
 
\end{verbatim}
770
 
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
771
 
size of the buffer (as number of chars) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
 
817
In all cases ``len'' is the size of the buffer (as number of octets) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
772
818
chunk sensitive.  That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
773
819
and end up with the same ciphertext.  However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts.  All
774
820
five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
775
821
 
 
822
In the ECB and CBC cases ``len'' must be a multiple of the ciphers block size.  In the CBC case you must manually pad the end of your message (either with
 
823
zeroes or with whatever your protocol requires).
 
824
 
776
825
To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
777
826
and use the decrypt routine on all of the blocks.
778
827
 
 
828
\subsection{IV Manipulation}
779
829
To change or read the IV of a previously initialized chaining mode use the following two functions.
780
830
 
781
831
\index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
785
835
int XXX_setiv(const unsigned char *IV, unsigned long len, symmetric_XXX *XXX);
786
836
\end{verbatim}
787
837
 
788
 
The XXX\_getiv function will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV 
 
838
The XXX\_getiv() functions will read the IV out of the chaining mode and store it into ``IV'' along with the length of the IV 
789
839
stored in ``len''.  The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified.  The length
790
840
of the IV passed in must be the size of the ciphers block size.
791
841
 
792
 
The XXX\_setiv functions are handy if you wish to change the IV without re--keying the cipher.  
 
842
The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.  
 
843
 
 
844
\subsection{Stream Termination}
 
845
To terminate an open stream call the done function.
 
846
 
 
847
\index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
 
848
\begin{verbatim}
 
849
int XXX_done(symmetric_XXX *XXX);
 
850
\end{verbatim}
 
851
 
 
852
This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
 
853
 
 
854
\subsection{Examples}
793
855
 
794
856
\newpage
795
857
\begin{small}
796
858
\begin{verbatim}
797
 
#include <mycrypt.h>
 
859
#include <tomcrypt.h>
798
860
int main(void)
799
861
{
800
862
   unsigned char key[16], IV[16], buffer[512];
816
878
                           key, /* the secret key */
817
879
                            16, /* length of secret key (16 bytes, 128 bits) */
818
880
                             0, /* 0 == default # of rounds */
 
881
     CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
819
882
                         &ctr)  /* where to store initialized CTR state */
820
883
      ) != CRYPT_OK) {
821
884
      printf("ctr_start error: %s\n", error_to_string(err));
852
915
      return -1;
853
916
   }
854
917
 
 
918
   /* terminate the stream */
 
919
   if ((err = ctr_done(&ctr)) != CRYPT_OK) {
 
920
      printf("ctr_done error: %s\n", error_to_string(err));
 
921
      return -1;
 
922
   }
 
923
 
855
924
   /* clear up and return */
856
925
   zeromem(key, sizeof(key));
857
926
   zeromem(&ctr, sizeof(ctr));
944
1013
This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
945
1014
 
946
1015
\begin{verbatim}
947
 
#include <mycrypt.h>
 
1016
#include <tomcrypt.h>
948
1017
int main(void)
949
1018
{
950
1019
   int           err;
1057
1126
both functions given a single ``ocb'' state.  For bi-directional communication you will have to initialize two ``ocb''
1058
1127
states (with different nonces).  Also ``pt'' and ``ct'' may point to the same location in memory.
1059
1128
 
 
1129
\subsubsection{State Termination}
 
1130
 
1060
1131
When you are finished encrypting the message you call the following function to compute the tag.
1061
1132
 
1062
1133
\index{ocb\_done\_encrypt()}
1090
1161
``res'' is set to zero.  If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
1091
1162
message).
1092
1163
 
 
1164
\subsubsection{Packet Functions}
1093
1165
To make life simpler the following two functions are provided for memory bound OCB.
1094
1166
 
1095
1167
\index{ocb\_encrypt\_authenticate\_memory()}
1119
1191
Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set 
1120
1192
appropriately.
1121
1193
 
 
1194
\subsection{CCM Mode}
 
1195
CCM is a NIST proposal for Encrypt+Authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.  Unlike EAX and OCB mode
 
1196
it is only meant for ``packet'' mode where the length of the input is known in advance.  Since it is a packet mode function CCM only has one 
 
1197
function that performs the protocol.
 
1198
 
 
1199
\index{ccm\_memory()}
 
1200
\begin{verbatim}
 
1201
int ccm_memory(int cipher,
 
1202
    const unsigned char *key,    unsigned long keylen,
 
1203
    const unsigned char *nonce,  unsigned long noncelen,
 
1204
    const unsigned char *header, unsigned long headerlen,
 
1205
          unsigned char *pt,     unsigned long ptlen,
 
1206
          unsigned char *ct,
 
1207
          unsigned char *tag,    unsigned long *taglen,
 
1208
                    int  direction);
 
1209
\end{verbatim}
 
1210
 
 
1211
This performs the ``CCM'' operation on the data.  The ``cipher'' variable indicates which cipher in the descriptor table to use.  It must have a 
 
1212
16--byte block size for CCM.  The key is ``key'' with a length of ``keylen'' octets.  The nonce or salt is ``nonce'' of
 
1213
length ``noncelen'' octets.  The header is meta--data you want to send with the message but not have encrypted, it is stored in ``header''
 
1214
of length ``headerlen'' octets.  The header can be zero octets long (if $headerlen = 0$ then you can pass ``header'' as \textbf{NULL}).  
 
1215
 
 
1216
The plaintext is stored in ``pt'' and the ciphertext in ``ct''.  The length of both are expected to be equal and is passed in as ``ptlen''.  It is
 
1217
allowable that $pt = ct$.  The ``direction'' variable indicates whether encryption (direction $=$ \textbf{CCM\_ENCRYPT}) or 
 
1218
decryption (direction $=$ \textbf{CCM\_DECRYPT}) is to be performed.
 
1219
 
 
1220
As implemented this copy of CCM cannot handle a header or plaintext longer than $2^{32} - 1$ octets long.  
 
1221
 
 
1222
You can test the implementation of CCM with the following function.
 
1223
 
 
1224
\index{ccm\_test()}
 
1225
\begin{verbatim}
 
1226
int ccm_test(void);
 
1227
\end{verbatim}
 
1228
 
 
1229
This will return \textbf{CRYPT\_OK} if the CCM routine passes known test vectors.
 
1230
 
 
1231
\subsection{GCM Mode}
 
1232
Galois counter mode is an IEEE proposal for authenticated encryption.  Like EAX and OCB it can be used in a streaming capacity however, unlike EAX it cannot
 
1233
accept ``additional authentication data'' (meta--data) after plaintext has been processed.  This mode also only works with block ciphers with a sixteen
 
1234
byte block.
 
1235
 
 
1236
A GCM stream is meant to be processed in three modes each one sequential serial.  First the initial vector (per session) data is processed.  This should be 
 
1237
unique to every session.  Next the the optional additional authentication data is processed and finally the plaintext.  
 
1238
 
 
1239
\subsubsection{Initialization}
 
1240
To initialize the GCM context with a secret key call the following function.
 
1241
 
 
1242
\index{gcm\_init()}
 
1243
\begin{verbatim}
 
1244
int gcm_init(gcm_state *gcm, int cipher,
 
1245
             const unsigned char *key, int keylen);
 
1246
\end{verbatim}
 
1247
This initializes the GCM state ``gcm'' for the given cipher indexed by ``cipher'' with a secret key ``key'' of length ``keylen'' octets.  The cipher chosen
 
1248
must have a 16--byte block size (e.g. AES).  
 
1249
 
 
1250
\subsubsection{Initial Vector}
 
1251
After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector.  It should be unique per packet encrypted.
 
1252
 
 
1253
\index{gcm\_add\_iv()}
 
1254
\begin{verbatim}
 
1255
int gcm_add_iv(gcm_state *gcm, 
 
1256
               const unsigned char *IV,     unsigned long IVlen);
 
1257
\end{verbatim}
 
1258
 
 
1259
This adds the initial vector octets from ``IV'' of length ``IVlen'' to the GCM state ``gcm''.  You can call this function as many times as required
 
1260
to process the entire IV.  
 
1261
 
 
1262
Note that the GCM protocols provides a ``shortcut'' for 12--byte IVs where no preprocessing is to be done.  If you want to minimize per packet latency it's ideal
 
1263
to only use 12--byte IVs.  You can just increment it like a counter for each packet and the CTR [privacy] will be ensured.
 
1264
 
 
1265
\subsubsection{Additional Authentication Data}
 
1266
After the entire IV has been processed the additional authentication data can be processed.  Unlike the IV a packet/session does not require additional
 
1267
authentication data (AAD) for security.  The AAD is meant to be used as side--channel data you want to be authenticated with the packet.  Note that once
 
1268
you begin adding AAD to the GCM state you cannot return to adding IV data until the state is reset.
 
1269
 
 
1270
\index{gcm\_add\_aad()}
 
1271
\begin{verbatim}
 
1272
int gcm_add_aad(gcm_state *gcm, 
 
1273
               const unsigned char *adata,     unsigned long adatalen);
 
1274
\end{verbatim}
 
1275
This adds the additional authentication data ``adata'' of length ``adatalen'' to the GCM state ``gcm''.
 
1276
 
 
1277
\subsubsection{Plaintext Processing}
 
1278
After the AAD has been processed the plaintext (or ciphertext depending on the direction) can be processed.  
 
1279
 
 
1280
\index{gcm\_process()}
 
1281
\begin{verbatim}
 
1282
int gcm_process(gcm_state *gcm,
 
1283
                     unsigned char *pt,     unsigned long ptlen,
 
1284
                     unsigned char *ct,
 
1285
                     int direction);
 
1286
\end{verbatim}
 
1287
This processes message data where ``pt'' is the plaintext and ``ct'' is the ciphertext.  The length of both are equal and stored in ``ptlen''.  Depending on the 
 
1288
mode ``pt'' is the input and ``ct'' is the output (or vice versa).  When ``direction'' equals \textbf{GCM\_ENCRYPT} the plaintext is read, encrypted and stored
 
1289
in the ciphertext buffer.  When ``direction'' equals \textbf{GCM\_DECRYPT} the opposite occurs.
 
1290
 
 
1291
\subsubsection{State Termination}
 
1292
To terminate a GCM state and retrieve the message authentication tag call the following function.
 
1293
 
 
1294
\index{gcm\_done()}
 
1295
\begin{verbatim}
 
1296
int gcm_done(gcm_state *gcm, 
 
1297
                     unsigned char *tag,    unsigned long *taglen);
 
1298
\end{verbatim}
 
1299
This terminates the GCM state ``gcm'' and stores the tag in ``tag'' of length ``taglen'' octets.
 
1300
 
 
1301
\subsubsection{State Reset}
 
1302
The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
 
1303
it is very costly to have to call it repeatedly.  To aid in this endeavour the reset function has been provided.
 
1304
 
 
1305
\index{gcm\_reset()}
 
1306
\begin{verbatim}
 
1307
int gcm_reset(gcm_state *gcm);
 
1308
\end{verbatim}
 
1309
 
 
1310
This will reset the GCM state ``gcm'' to the state that gcm\_init() left it.  The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
 
1311
 
 
1312
\subsubsection{One--Shot Packet}
 
1313
To process a single packet under any given key the following helper function can be used.
 
1314
 
 
1315
\index{gcm\_memory()}
 
1316
\begin{verbatim}
 
1317
int gcm_memory(      int           cipher,
 
1318
               const unsigned char *key,    unsigned long keylen,
 
1319
               const unsigned char *IV,     unsigned long IVlen,
 
1320
               const unsigned char *adata,  unsigned long adatalen,
 
1321
                     unsigned char *pt,     unsigned long ptlen,
 
1322
                     unsigned char *ct, 
 
1323
                     unsigned char *tag,    unsigned long *taglen,
 
1324
                               int direction);
 
1325
\end{verbatim}
 
1326
 
 
1327
This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
 
1328
message tag.  The definition of the variables is the same as it is for all the manual functions.
 
1329
 
 
1330
If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
 
1331
 
 
1332
\subsubsection{Example Usage}
 
1333
The following is an example usage of how to use GCM over multiple packets with a shared secret key.
 
1334
 
 
1335
\begin{small}
 
1336
\begin{verbatim}
 
1337
#include <tomcrypt.h>
 
1338
 
 
1339
int send_packet(const unsigned char *pt,  unsigned long ptlen,
 
1340
                const unsigned char *iv,  unsigned long ivlen,
 
1341
                const unsigned char *aad, unsigned long aadlen,
 
1342
                      gcm_state     *gcm)
 
1343
{
 
1344
   int           err;
 
1345
   unsigned long taglen;
 
1346
   unsigned char tag[16];
 
1347
 
 
1348
   /* reset the state */
 
1349
   if ((err = gcm_reset(gcm)) != CRYPT_OK) {
 
1350
      return err;
 
1351
   }
 
1352
 
 
1353
   /* Add the IV */
 
1354
   if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
 
1355
      return err;
 
1356
   }
 
1357
 
 
1358
   /* Add the AAD (note: aad can be NULL if aadlen == 0) */
 
1359
   if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
 
1360
      return err;
 
1361
   }
 
1362
 
 
1363
   /* process the plaintext */
 
1364
   if ((err = gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
 
1365
      return err;
 
1366
   }
 
1367
 
 
1368
   /* Finish up and get the MAC tag */
 
1369
   taglen = sizeof(tag);
 
1370
   if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
 
1371
      return err;
 
1372
   }
 
1373
 
 
1374
   /* ... send a header describing the lengths ... */
 
1375
 
 
1376
   /* depending on the protocol and how IV is generated you may have to send it too... */
 
1377
   send(socket, iv, ivlen, 0);
 
1378
 
 
1379
   /* send the aad */
 
1380
   send(socket, aad, aadlen, 0);
 
1381
 
 
1382
   /* send the ciphertext */
 
1383
   send(socket, pt, ptlen, 0);
 
1384
 
 
1385
   /* send the tag */
 
1386
   send(socket, tag, taglen, 0);
 
1387
 
 
1388
   return CRYPT_OK;
 
1389
}
 
1390
 
 
1391
int main(void)
 
1392
{
 
1393
   gcm_state     gcm;
 
1394
   unsigned char key[16], IV[12], pt[PACKET_SIZE];
 
1395
   int           err, x;
 
1396
   unsigned long ptlen; 
 
1397
 
 
1398
   /* somehow fill key/IV with random values */
 
1399
   
 
1400
   /* register AES */
 
1401
   register_cipher(&aes_desc);
 
1402
 
 
1403
   /* init the GCM state */
 
1404
   if ((err = gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
 
1405
      whine_and_pout(err);
 
1406
   }
 
1407
 
 
1408
   /* handle us some packets */
 
1409
   for (;;) {
 
1410
       ptlen = make_packet_we_want_to_send(pt);
 
1411
 
 
1412
       /* use IV as counter (12 byte counter) */
 
1413
       for (x = 11; x >= 0; x--) {
 
1414
           if (++IV[x]) {
 
1415
              break;
 
1416
           }
 
1417
       }
 
1418
 
 
1419
       if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm)) != CRYPT_OK) {
 
1420
           whine_and_pout(err);
 
1421
       }
 
1422
   }
 
1423
   return EXIT_SUCCESS;
 
1424
}
 
1425
\end{verbatim}
 
1426
\end{small}
 
1427
 
1122
1428
\chapter{One-Way Cryptographic Hash Functions}
1123
1429
\section{Core Functions}
1124
1430
 
1132
1438
This simply sets up the hash to the default state governed by the specifications of the hash.  To add data to the 
1133
1439
message being hashed call:
1134
1440
\begin{verbatim}
1135
 
int XXX_process(hash_state *md, const unsigned char *in, unsigned long len);
 
1441
int XXX_process(hash_state *md, const unsigned char *in, unsigned long inlen);
1136
1442
\end{verbatim}
1137
1443
 
1138
1444
Essentially all hash messages are virtually infinitely\footnote{Most hashes are limited to $2^{64}$ bits or 2,305,843,009,213,693,952 bytes.} long message which 
1167
1473
example snippet that hashes a message with md5 is given below.
1168
1474
\begin{small}
1169
1475
\begin{verbatim}
1170
 
#include <mycrypt.h>
 
1476
#include <tomcrypt.h>
1171
1477
int main(void)
1172
1478
{
1173
1479
    hash_state md;
1195
1501
    char *name;
1196
1502
    unsigned long hashsize;    /* digest output size in bytes  */
1197
1503
    unsigned long blocksize;   /* the block size the hash uses */
1198
 
    void (*init)   (hash_state *);
1199
 
    int  (*process)(hash_state *, const unsigned char *, unsigned long);
1200
 
    int  (*done)   (hash_state *, unsigned char *);
 
1504
    void (*init)   (hash_state *hash);
 
1505
    int  (*process)(hash_state *hash, 
 
1506
                    const unsigned char *in, unsigned long inlen);
 
1507
    int  (*done)   (hash_state *hash, unsigned char *out);
1201
1508
    int  (*test)   (void);
1202
1509
};
1203
1510
\end{verbatim}
1210
1517
You can use the table to indirectly call a hash function that is chosen at runtime.  For example:
1211
1518
\begin{small}
1212
1519
\begin{verbatim}
1213
 
#include <mycrypt.h>
 
1520
#include <tomcrypt.h>
1214
1521
int main(void)
1215
1522
{
1216
1523
   unsigned char buffer[100], hash[MAXBLOCKSIZE];
1258
1565
There are three helper functions as well:
1259
1566
\index{hash\_memory()} \index{hash\_file()}
1260
1567
\begin{verbatim}
1261
 
int hash_memory(int hash, const unsigned char *data, 
1262
 
                unsigned long len, unsigned char *dst,
1263
 
                unsigned long *outlen);
 
1568
int hash_memory(int hash, 
 
1569
                const unsigned char *in,   unsigned long inlen, 
 
1570
                      unsigned char *out,  unsigned long *outlen);
1264
1571
 
1265
1572
int hash_file(int hash, const char *fname, 
1266
 
              unsigned char *dst,
1267
 
              unsigned long *outlen);
 
1573
              unsigned char *out, unsigned long *outlen);
1268
1574
 
1269
1575
int hash_filehandle(int hash, FILE *in, 
1270
 
                    unsigned char *dst, unsigned long *outlen);
 
1576
                    unsigned char *out, unsigned long *outlen);
1271
1577
\end{verbatim}
1272
1578
 
1273
1579
The ``hash'' parameter is the location in the descriptor table of the hash (\textit{e.g. the return of find\_hash()}).  
1274
 
The ``*outlen'' variable is used to keep track of the output size.  You
1275
 
must set it to the size of your output buffer before calling the functions.  When they complete succesfully they store
1276
 
the length of the message digest back in it.  The functions are otherwise straightforward.  The ``hash\_filehandle'' 
1277
 
function assumes that ``in'' is an file handle opened in binary mode.  It will hash to the end of file and not reset
1278
 
the file position when finished.
 
1580
The ``*outlen'' variable is used to keep track of the output size.  You must set it to the size of your output buffer before 
 
1581
calling the functions.  When they complete succesfully they store the length of the message digest back in it.  The functions 
 
1582
are otherwise straightforward.  The ``hash\_filehandle'' function assumes that ``in'' is an file handle opened in binary mode.  
 
1583
It will hash to the end of file and not reset the file position when finished.
1279
1584
 
1280
1585
To perform the above hash with md5 the following code could be used:
1281
1586
\begin{small}
1282
1587
\begin{verbatim}
1283
 
#include <mycrypt.h>
 
1588
#include <tomcrypt.h>
1284
1589
int main(void)
1285
1590
{
1286
1591
   int idx, err;
1364
1669
Example of using CHC with the AES block cipher.
1365
1670
 
1366
1671
\begin{verbatim}
1367
 
#include <mycrypt.h>
 
1672
#include <tomcrypt.h>
1368
1673
int main(void)
1369
1674
{
1370
1675
   int err; 
1417
1722
length (in octets) of the key you want to use to authenticate the message.  To send octets of a message through the HMAC system you must use the following function:
1418
1723
\index{hmac\_process()}
1419
1724
\begin{verbatim}
1420
 
int hmac_process(hmac_state *hmac, const unsigned char *buf,
1421
 
                  unsigned long len);
 
1725
int hmac_process(hmac_state *hmac, 
 
1726
                 const unsigned char *in, unsigned long inlen);
1422
1727
\end{verbatim}
1423
1728
``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process.  ``len'' is the
1424
1729
number of octets to process.  Like the hash process routines you can send the data in arbitrarly sized chunks. When you 
1425
1730
are finished with the HMAC process you must call the following function to get the HMAC code:
1426
1731
\index{hmac\_done()}
1427
1732
\begin{verbatim}
1428
 
int hmac_done(hmac_state *hmac, unsigned char *hashOut,
1429
 
              unsigned long *outlen);
 
1733
int hmac_done(hmac_state *hmac, 
 
1734
              unsigned char *out, unsigned long *outlen);
1430
1735
\end{verbatim}
1431
 
``hmac'' is the HMAC state you are working with.  ``hashOut'' is the array of octets where the HMAC code should be stored.  You must
 
1736
``hmac'' is the HMAC state you are working with.  ``out'' is the array of octets where the HMAC code should be stored.  You must
1432
1737
set ``outlen'' to the size of the destination buffer before calling this function.  It is updated with the length of the HMAC code
1433
1738
produced (depending on which hash was picked).  If ``outlen'' is less than the size of the message digest (and ultimately
1434
1739
the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first ``outlen'' bytes).
1439
1744
 
1440
1745
\index{hmac\_memory()}
1441
1746
\begin{verbatim}
1442
 
int hmac_memory(int hash, const unsigned char *key, unsigned long keylen,
1443
 
                const unsigned char *data, unsigned long len, 
1444
 
                unsigned char *dst, unsigned long *dstlen);
 
1747
int hmac_memory(int hash, 
 
1748
                const unsigned char *key, unsigned long  keylen,
 
1749
                const unsigned char *in,  unsigned long  inlen, 
 
1750
                      unsigned char *out, unsigned long *outlen);
1445
1751
\end{verbatim}
1446
 
This will produce an HMAC code for the array of octets in ``data'' of length ``len''.  The index into the hash descriptor 
 
1752
This will produce an HMAC code for the array of octets in ``in'' of length ``inlen''.  The index into the hash descriptor 
1447
1753
table must be provided in ``hash''.  It uses the key from ``key'' with a key length of ``keylen''.  
1448
 
The result is stored in the array of octets ``dst'' and the length in ``dstlen''.  The value of ``dstlen'' must be set
 
1754
The result is stored in the array of octets ``out'' and the length in ``outlen''.  The value of ``outlen'' must be set
1449
1755
to the size of the destination buffer before calling this function.  Similarly for files there is the  following function:
1450
1756
\index{hmac\_file()}
1451
1757
\begin{verbatim}
1452
 
int hmac_file(int hash, const char *fname, const unsigned char *key,
1453
 
              unsigned long keylen, 
1454
 
              unsigned char *dst, unsigned long *dstlen);
 
1758
int hmac_file(int hash, const char *fname, 
 
1759
              const unsigned char *key, unsigned long  keylen, 
 
1760
                    unsigned char *out, unsigned long *outlen);
1455
1761
\end{verbatim}
1456
1762
``hash'' is the index into the hash descriptor table of the hash you want to use.  ``fname'' is the filename to process.  
1457
 
``key'' is the array of octets to use as the key of length ``keylen''.  ``dst'' is the array of octets where the 
 
1763
``key'' is the array of octets to use as the key of length ``keylen''.  ``out'' is the array of octets where the 
1458
1764
result should be stored.
1459
1765
 
1460
1766
To test if the HMAC code is working there is the following function:
1467
1773
 
1468
1774
\begin{small}
1469
1775
\begin{verbatim}
1470
 
#include <mycrypt.h>
 
1776
#include <tomcrypt.h>
1471
1777
int main(void)
1472
1778
{
1473
1779
   int idx, err;
1531
1837
\index{omac\_process()}
1532
1838
\begin{verbatim}
1533
1839
int omac_process(omac_state *state, 
1534
 
                 const unsigned char *buf, unsigned long len);
 
1840
                 const unsigned char *in, unsigned long inlen);
1535
1841
\end{verbatim}
1536
 
This will send ``len'' bytes from ``buf'' through the active OMAC state ``state''.  Returns \textbf{CRYPT\_OK} if the 
 
1842
This will send ``inlen'' bytes from ``in'' through the active OMAC state ``state''.  Returns \textbf{CRYPT\_OK} if the 
1537
1843
function succeeds.  The function is not sensitive to the granularity of the data.  For example,
1538
1844
 
1539
1845
\begin{verbatim}
1567
1873
\begin{verbatim}
1568
1874
int omac_memory(int cipher, 
1569
1875
                const unsigned char *key, unsigned long keylen,
1570
 
                const unsigned char *msg, unsigned long msglen,
1571
 
                unsigned char *out, unsigned long *outlen);
 
1876
                const unsigned char *in,  unsigned long inlen,
 
1877
                      unsigned char *out, unsigned long *outlen);
1572
1878
\end{verbatim}
1573
 
This will compute the OMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
 
1879
This will compute the OMAC of ``inlen'' bytes of ``in'' using the key ``key'' of length ``keylen'' bytes and the cipher
1574
1880
specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
1575
1881
rules as omac\_done.
1576
1882
 
1580
1886
int omac_file(int cipher, 
1581
1887
              const unsigned char *key, unsigned long keylen,
1582
1888
              const char *filename, 
1583
 
              unsigned char *out, unsigned long *outlen);
 
1889
                    unsigned char *out, unsigned long *outlen);
1584
1890
\end{verbatim}
1585
1891
 
1586
1892
Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
1597
1903
 
1598
1904
\begin{small}
1599
1905
\begin{verbatim}
1600
 
#include <mycrypt.h>
 
1906
#include <tomcrypt.h>
1601
1907
int main(void)
1602
1908
{
1603
1909
   int idx, err;
1662
1968
\index{pmac\_process()}
1663
1969
\begin{verbatim}
1664
1970
int pmac_process(pmac_state *state, 
1665
 
                 const unsigned char *buf, unsigned long len);
 
1971
                 const unsigned char *in, unsigned long inlen);
1666
1972
\end{verbatim}
1667
 
This will process ``len'' bytes of ``buf'' in the given ``state''.  The function is not sensitive to the granularity of the
 
1973
This will process ``inlen'' bytes of ``in'' in the given ``state''.  The function is not sensitive to the granularity of the
1668
1974
data.  For example,
1669
1975
 
1670
1976
\begin{verbatim}
1694
2000
\index{pmac\_memory()}
1695
2001
\begin{verbatim}
1696
2002
int pmac_memory(int cipher, 
1697
 
                const unsigned char *key, unsigned long keylen,
1698
 
                const unsigned char *msg, unsigned long msglen,
1699
 
                unsigned char *out, unsigned long *outlen);
 
2003
                const unsigned char *key, unsigned long  keylen,
 
2004
                const unsigned char *in,  unsigned long  inlen,
 
2005
                      unsigned char *out, unsigned long *outlen);
1700
2006
\end{verbatim}
1701
2007
This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
1702
2008
specified by the ``cipher'''th entry in the cipher\_descriptor table.  It will store the MAC in ``out'' with the same
1716
2022
the same rules as omac\_done.
1717
2023
 
1718
2024
To test if the PMAC code is working there is the following function:
 
2025
\index{pmac\_test()}
1719
2026
\begin{verbatim}
1720
2027
int pmac_test(void);
1721
2028
\end{verbatim}
1722
2029
Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
1723
2030
 
1724
 
 
1725
 
 
 
2031
\section{Pelican MAC}
 
2032
Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a ``mixing function''.  It achieves a very high 
 
2033
rate of processing and is potentially very secure.  It requires AES to be enabled to function.  You do not have to register\_cipher() AES first though
 
2034
as it calls AES directly.
 
2035
 
 
2036
\index{pelican\_init()}
 
2037
\begin{verbatim}
 
2038
int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
 
2039
\end{verbatim}
 
2040
This will initialize the Pelican state with the given AES key.  Once this has been done you can begin processing data.
 
2041
 
 
2042
\index{pelican\_process()}
 
2043
\begin{verbatim}
 
2044
int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
 
2045
\end{verbatim}
 
2046
This will process ``inlen'' bytes of ``in'' through the Pelican MAC.  It's best that you pass in multiples of 16 bytes as it makes the
 
2047
routine more efficient but you may pass in any length of text.  You can call this function as many times as required to process
 
2048
an entire message.
 
2049
 
 
2050
\index{pelican\_done()}
 
2051
\begin{verbatim}
 
2052
int pelican_done(pelican_state *pelmac, unsigned char *out);
 
2053
\end{verbatim}
 
2054
This terminates a Pelican MAC and writes the 16--octet tag to ``out''.
 
2055
 
 
2056
\subsection{Example}
 
2057
 
 
2058
\begin{verbatim}
 
2059
#include <tomcrypt.h>
 
2060
int main(void)
 
2061
{
 
2062
   pelican_state pelstate;
 
2063
   unsigned char key[32], tag[16];
 
2064
   int           err;
 
2065
 
 
2066
   /* somehow initialize a key */
 
2067
 
 
2068
   /* initialize pelican mac */
 
2069
   if ((err = pelican_init(&pelstate,          /* the state */
 
2070
                           key,                /* user key */
 
2071
                           32                  /* key length in octets */
 
2072
                          )) != CRYPT_OK) {
 
2073
      printf("Error initializing Pelican: %s", error_to_string(err));
 
2074
      return EXIT_FAILURE;
 
2075
   }
 
2076
 
 
2077
   /* MAC some data */
 
2078
   if ((err = pelican_process(&pelstate,       /* the state */
 
2079
                              "hello world",   /* data to mac */        
 
2080
                              11               /* length of data */
 
2081
                              )) != CRYPT_OK) {
 
2082
      printf("Error processing Pelican: %s", error_to_string(err));
 
2083
      return EXIT_FAILURE;
 
2084
   }
 
2085
 
 
2086
   /* Terminate the MAC */
 
2087
   if ((err = pelican_done(&pelstate,       /* the state */
 
2088
                           tag              /* where to store the tag */
 
2089
                           )) != CRYPT_OK) {
 
2090
      printf("Error terminating Pelican: %s", error_to_string(err));
 
2091
      return EXIT_FAILURE;
 
2092
   }
 
2093
 
 
2094
   /* tag[0..15] has the MAC output now */
 
2095
 
 
2096
   return EXIT_SUCCESS;
 
2097
}
 
2098
\end{verbatim}
1726
2099
 
1727
2100
 
1728
2101
\chapter{Pseudo-Random Number Generators}
1735
2108
int XXX_start(prng_state *prng);
1736
2109
\end{verbatim}
1737
2110
 
1738
 
This will setup the PRNG for future use and not seed it.  In order 
1739
 
for the PRNG to be cryptographically useful you must give it entropy.  Ideally you'd have some OS level source to tap 
1740
 
like in UNIX (see section 5.3).  To add entropy to the PRNG call:
 
2111
This will setup the PRNG for future use and not seed it.  In order for the PRNG to be cryptographically useful you must give it 
 
2112
entropy.  Ideally you'd have some OS level source to tap like in UNIX.  To add entropy to the PRNG call:
1741
2113
\index{PRNG add\_entropy}
1742
2114
\begin{verbatim}
1743
 
int XXX_add_entropy(const unsigned char *in, unsigned long len, 
 
2115
int XXX_add_entropy(const unsigned char *in, unsigned long inlen, 
1744
2116
                    prng_state *prng);
1745
2117
\end{verbatim}
1746
2118
 
1754
2126
Which returns {\bf CRYPTO\_OK} if it is ready.  Finally to actually read bytes call:
1755
2127
\index{PRNG read}
1756
2128
\begin{verbatim}
1757
 
unsigned long XXX_read(unsigned char *out, unsigned long len,
 
2129
unsigned long XXX_read(unsigned char *out, unsigned long outlen,
1758
2130
                       prng_state *prng);
1759
2131
\end{verbatim}
1760
2132
 
1831
2203
{\bf NOT} secure since the entropy added is not random.
1832
2204
 
1833
2205
\begin{verbatim}
1834
 
#include <mycrypt.h>
 
2206
#include <tomcrypt.h>
1835
2207
int main(void)
1836
2208
{
1837
2209
   prng_state prng;
1961
2333
\subsubsection{Example Usage}
1962
2334
\begin{small}
1963
2335
\begin{verbatim}
1964
 
#include <mycrypt.h>
 
2336
#include <tomcrypt.h>
1965
2337
int main(void)
1966
2338
{
1967
2339
   prng_state prng;
2029
2401
 
2030
2402
\begin{small}
2031
2403
\begin{verbatim}
2032
 
#include <mycrypt.h>
 
2404
#include <tomcrypt.h>
2033
2405
int main(void)
2034
2406
{
2035
2407
   ecc_key mykey;
2066
2438
 
2067
2439
\begin{small}
2068
2440
\begin{verbatim}
2069
 
#include <mycrypt.h>
 
2441
#include <tomcrypt.h>
2070
2442
int main(void)
2071
2443
{
2072
2444
   ecc_key mykey;
2088
2460
\end{verbatim}
2089
2461
\end{small}
2090
2462
 
 
2463
 
 
2464
 
2091
2465
\chapter{RSA Public Key Cryptography}
2092
2466
 
2093
2467
\section{Introduction}
2094
2468
RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography.  In the specifications are
2095
 
padding algorithms for encryption and signatures.  The standard includes ``v1.5'' and ``v2.0'' algorithms.
2096
 
To simplify matters a little the v2.0 encryption and signature padding algorithms are called OAEP and PSS 
 
2469
padding algorithms for encryption and signatures.  The standard includes the ``v2.1'' algorithms.
 
2470
To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS 
2097
2471
respectively.  
2098
2472
 
2099
2473
\section{PKCS \#1 Encryption}
2149
2523
$1$ in ``res''.  If the packet is invalid it stores $0$ in ``res'' and if the function fails for another reason
2150
2524
it returns an error code.  
2151
2525
 
2152
 
\subsection{PKCS \#1 v1.5 Encoding}
2153
 
 
2154
 
\index{pkcs\_1\_v15\_es\_encode()}
2155
 
\begin{verbatim}
2156
 
int pkcs_1_v15_es_encode(const unsigned char *msg,    unsigned long msglen,
2157
 
                               unsigned long  modulus_bitlen, 
2158
 
                               prng_state    *prng,   int           prng_idx,
2159
 
                               unsigned char *out,    unsigned long *outlen);
2160
 
\end{verbatim}
2161
 
 
2162
 
This will PKCS v1.5 encode the data in ``msg'' of length ``msglen''.  Pass the length (in bits) of your
2163
 
RSA modulus in ``modulus\_bitlen''.  The encoded data will be stored in ``out'' of length ``outlen''.
2164
 
 
2165
 
\subsection{PKCS \#1 v1.5 Decoding}
2166
 
\index{pkcs\_1\_v15\_es\_decode()}
2167
 
\begin{verbatim}
2168
 
int pkcs_1_v15_es_decode(const unsigned char *msg,  unsigned long msglen,
2169
 
                               unsigned long modulus_bitlen,
2170
 
                               unsigned char *out,  unsigned long outlen,
2171
 
                               int           *res);
2172
 
\end{verbatim}
2173
 
 
2174
 
This will PKCS v1.5 decode the message in ``msg'' of length ``msglen''.  It will store the output in ``out''. Note
2175
 
that the length of the output ``outlen'' is a constant.  This decoder cannot determine the original message 
2176
 
length.  If the data in ``msg'' is a valid packet then a $1$ is stored in ``res'', otherwise a $0$ is 
2177
 
stored.
2178
 
 
2179
2526
\section{PKCS \#1 Digital Signatures}
2180
2527
 
2181
2528
\subsection{PSS Encoding}
2217
2564
 
2218
2565
It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
2219
2566
 
2220
 
\subsection{PKCS \#1 v1.5 Encoding}
2221
 
 
2222
 
\index{pkcs\_1\_v15\_sa\_encode()}
2223
 
\begin{verbatim}
2224
 
int pkcs_1_v15_sa_encode(const unsigned char *msghash,  unsigned long msghashlen,
2225
 
                               int            hash_idx, unsigned long modulus_bitlen,
2226
 
                               unsigned char *out,      unsigned long *outlen);
2227
 
\end{verbatim}
2228
 
 
2229
 
This will PKCS \#1 v1.5 signature encode the message hash ``msghash''  of length ``msghashlen''.  You have
2230
 
to tell this routine which hash produced the message hash in ``hash\_idx''.  The encoded hash is stored
2231
 
in ``out'' of length ``outlen''.
2232
 
 
2233
 
\subsection{PKCS \#1 v1.5 Decoding}
2234
 
 
2235
 
\index{pkcs\_1\_v15\_sa\_decode()}
2236
 
\begin{verbatim}
2237
 
int pkcs_1_v15_sa_decode(const unsigned char *msghash, unsigned long msghashlen,
2238
 
                         const unsigned char *sig,     unsigned long siglen,
2239
 
                               int           hash_idx, unsigned long modulus_bitlen, 
2240
 
                               int          *res);
2241
 
\end{verbatim}
2242
 
 
2243
 
This will PKCS \#1 v1.5 signature decode the data in ``sig'' of length ``siglen'' and compare the extracted
2244
 
hash against ``msghash'' of length ``msghashlen''.  You have to tell this routine which hash produced the
2245
 
message digest in ``hash\_idx''.  If the packet is valid and the hashes match ``res'' is set to $1$.  Otherwise,
2246
 
it is set to $0$.
2247
 
 
2248
2567
\section{RSA Operations}
2249
2568
\subsection{Background}
2250
2569
 
2307
2626
\index{rsa\_exptmod()}
2308
2627
\begin{verbatim}
2309
2628
int rsa_exptmod(const unsigned char *in,   unsigned long inlen,
2310
 
                      unsigned char *out,  unsigned long *outlen, int which,
2311
 
                      prng_state    *prng, int           prng_idx,
 
2629
                      unsigned char *out,  unsigned long *outlen, 
 
2630
                      int which, prng_state *prng, int prng_idx,
2312
2631
                      rsa_key *key);
2313
2632
\end{verbatim}
2314
2633
This loads the bignum from ``in'' as a big endian word in the format PKCS specifies, raises it to either ``e'' or ``d'' and stores the result
2324
2643
 
2325
2644
\index{rsa\_encrypt\_key()}
2326
2645
\begin{verbatim}
2327
 
int rsa_encrypt_key(const unsigned char *inkey,  unsigned long inlen,
2328
 
                          unsigned char *outkey, unsigned long *outlen,
 
2646
int rsa_encrypt_key(const unsigned char *in,  unsigned long inlen,
 
2647
                          unsigned char *out, unsigned long *outlen,
2329
2648
                    const unsigned char *lparam, unsigned long lparamlen,
2330
2649
                    prng_state *prng, int prng_idx, int hash_idx, rsa_key *key);
2331
2650
\end{verbatim}
2332
 
This function will OAEP pad ``inkey'' of length inlen bytes then RSA encrypt it and store the ciphertext
2333
 
in ``outkey'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
 
2651
This function will OAEP pad ``in'' of length inlen bytes then RSA encrypt it and store the ciphertext
 
2652
in ``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2334
2653
to pkcs\_1\_oaep\_encode().
2335
2654
 
2336
2655
\index{rsa\_decrypt\_key()}
2337
2656
\begin{verbatim}
2338
 
int rsa_decrypt_key(const unsigned char *in,     unsigned long inlen,
2339
 
                          unsigned char *outkey, unsigned long *keylen, 
 
2657
int rsa_decrypt_key(const unsigned char *in,  unsigned long inlen,
 
2658
                          unsigned char *out, unsigned long *outlen, 
2340
2659
                    const unsigned char *lparam, unsigned long lparamlen,
2341
 
                          prng_state    *prng,   int           prng_idx,
2342
 
                          int            hash_idx, int *res,
 
2660
                          int            hash_idx, int *stat,
2343
2661
                          rsa_key       *key);
2344
2662
\end{verbatim}
2345
2663
This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
2346
 
``outkey'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
 
2664
``out'' of length ``outlen''.  The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2347
2665
to pkcs\_1\_oaep\_decode().
2348
2666
 
2349
 
If the RSA decrypted data isn't a valid OAEP packet then ``res'' is set to $0$.  Otherwise, it is set to $1$.
 
2667
If the RSA decrypted data isn't a valid OAEP packet then ``stat'' is set to $0$.  Otherwise, it is set to $1$.
2350
2668
 
2351
2669
\subsection{RSA Hash Signatures}
2352
2670
Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes).  To facilitate this
2354
2672
 
2355
2673
\index{rsa\_sign\_hash()}
2356
2674
\begin{verbatim}
2357
 
int rsa_sign_hash(const unsigned char *msghash,  unsigned long  msghashlen, 
2358
 
                        unsigned char *sig,      unsigned long *siglen, 
 
2675
int rsa_sign_hash(const unsigned char *in,   unsigned long  inlen, 
 
2676
                        unsigned char *out,  unsigned long *outlen, 
2359
2677
                        prng_state    *prng,     int            prng_idx,
2360
2678
                        int            hash_idx, unsigned long  saltlen,
2361
2679
                        rsa_key *key);
2362
2680
\end{verbatim}
2363
2681
 
2364
 
This will PSS encode the message hash ``msghash'' of length ``msghashlen''.  Next the PSS encoded message is
2365
 
RSA ``signed'' and the output is stored in ``sig'' of length ``siglen''.  
 
2682
This will PSS encode the message hash ``in'' of length ``inlen''.  Next the PSS encoded message will be RSA ``signed'' and 
 
2683
the output is stored in ``out'' of length ``outlen''.  
2366
2684
 
2367
2685
 
2368
2686
\index{rsa\_verify\_hash()}
2369
2687
\begin{verbatim}
2370
2688
int rsa_verify_hash(const unsigned char *sig,      unsigned long siglen,
2371
2689
                    const unsigned char *msghash,  unsigned long msghashlen,
2372
 
                          prng_state    *prng,     int           prng_idx,
2373
2690
                          int            hash_idx, unsigned long saltlen,
2374
2691
                          int           *stat,     rsa_key      *key);
2375
2692
\end{verbatim}
2382
2699
to $1$.
2383
2700
 
2384
2701
\begin{verbatim}
2385
 
#include <mycrypt.h>
 
2702
#include <tomcrypt.h>
2386
2703
int main(void)
2387
2704
{
2388
2705
   int           err, hash_idx, prng_idx, res;
2439
2756
                              &l2, /* plaintext length */
2440
2757
                        "TestApp", /* lparam for this program */
2441
2758
                                7, /* lparam is 7 bytes long */
2442
 
                             NULL, /* PRNG state */
2443
 
                         prng_idx, /* prng idx */
2444
2759
                         hash_idx, /* hash idx */
2445
2760
                             &res, /* validity of data */
2446
2761
                             &key) /* our RSA key */ 
2646
2961
algorithms.  
2647
2962
\index{dh\_encrypt\_key()} \index{dh\_decrypt\_key()}
2648
2963
\begin{verbatim}
2649
 
int dh_encrypt_key(const unsigned char *inkey, unsigned long keylen,
 
2964
int dh_encrypt_key(const unsigned char *in,   unsigned long  inlen,
2650
2965
                         unsigned char *out,  unsigned long *len, 
2651
2966
                         prng_state *prng, int wprng, int hash, 
2652
2967
                         dh_key *key);
2653
2968
 
2654
 
int dh_decrypt_key(const unsigned char *in, unsigned long inlen,
2655
 
                         unsigned char *outkey, unsigned long *keylen, 
 
2969
int dh_decrypt_key(const unsigned char *in,  unsigned long  inlen,
 
2970
                         unsigned char *out, unsigned long *outlen, 
2656
2971
                         dh_key *key);
2657
2972
\end{verbatim}
2658
 
Where ``inkey'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
 
2973
Where ``in'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
2659
2974
and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the 
2660
2975
required data is placed in ``out'' by ``dh\_encrypt\_key()''.   The hash must produce a message digest at least as large
2661
2976
as the symmetric key you are trying to share.
2700
3015
range in order from $\approx 2^{192}$ points to $\approx 2^{521}$.  According to the source document any key size greater
2701
3016
than or equal to 256-bits is sufficient for long term security.  
2702
3017
 
 
3018
\section{Key Format}
 
3019
LibTomCrypt uses it's own format for ECC public and private keys.  While ANSI X9.62 partially specifies key formats (it covers public keys) it does it in a less
 
3020
than ideally simple manner.  In the case of LibTomCrypt it is meant \textbf{solely} for NIST $GF(p)$ curves.  The format of the keys is as follows:
 
3021
 
 
3022
\begin{small}
 
3023
\begin{verbatim}
 
3024
ECCPublicKey ::= SEQUENCE {
 
3025
    flags       BIT STRING(1), -- public/private flag (always zero), 
 
3026
    keySize     INTEGER,       -- Curve size (in bits) divided by eight 
 
3027
                               -- and rounded down, e.g. 521 => 65
 
3028
    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
 
3029
    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
 
3030
}
 
3031
 
 
3032
ECCPrivateKey ::= SEQUENCE {
 
3033
    flags       BIT STRING(1), -- public/private flag (always one), 
 
3034
    keySize     INTEGER,       -- Curve size (in bits) divided by eight 
 
3035
                               -- and rounded down, e.g. 521 => 65
 
3036
    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
 
3037
    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
 
3038
    secret.k    INTEGER,       -- The secret key scalar
 
3039
}
 
3040
\end{verbatim}
 
3041
\end{small}
 
3042
 
 
3043
The first flags bit denotes whether the key is public (zero) or private (one).  
 
3044
 
2703
3045
\section{Core Functions}
2704
3046
 
2705
3047
Like the DH routines there is a key structure ``ecc\_key'' used by the functions.  There is a function to make a key:
2709
3051
                 int keysize, ecc_key *key);
2710
3052
\end{verbatim}
2711
3053
 
2712
 
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
2713
 
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
 
3054
The ``keysize'' is the size of the modulus in bytes desired.  Currently directly supported values are 24, 28, 32, 48 and 65 bytes which
 
3055
correspond to key sizes of 192, 224, 256, 384 and 521 bits respectively.  If you pass a key size that is between any key size
2714
3056
it will round the keysize up to the next available one.  The rest of the parameters work like they do in the ``dh\_make\_key()'' function.  
2715
3057
To free the ram allocated by a key call:
2716
3058
\index{ecc\_free()}
2759
3101
 
2760
3102
\index{ecc\_encrypt\_key()} \index{ecc\_decrypt\_key()}
2761
3103
\begin{verbatim}
2762
 
int ecc_encrypt_key(const unsigned char *inkey, unsigned long keylen,
2763
 
                          unsigned char *out,  unsigned long *len, 
 
3104
int ecc_encrypt_key(const unsigned char *in,   unsigned long  inlen,
 
3105
                          unsigned char *out,  unsigned long *outlen, 
2764
3106
                          prng_state *prng, int wprng, int hash, 
2765
3107
                          ecc_key *key);
2766
3108
 
2767
 
int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
2768
 
                          unsigned char *outkey, unsigned long *keylen, 
 
3109
int ecc_decrypt_key(const unsigned char *in,  unsigned long  inlen,
 
3110
                          unsigned char *out, unsigned long *outlen, 
2769
3111
                          ecc_key *key);
2770
3112
\end{verbatim}
2771
3113
 
2772
 
Where ``inkey'' is an input symmetric key of no more than 32 bytes.  Essentially these routines created a random public key
 
3114
Where ``in'' is an input symmetric key of no more than 64 bytes.  Essentially these routines created a random public key
2773
3115
and find the hash of the shared secret.  The message digest is than XOR'ed against the symmetric key.  All of the required
2774
3116
data is placed in ``out'' by ``ecc\_encrypt\_key()''.   The hash chosen must produce a message digest at least as large
2775
3117
as the symmetric key you are trying to share.
2776
3118
 
 
3119
\subsection{Encrypt Packet Format}
 
3120
 
 
3121
The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
 
3122
 
 
3123
\begin{verbatim}
 
3124
ECCEncrypt ::= SEQUENCE {
 
3125
   hashID        OBJECT IDENTIFIER, -- OID of hash used
 
3126
   pubkey        OCTET STRING     , -- Encapsulated ECCPublicKey (see above)
 
3127
   skey          OCTET STRING       -- xor of plaintext and "hash of shared secret"
 
3128
}
 
3129
\end{verbatim}
 
3130
 
2777
3131
There are also functions to sign and verify the hash of a message.
2778
3132
\index{ecc\_sign\_hash()} \index{ecc\_verify\_hash()}
2779
3133
\begin{verbatim}
2790
3144
The ``ecc\_verify\_hash'' function verifies the ECC signature in ``sig'' against the hash in ``hash''.  It sets ``stat''
2791
3145
to non-zero if the signature passes or zero if it fails.
2792
3146
 
 
3147
\subsection{Signature Format}
 
3148
The signature code is an implementation of X9.62 EC-DSA and the output is comformant for GF(p) curves.
2793
3149
 
2794
3150
\section{ECC Keysizes}
2795
3151
With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems.  The math will still work
2796
3152
and in effect the signature will still work.  With ECC keys the strength of the signature is limited by the size of
2797
 
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
2798
 
you have 160-bits of security (e.g. as if you signed with SHA-1).  
 
3153
the hash or the size of they key, whichever is smaller.  For example, if you sign with SHA256 and an ECC-192 key in effect
 
3154
you have 192-bits of security.  
2799
3155
 
2800
3156
The library will not warn you if you make this mistake so it is important to check yourself before using the 
2801
3157
signatures.
2810
3166
The API for the DSA is essentially the same as the other PK algorithms.  Except in the case of DSA no encryption or
2811
3167
decryption routines are provided.  
2812
3168
 
 
3169
\section{Key Format}
 
3170
Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
 
3171
now so that others can interoperate with this library.
 
3172
 
 
3173
\begin{verbatim}
 
3174
DSAPublicKey ::= SEQUENCE {
 
3175
    publicFlags    BIT STRING(1), -- must be 0
 
3176
    g              INTEGER      , -- base generator, check that g^q mod p == 1
 
3177
                                  -- and that 1 < g < p - 1
 
3178
    p              INTEGER      , -- prime modulus 
 
3179
    q              INTEGER      , -- order of sub-group (must be prime)
 
3180
    y              INTEGER      , -- public key, specifically, g^x mod p, 
 
3181
                                  -- check that y^q mod p == 1
 
3182
                                  -- and that 1 < y < p - 1
 
3183
}
 
3184
 
 
3185
DSAPrivateKey ::= SEQUENCE {
 
3186
    publicFlags    BIT STRING(1), -- must be 1
 
3187
    g              INTEGER      , -- base generator, check that g^q mod p == 1
 
3188
                                  -- and that 1 < g < p - 1
 
3189
    p              INTEGER      , -- prime modulus 
 
3190
    q              INTEGER      , -- order of sub-group (must be prime)
 
3191
    y              INTEGER      , -- public key, specifically, g^x mod p, 
 
3192
                                  -- check that y^q mod p == 1
 
3193
                                  -- and that 1 < y < p - 1
 
3194
    x              INTEGER        -- private key
 
3195
}
 
3196
\end{verbatim}
 
3197
 
 
3198
The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys.  This makes the structure uniquely decodable and easy
 
3199
to work with.
 
3200
 
2813
3201
\section{Key Generation}
2814
3202
To make a DSA key you must call the following function
2815
3203
\begin{verbatim}
2931
3319
will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).  
2932
3320
 
2933
3321
\chapter{Standards Support}
2934
 
\section{DER Support}
2935
 
DER or ``Distinguished Encoding Rules'' is a subset of the ASN.1 encoding rules that is fully deterministic and
2936
 
ideal for cryptography.  In particular ASN.1 specifies an INTEGER type for storing arbitrary sized integers.  DER
2937
 
further limits the ASN.1 specifications to a deterministic encoding.
2938
 
 
2939
 
\subsection{Storing INTEGER types}
 
3322
\section{ASN.1 Formats}
 
3323
LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols.  The data types
 
3324
are all provided with three basic functions with \textit{similar} prototypes.  One function has been dedicated to calculate the length in octets of a given
 
3325
format and two functions have been dedicated to encoding and decoding the format.  
 
3326
 
 
3327
On top of the basic data types are the SEQUENCE and\footnote{Planned for LTC 1.06} SET data types which are collections of other ASN.1 types.  They are provided 
 
3328
in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure.  It is defined as 
 
3329
 
 
3330
\index{ltc\_asn1\_list structure}
 
3331
\begin{verbatim}
 
3332
typedef struct {
 
3333
   int           type;
 
3334
   void         *data;
 
3335
   unsigned long size;
 
3336
   int           used;
 
3337
} ltc_asn1_list;
 
3338
\end{verbatim}
 
3339
 
 
3340
The ``type'' field is one of the following ASN.1 field definitions.  The ``data'' pointer is a void pointer to the data to be encoded (or the destination) and the 
 
3341
``size'' field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type).  The ``used'' field is primarily for the CHOICE decoder
 
3342
and reflects if the particular member of a list was the decoded data type.  To help build the lists in an orderly fashion the macro
 
3343
``LTC\_SET\_ASN1(list, index, Type, Data, Size)'' has been provided.
 
3344
 
 
3345
It will assign to the ``index''th position in the ``list'' the tripplet (Type, Data, Size).  An example usage would be:
 
3346
 
 
3347
\begin{small}
 
3348
\begin{verbatim}
 
3349
...
 
3350
ltc_asn1_list   sequence[3];
 
3351
unsigned long   three=3;
 
3352
 
 
3353
LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING,    "hello", 5);
 
3354
LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three,  1);
 
3355
LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL,           NULL,   0);
 
3356
\end{verbatim}
 
3357
\end{small}
 
3358
 
 
3359
The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
 
3360
 
 
3361
\begin{small}
 
3362
\begin{verbatim}
 
3363
...
 
3364
ltc_asn1_list   sequence[3];
 
3365
unsigned long   three=3;
 
3366
int             x=0;
 
3367
LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING,    "hello", 5);
 
3368
LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three,  1);
 
3369
LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL,           NULL,   0);
 
3370
\end{verbatim}
 
3371
\end{small}
 
3372
 
 
3373
\begin{figure}[here]
 
3374
\begin{center}
 
3375
\begin{small}
 
3376
\begin{tabular}{|l|l|}
 
3377
\hline \textbf{Definition}           & \textbf{ASN.1 Type} \\
 
3378
\hline LTC\_ASN1\_EOL                & End of a ASN.1 list structure. \\
 
3379
\hline LTC\_ASN1\_INTEGER            & INTEGER (uses mp\_int) \\
 
3380
\hline LTC\_ASN1\_SHORT\_INTEGER     & INTEGER (32--bit using unsigned long) \\
 
3381
\hline LTC\_ASN1\_BIT\_STRING        & BIT STRING (one bit per char) \\
 
3382
\hline LTC\_ASN1\_OCTET\_STRING      & OCTET STRING (one octet per char) \\
 
3383
\hline LTC\_ASN1\_NULL               & NULL \\
 
3384
\hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER (words are in unsigned long) \\
 
3385
\hline LTC\_ASN1\_IA5\_STRING        & IA5 STRING (one octet per char) \\
 
3386
\hline LTC\_ASN1\_PRINTABLE\_STRING  & PRINTABLE STIRNG (one octet per char) \\
 
3387
\hline LTC\_ASN1\_UTCTIME            & UTCTIME (see ltc\_utctime structure) \\
 
3388
\hline LTC\_ASN1\_SEQUENCE           & SEQUENCE OF \\
 
3389
\hline LTC\_ASN1\_CHOICE             & CHOICE \\
 
3390
\hline
 
3391
\end{tabular}
 
3392
\caption{List of ASN.1 Supported Types}
 
3393
\end{small}
 
3394
\end{center}
 
3395
\end{figure}
 
3396
 
 
3397
\subsection{SEQUENCE Type}
 
3398
The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
 
3399
 
 
3400
\subsubsection{SEUQNECE Encoding}
 
3401
To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers.  The encoding is performed
 
3402
with the following function.
 
3403
 
 
3404
\index{der\_encode\_sequence()}
 
3405
\begin{verbatim}
 
3406
int der_encode_sequence(ltc_asn1_list *list, unsigned long inlen,
 
3407
                        unsigned char *out,  unsigned long *outlen);
 
3408
\end{verbatim}
 
3409
This encodes a sequence of items pointed to by ``list'' where the list has ``inlen'' items in it.  The SEQUENCE will be encoded to ``out'' and of length ``outlen''.  The
 
3410
function will terminate when it reads all the items out of the list (upto ``inlen'') or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
 
3411
 
 
3412
The ``data'' pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
 
3413
verbatim to the dependent encoder.  The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions.  In these cases
 
3414
the ``data'' pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
 
3415
 
 
3416
\subsubsection{SEQUENCE Decoding}
 
3417
 
 
3418
\index{der\_decode\_sequence()}
 
3419
 
 
3420
Decoding a SEQUENCE is similar to encoding.  You set up an array of \textbf{ltc\_asn1\_list} where in this case the ``size'' member is the maximum size 
 
3421
(in certain cases).  For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the ``size'' field is updated after successful decoding to reflect how many
 
3422
units of the respective type has been loaded.  
 
3423
 
 
3424
\begin{verbatim}
 
3425
int der_decode_sequence(const unsigned char *in,   unsigned long  inlen,
 
3426
                              ltc_asn1_list *list, unsigned long  outlen);
 
3427
\end{verbatim}
 
3428
 
 
3429
This will decode upto ``outlen'' items from the input buffer ``in'' of length ``inlen'' octets.  The function will stop (gracefully) when it runs out of items to decode.
 
3430
It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occured.
 
3431
 
 
3432
For the following types the ``size'' field will be updated to reflect the number of units read of the given type.
 
3433
\begin{enumerate}
 
3434
   \item BIT STRING
 
3435
   \item OCTET STRING
 
3436
   \item OBJECT IDENTIFIER
 
3437
   \item IA5 STRING
 
3438
   \item PRINTABLE STRING
 
3439
\end{enumerate}
 
3440
 
 
3441
\subsubsection{SEQUENCE Length}
 
3442
 
 
3443
The length of a SEQUENCE can be determined with the following function.
 
3444
 
 
3445
\index{der\_length\_sequence()}
 
3446
\begin{verbatim}
 
3447
int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
 
3448
                        unsigned long *outlen);
 
3449
\end{verbatim}
 
3450
 
 
3451
This will get the encoding size for the given ``list'' of length ``inlen'' and store it in ``outlen''.  
 
3452
 
 
3453
\subsubsection{SEQUENCE Multiple Argument Lists}
 
3454
 
 
3455
For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
 
3456
 
 
3457
\index{der\_encode\_sequence\_multi()}
 
3458
\index{der\_decode\_sequence\_multi()}
 
3459
 
 
3460
\begin{verbatim}
 
3461
int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
 
3462
int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
 
3463
\end{verbatim}
 
3464
 
 
3465
These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
 
3466
 
 
3467
The list of items are specified as a triple of the form ``(type, size, data)''  where ``type'' is an \textbf{int}, ``size'' is a \textbf{unsigned long}
 
3468
and ``data'' is \textbf{void} pointer.  The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
 
3469
 
 
3470
It's ideal that you cast the ``size'' values to unsigned long to ensure that the proper data type is passed to the function.  Constants such as ``1'' without
 
3471
a cast or prototype are of type \textbf{int} by default.  Appending \textit{UL} or prepending \textit{(unsigned long)} is enough to cast it to the correct type.
 
3472
 
 
3473
\subsection{ASN.1 INTEGER}
 
3474
 
 
3475
To encode or decode INTEGER data types use the following functions.
 
3476
 
2940
3477
\index{der\_encode\_integer()}
2941
 
\begin{alltt}
2942
 
int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
2943
 
\end{alltt}
2944
 
 
2945
 
This will store the integer in ``num'' to the output buffer ``out'' of length ``outlen''.  It only stores
2946
 
non--negative numbers.  It stores the number of octets used back in ``outlen''.
2947
 
 
2948
 
\subsection{Reading INTEGER types}
2949
3478
\index{der\_decode\_integer()}
2950
 
\begin{alltt}
2951
 
int der_decode_integer(const unsigned char *in, unsigned long *inlen, mp_int *num);
2952
 
\end{alltt}
2953
 
This will decode the DER encoded INTEGER in ``in'' of length ``inlen'' and store the resulting integer
2954
 
in ``num''.  It will store the bytes read in ``inlen'' which is handy if you have to parse multiple
2955
 
data items out of a binary packet.
2956
 
 
2957
 
\subsection{INTEGER length}
2958
3479
\index{der\_length\_integer()}
2959
 
\begin{alltt}
 
3480
\begin{verbatim}
 
3481
int der_encode_integer(mp_int *num, unsigned char *out, unsigned long *outlen);
 
3482
int der_decode_integer(const unsigned char *in, unsigned long inlen, mp_int *num);
2960
3483
int der_length_integer(mp_int *num, unsigned long *len);
2961
 
\end{alltt}
2962
 
This will determine the length of the DER encoding of the integer ``num'' and store it in ``len''.
2963
 
 
2964
 
\subsection{Multiple INTEGER types}
2965
 
To simplify the DER encoding/decoding there are two functions two handle multple types at once.
2966
 
 
2967
 
\index{der\_put\_multi\_integer()}
2968
 
\index{der\_get\_multi\_integer()}
2969
 
\begin{alltt}
2970
 
int der_put_multi_integer(unsigned char *dst, unsigned long *outlen, mp_int *num, ...);
2971
 
int der_get_multi_integer(const unsigned char *src, unsigned long *inlen,  mp_int *num, ...);
2972
 
\end{alltt}
2973
 
 
2974
 
These will handle multiple encodings/decodings at once.  They work like their single operand counterparts
2975
 
except they handle a \textbf{NULL} terminated list of operands.
2976
 
 
2977
 
\begin{verbatim}
2978
 
#include <mycrypt.h>
2979
 
int main(void)
2980
 
{
2981
 
   mp_int        a, b, c, d;
2982
 
   unsigned char buffer[1000];
2983
 
   unsigned long len;
2984
 
   int           err;
2985
 
 
2986
 
   /* init a,b,c,d with some values ... */
2987
 
 
2988
 
   /* ok we want to store them now... */
2989
 
   len = sizeof(buffer);
2990
 
   if ((err = der_put_multi_integer(buffer, &len, 
2991
 
                                    &a, &b, &c, &d, NULL)) != CRYPT_OK) {
2992
 
      // error
2993
 
   }
2994
 
   printf("I stored %lu bytes in buf\n", len);
2995
 
 
2996
 
   /* ok say we want to get them back for fun */
2997
 
   /* len set previously...otherwise set it to the size of the packet */
2998
 
   if ((err = der_get_multi_integer(buffer, &len,
2999
 
                                    &a, &b, &c, &d, NULL)) != CRYPT_OK) {
3000
 
      // error
3001
 
   }
3002
 
   printf("I read %lu bytes from buf\n", len);
3003
 
}
3004
 
\end{verbatim}
 
3484
\end{verbatim}
 
3485
 
 
3486
These will encode or decode a signed INTEGER data type using the ``mp\_int'' data type to store the large INTEGER.  To encode smaller values without allocating
 
3487
an mp\_int to store the value the ``short'' INTEGER functions were made available.
 
3488
 
 
3489
\index{der\_encode\_short\_integer()}
 
3490
\index{der\_decode\_short\_integer()}
 
3491
\index{der\_length\_short\_integer()}
 
3492
\begin{verbatim}
 
3493
int der_encode_short_integer(unsigned long  num, 
 
3494
                             unsigned char *out, unsigned long *outlen);
 
3495
 
 
3496
int der_decode_short_integer(const unsigned char *in,  unsigned long inlen, 
 
3497
                                   unsigned long *num);
 
3498
 
 
3499
int der_length_short_integer(unsigned long num, unsigned long *outlen);
 
3500
\end{verbatim}
 
3501
 
 
3502
These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits).  For values in the range $0 \dots 2^{32} - 1$ the integer 
 
3503
and short integer functions can encode and decode each others outputs.  
 
3504
 
 
3505
\subsection{ASN.1 BIT STRING}
 
3506
 
 
3507
\index{der\_encode\_bit\_string()}
 
3508
\index{der\_decode\_bit\_string()}
 
3509
\index{der\_length\_bit\_string()}
 
3510
\begin{verbatim}
 
3511
int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
 
3512
                                unsigned char *out, unsigned long *outlen);
 
3513
 
 
3514
int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
 
3515
                                unsigned char *out, unsigned long *outlen);
 
3516
 
 
3517
int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
 
3518
\end{verbatim}
 
3519
 
 
3520
These will encode or decode a BIT STRING data type.  The bits are passed in (or read out) using one \textbf{char} per bit.  A non--zero value will be interpretted
 
3521
as a one bit and a zero value a zero bit.
 
3522
 
 
3523
\subsection{ASN.1 OCTET STRING}
 
3524
 
 
3525
\index{der\_encode\_octet\_string()}
 
3526
\index{der\_decode\_octet\_string()}
 
3527
\index{der\_length\_octet\_string()}
 
3528
\begin{verbatim}
 
3529
int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
 
3530
                                  unsigned char *out, unsigned long *outlen);
 
3531
 
 
3532
int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
 
3533
                                  unsigned char *out, unsigned long *outlen);
 
3534
 
 
3535
int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
 
3536
\end{verbatim}
 
3537
 
 
3538
These will encode or decode an OCTET STRING data type.  The octets are stored using one \textbf{char} each.  
 
3539
 
 
3540
\subsection{ASN.1 OBJECT IDENTIFIER}
 
3541
 
 
3542
\index{der\_encode\_object\_identifier()}
 
3543
\index{der\_decode\_object\_identifier()}
 
3544
\index{der\_length\_object\_identifier()}
 
3545
\begin{verbatim}
 
3546
int der_encode_object_identifier(unsigned long *words, unsigned long  nwords,
 
3547
                                 unsigned char *out,   unsigned long *outlen);
 
3548
 
 
3549
int der_decode_object_identifier(const unsigned char *in,    unsigned long  inlen,
 
3550
                                       unsigned long *words, unsigned long *outlen);
 
3551
 
 
3552
int der_length_object_identifier(unsigned long *words, unsigned long nwords, 
 
3553
                                 unsigned long *outlen);
 
3554
\end{verbatim}
 
3555
 
 
3556
These will encode or decode an OBJECT IDENTIFIER object.  The words of the OID are stored in individual \textbf{unsigned long} elements and must be in the range
 
3557
$0 \ldots 2^{32} - 1$.  
 
3558
 
 
3559
\subsection{ASN.1 IA5 STRING}
 
3560
 
 
3561
\index{der\_encode\_ia5\_string()}
 
3562
\index{der\_decode\_ia5\_string()}
 
3563
\index{der\_length\_ia5\_string()}
 
3564
\begin{verbatim}
 
3565
int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
 
3566
                                unsigned char *out, unsigned long *outlen);
 
3567
 
 
3568
int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
 
3569
                                unsigned char *out, unsigned long *outlen);
 
3570
 
 
3571
int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, 
 
3572
                                unsigned long *outlen);
 
3573
\end{verbatim}
 
3574
 
 
3575
These will encode or decode an IA5 STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
 
3576
to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
 
3577
say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
 
3578
that the build platform honours the runtime platforms character conventions.
 
3579
 
 
3580
If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
 
3581
 
 
3582
\subsection{ASN.1 PRINTABLE STRING}
 
3583
 
 
3584
\index{der\_encode\_printable\_string()}
 
3585
\index{der\_decode\_printable\_string()}
 
3586
\index{der\_length\_printable\_string()}
 
3587
\begin{verbatim}
 
3588
int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
 
3589
                                unsigned char *out, unsigned long *outlen);
 
3590
 
 
3591
int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
 
3592
                                unsigned char *out, unsigned long *outlen);
 
3593
 
 
3594
int der_length_printable_string(const unsigned char *octets, unsigned long noctets, 
 
3595
                                unsigned long *outlen);
 
3596
\end{verbatim}
 
3597
 
 
3598
These will encode or decode an PRINTABLE STRING.  The characters are read or stored in individual \textbf{char} elements.  This functions performs internal character
 
3599
to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on 
 
3600
say a SPARC machine.  Internally these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
 
3601
that the build platform honours the runtime platforms character conventions.
 
3602
 
 
3603
If you're worried try building the test suite and running it.  It has hard coded test vectors to ensure it is operating properly. 
 
3604
 
 
3605
\subsection{ASN.1 UTCTIME}
 
3606
 
 
3607
The UTCTIME type is to store a date and time in ASN.1 format.  It uses the following structure to organize the time.
 
3608
 
 
3609
\begin{verbatim}
 
3610
typedef struct {
 
3611
   unsigned YY, /* year    00--99 */
 
3612
            MM, /* month   01--12 */
 
3613
            DD, /* day     01--31 */
 
3614
            hh, /* hour    00--23 */
 
3615
            mm, /* minute  00--59 */
 
3616
            ss, /* second  00--59 */
 
3617
            off_dir, /* timezone offset direction 0 == +, 1 == - */
 
3618
            off_hh, /* timezone offset hours */
 
3619
            off_mm; /* timezone offset minutes */
 
3620
} ltc_utctime;
 
3621
\end{verbatim}
 
3622
 
 
3623
The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When ``off\_dir'' is zero the time will be added otherwise it 
 
3624
will be subtracted.  
 
3625
 
 
3626
For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of 2005, June 20th, 22:04:00 with a time offset of +05h00.  
 
3627
 
 
3628
\index{der\_encode\_utctime()}
 
3629
\index{der\_decode\_utctime()}
 
3630
\index{der\_length\_utctime()}
 
3631
\begin{verbatim}
 
3632
int der_encode_utctime(ltc_utctime *utctime, 
 
3633
                       unsigned char *out,   unsigned long *outlen);
 
3634
 
 
3635
int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
 
3636
                             ltc_utctime   *out);
 
3637
 
 
3638
int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
 
3639
\end{verbatim}
 
3640
 
 
3641
The encoder will store time in one of the two ASN.1 formats, either ``YYMMDDhhmmssZ'' or ``YYMMDDhhmmss$\pm$hhmm'' and perform minimal error checking on the 
 
3642
input.  The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
 
3643
 
 
3644
It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
 
3645
 
 
3646
\subsection{ASN.1 CHOICE}
 
3647
 
 
3648
The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a ``ltc\_asn1\_list''.  There is no encoder for the CHOICE type, only a 
 
3649
decoder.  The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet.  The list can contain any ASN.1 data
 
3650
type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.  
 
3651
 
 
3652
There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.  
 
3653
 
 
3654
\index{der\_decode\_choice()}
 
3655
\begin{verbatim}
 
3656
int der_decode_choice(const unsigned char *in,   unsigned long *inlen,
 
3657
                            ltc_asn1_list *list, unsigned long  outlen);
 
3658
\end{verbatim}
 
3659
 
 
3660
This will decode the input in the ``in'' field of length ``inlen''.  It uses the provided ASN.1 list specified in the ``list'' field which has ``outlen'' elements.  
 
3661
The ``inlen'' field will be updated with the length of the decoded data type as well as the respective entry in the ``list'' field will have the ``used'' flag 
 
3662
set to non--zero to reflect it was the data type decoded.
 
3663
 
3005
3664
\section{Password Based Cryptography}
3006
3665
\subsection{PKCS \#5}
 
3666
\index{PKCS \#5}
3007
3667
In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted.   PKCS \#5
3008
3668
is made up of two algorithms, Algorithm One and Algorithm Two.  Algorithm One is the older fairly limited algorithm which has been implemented
3009
3669
for completeness.  Algorithm Two is a bit more modern and more flexible to work with.
3047
3707
 
3048
3708
\begin{alltt}
3049
3709
/* demo to show how to make session state material from a password */
3050
 
#include <mycrypt.h>
 
3710
#include <tomcrypt.h>
3051
3711
int main(void)
3052
3712
\{
3053
3713
    unsigned char password[100], salt[100],
3076
3736
\}
3077
3737
\end{alltt}
3078
3738
 
3079
 
 
3080
3739
\chapter{Miscellaneous}
3081
3740
\section{Base64 Encoding and Decoding}
3082
3741
The library provides functions to encode and decode a RFC1521 base64 coding scheme.  This means that it can decode what it 
3115
3774
At the heart of all the functions is the data type ``mp\_int'' (defined in tommath.h).  This data type is what 
3116
3775
will hold all large integers.  In order to use an mp\_int one must initialize it first, for example:
3117
3776
\begin{verbatim}
3118
 
#include <mycrypt.h> /* mycrypt.h includes mpi.h automatically */
 
3777
#include <tomcrypt.h> /* tomcrypt.h includes mpi.h automatically */
3119
3778
int main(void)
3120
3779
3121
3780
   mp_int bignum;
3274
3933
\begin{center}
3275
3934
\begin{tabular}{|c|c|}
3276
3935
    \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
3277
 
    \hline 160 & 80  \\
3278
3936
    \hline 192 & 96  \\
3279
3937
    \hline 224 & 112 \\
3280
3938
    \hline 256 & 128 \\
3327
3985
Which will build the library and install it in /usr/lib (as well as the headers in /usr/include).  The destination
3328
3986
directory of the library and headers can be changed by editing ``makefile''.  The variable LIBNAME controls
3329
3987
where the library is to be installed and INCNAME controls where the headers are to be installed.  A developer can 
3330
 
then use the library by including ``mycrypt.h'' in their program and linking against ``libtomcrypt.a''.
 
3988
then use the library by including ``tomcrypt.h'' in their program and linking against ``libtomcrypt.a''.
3331
3989
 
3332
3990
A static library can also be built with the Intel C Compiler  (ICC) by issuing the following
3333
3991
 
3368
4026
and install them into /usr/lib (and the headers into /usr/include).  To link your application you should use the 
3369
4027
libtool program in ``--mode=link''.
3370
4028
 
3371
 
You can also build LibTomCrypt as a shared library (DLL) in Windows with Cygwin.  Issue the following
3372
 
 
3373
 
\begin{alltt}
3374
 
make -f makefile.cygwin_dll
3375
 
\end{alltt}
3376
 
This will build ``libtomcrypt.dll.a'' which is an import library for ``libtomcrypt.dll''.  You must copy 
3377
 
``libtomcrypt.dll.a'' to your library directory, ``libtomcrypt.dll' to somewhere in your PATH and the header
3378
 
files to your include directory.  So long as ``libtomcrypt.dll'' is in your system path you can run any LibTomCrypt
3379
 
program that uses it.
3380
 
 
3381
 
\section{mycrypt\_cfg.h}
3382
 
The file ``mycrypt\_cfg.h'' is what lets you control various high level macros which control the behaviour 
 
4029
\section{tomcrypt\_cfg.h}
 
4030
The file ``tomcrypt\_cfg.h'' is what lets you control various high level macros which control the behaviour 
3383
4031
of the library. 
3384
4032
 
3385
4033
\subsubsection{ARGTYPE}
3398
4046
Currently LibTomCrypt will detect x86-32 and x86-64 running GCC as well as x86-32 running MSVC.  
3399
4047
 
3400
4048
\section{The Configure Script}
3401
 
There are also options you can specify from the configure script or ``mycrypt\_custom.h''.  
 
4049
There are also options you can specify from the configure script or ``tomcrypt\_custom.h''.  
3402
4050
 
3403
 
\subsubsection{X memory routines}
3404
 
At the top of mycrypt\_custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to 
 
4051
\subsection{X memory routines}
 
4052
At the top of tomcrypt\_custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to 
3405
4053
the name of the respective functions.  This lets you substitute in your own memory routines.  If you substitute in 
3406
4054
your own functions they must behave like the standard C library functions in terms of what they expect as input and 
3407
4055
output.  By default the library uses the standard C routines.
3408
4056
 
3409
 
\subsubsection{X clock routines}
 
4057
\subsection{X clock routines}
3410
4058
The rng\_get\_bytes() function can call a function that requires the clock() function.  These macros let you override
3411
4059
the default clock() used with a replacement.  By default the standard C library clock() function is used.
3412
4060
 
3413
 
\subsubsection{NO\_FILE}
 
4061
\subsection{NO\_FILE}
3414
4062
During the build if NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O 
3415
4063
functions and instead simply return CRYPT\_NOP.  This should help resolve any linker errors stemming from a lack of
3416
4064
file I/O on embedded platforms.
3417
4065
 
3418
 
\subsubsection{CLEAN\_STACK}
 
4066
\subsection{CLEAN\_STACK}
3419
4067
When this functions is defined the functions that store key material on the stack will clean up afterwards.  
3420
4068
Assumes that you have no memory paging with the stack.
3421
4069
 
3422
 
\subsubsection{LTC\_TEST}
 
4070
\subsection{LTC\_TEST}
3423
4071
When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.
3424
4072
When this has been undefined the tests are removed and if called will return CRYPT\_NOP.
3425
4073
 
3426
 
\subsubsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
 
4074
\subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
3427
4075
There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly 
3428
4076
self-explanatory.  When they are defined the functionality is included otherwise it is not.  There are some 
3429
4077
dependency issues which are noted in the file.  For instance, Yarrow requires CTR chaining mode, a block 
3430
4078
cipher and a hash function.
3431
4079
 
3432
 
\subsubsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
 
4080
\subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
3433
4081
Twofish is a 128-bit symmetric block cipher that is provided within the library.  The cipher itself is flexible enough
3434
4082
to allow some tradeoffs in the implementation.  When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish 
3435
4083
requires only 200 bytes of memory.  This is achieved by not pre-computing the substitution boxes.  Having this 
3441
4089
will increase by approximately 500 bytes.  If this is defined but TWOFISH\_SMALL is not the cipher will still work but
3442
4090
it will not speed up the encryption or decryption functions.
3443
4091
 
3444
 
\subsubsection{SMALL\_CODE}
 
4092
\subsection{GCM\_TABLES}
 
4093
When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.  
 
4094
It also increases the initialization time and isn't suitable when you are going to use a key a few times only.  
 
4095
 
 
4096
\subsection{SMALL\_CODE}
3445
4097
When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
3446
4098
These variants are slower but can save quite a bit of code space.
3447
4099
 
 
4100
\subsection{LTC\_FAST}
 
4101
This mode (autodetected with x86\_32,x86\_64 platforms with GCC or MSVC) configures various routines such as ctr\_encrypt() or 
 
4102
cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type.  This has the benefit of 
 
4103
cutting down the overhead of the respective functions.  
 
4104
 
 
4105
This mode does have one downside.  It can cause unaligned reads from memory if you are not careful with the functions.  This is why
 
4106
it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed.  Technically LTC\_FAST
 
4107
is not ``portable'' since unaligned accesses are not covered by the ISO C specifications.
 
4108
 
 
4109
In practice however, you can use it on pretty much any platform (even MIPS) with care.
 
4110
 
 
4111
By design the ``fast'' mode functions won't get unaligned on their own.  For instance, if you call ctr\_encrypt() right after calling
 
4112
ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only.  However, if you 
 
4113
call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used.  This will
 
4114
cause the ctr routine to first use up the remaining pad bytes.  Then if there are enough plaintext bytes left it will use 
 
4115
whole word XOR operations.  These operations will be unaligned.
 
4116
 
 
4117
The simplest precaution is to make sure you process all data in power of two blocks and handle ``remainder'' at the end.  e.g. If you are 
 
4118
CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.  
 
4119
 
 
4120
If you do plan on using the ``LTC\_FAST'' mode you have to also define a ``LTC\_FAST\_TYPE'' macro which resolves to an optimal sized
 
4121
data type you can perform integer operations with.  Ideally it should be four or eight bytes since it must properly divide the size 
 
4122
of your block cipher (e.g. 16 bytes for AES).  This means sadly if you're on a platform with 57--bit words (or something) you can't 
 
4123
use this mode.  So sad.
 
4124
 
 
4125
\subsection{LTC\_PTHREAD}
 
4126
When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables.  Note that 
 
4127
it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
 
4128
 
 
4129
Generally the rule of thumb is to setup the tables once at startup and then leave them be.  This added build flag simply makes updating
 
4130
the tables safer.
 
4131
 
3448
4132
\section{MPI Tweaks}
3449
4133
\subsection{RSA Only Tweak}
3450
4134
If you plan on only using RSA with moduli in the range of 1024 to 2560 bits you can enable a series of tweaks
3451
4135
to reduce the library size.  Follow these steps
3452
4136
 
3453
4137
\begin{enumerate}
3454
 
   \item Undefine MDSA, MECC and MDH from mycrypt\_custom.h
 
4138
   \item Undefine MDSA, MECC and MDH from tomcrypt\_custom.h
3455
4139
   \item Undefine LTM\_ALL  from tommath\_superclass.h
3456
4140
   \item Define SC\_RSA\_1 from tommath\_superclass.h
3457
4141
   \item Rebuild the library.
3458
4142
\end{enumerate}
3459
4143
 
3460
 
 
 
4144
\chapter{Optimizations}
 
4145
\section{Introduction}
 
4146
The entire API was designed with plug and play in mind at the low level.  That is you can swap out any cipher, hash or PRNG and dependent API will not require
 
4147
updating.  This has the nice benefit that I can add ciphers not have to re--write large portions of the API.  For the most part LibTomCrypt has also been written
 
4148
to be highly portable and easy to build out of the box on pretty much any platform.  As such there are no assembler inlines throughout the code, I make no assumptions
 
4149
about the platform, etc...
 
4150
 
 
4151
That works well for most cases but there are times where time is of the essence.  This API also allows optimized routines to be dropped in--place of the existing
 
4152
portable routines.  For instance, hand optimized assembler versions of AES could be provided and any existing function that uses the cipher could automatically use
 
4153
the optimized code without re--writing.  This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
 
4154
 
 
4155
At the heart of this flexibility is the ``descriptor'' system.  A descriptor is essentially just a C ``struct'' which describes the algorithm and provides pointers
 
4156
to functions that do the work.  For a given class of operation (e.g. cipher, hash, prng) the functions have identical prototypes which makes development simple.  In most
 
4157
dependent routines all a developer has to do is register\_XXX() the descriptor and they're set.
 
4158
 
 
4159
\section{Ciphers}
 
4160
The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
 
4161
 
 
4162
\begin{small}
 
4163
\begin{verbatim}
 
4164
struct ltc_cipher_descriptor {
 
4165
   /** name of cipher */
 
4166
   char *name;
 
4167
   /** internal ID */
 
4168
   unsigned char ID;
 
4169
   /** min keysize (octets) */
 
4170
   int  min_key_length, 
 
4171
   /** max keysize (octets) */
 
4172
        max_key_length, 
 
4173
   /** block size (octets) */
 
4174
        block_length, 
 
4175
   /** default number of rounds */
 
4176
        default_rounds;
 
4177
   /** Setup the cipher 
 
4178
      @param key         The input symmetric key
 
4179
      @param keylen      The length of the input key (octets)
 
4180
      @param num_rounds  The requested number of rounds (0==default)
 
4181
      @param skey        [out] The destination of the scheduled key
 
4182
      @return CRYPT_OK if successful
 
4183
   */
 
4184
   int  (*setup)(const unsigned char *key, int keylen, 
 
4185
                 int num_rounds, symmetric_key *skey);
 
4186
   /** Encrypt a block
 
4187
      @param pt      The plaintext
 
4188
      @param ct      [out] The ciphertext
 
4189
      @param skey    The scheduled key
 
4190
   */
 
4191
   void (*ecb_encrypt)(const unsigned char *pt, 
 
4192
                             unsigned char *ct, symmetric_key *skey);
 
4193
   /** Decrypt a block
 
4194
      @param ct      The ciphertext
 
4195
      @param pt      [out] The plaintext
 
4196
      @param skey    The scheduled key
 
4197
   */
 
4198
   void (*ecb_decrypt)(const unsigned char *ct, 
 
4199
                             unsigned char *pt, symmetric_key *skey);
 
4200
   /** Test the block cipher
 
4201
       @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
 
4202
   */
 
4203
   int (*test)(void);
 
4204
   /** Determine a key size
 
4205
       @param keysize    [in/out] The size of the key desired and the suggested size
 
4206
       @return CRYPT_OK if successful
 
4207
   */
 
4208
   int  (*keysize)(int *keysize);
 
4209
 
 
4210
/** Accelerators **/
 
4211
   /** Accelerated ECB encryption 
 
4212
       @param pt      Plaintext
 
4213
       @param ct      Ciphertext
 
4214
       @param blocks  The number of complete blocks to process
 
4215
       @param skey    The scheduled key context
 
4216
   */
 
4217
   void (*accel_ecb_encrypt)(const unsigned char *pt, 
 
4218
                                   unsigned char *ct, unsigned long blocks, 
 
4219
                             symmetric_key *skey);
 
4220
 
 
4221
   /** Accelerated ECB decryption 
 
4222
       @param pt      Plaintext
 
4223
       @param ct      Ciphertext
 
4224
       @param blocks  The number of complete blocks to process
 
4225
       @param skey    The scheduled key context
 
4226
   */
 
4227
   void (*accel_ecb_decrypt)(const unsigned char *ct, 
 
4228
                                   unsigned char *pt, unsigned long blocks, 
 
4229
                             symmetric_key *skey);
 
4230
 
 
4231
   /** Accelerated CBC encryption 
 
4232
       @param pt      Plaintext
 
4233
       @param ct      Ciphertext
 
4234
       @param blocks  The number of complete blocks to process
 
4235
       @param IV      The initial value (input/output)
 
4236
       @param skey    The scheduled key context
 
4237
   */
 
4238
   void (*accel_cbc_encrypt)(const unsigned char *pt, 
 
4239
                                   unsigned char *ct, unsigned long blocks, 
 
4240
                                   unsigned char *IV, symmetric_key *skey);
 
4241
 
 
4242
   /** Accelerated CBC decryption 
 
4243
       @param pt      Plaintext
 
4244
       @param ct      Ciphertext
 
4245
       @param blocks  The number of complete blocks to process
 
4246
       @param IV      The initial value (input/output)
 
4247
       @param skey    The scheduled key context
 
4248
   */
 
4249
   void (*accel_cbc_decrypt)(const unsigned char *ct, 
 
4250
                                   unsigned char *pt, unsigned long blocks, 
 
4251
                                   unsigned char *IV, symmetric_key *skey);
 
4252
 
 
4253
   /** Accelerated CTR encryption 
 
4254
       @param pt      Plaintext
 
4255
       @param ct      Ciphertext
 
4256
       @param blocks  The number of complete blocks to process
 
4257
       @param IV      The initial value (input/output)
 
4258
       @param mode    little or big endian counter (mode=0 or mode=1)
 
4259
       @param skey    The scheduled key context
 
4260
   */
 
4261
   void (*accel_ctr_encrypt)(const unsigned char *pt, 
 
4262
                                   unsigned char *ct, unsigned long blocks, 
 
4263
                                   unsigned char *IV, int mode, symmetric_key *skey);
 
4264
 
 
4265
   /** Accelerated CCM packet (one-shot)
 
4266
       @param key        The secret key to use
 
4267
       @param keylen     The length of the secret key (octets)
 
4268
       @param nonce      The session nonce [use once]
 
4269
       @param noncelen   The length of the nonce
 
4270
       @param header     The header for the session
 
4271
       @param headerlen  The length of the header (octets)
 
4272
       @param pt         [out] The plaintext
 
4273
       @param ptlen      The length of the plaintext (octets)
 
4274
       @param ct         [out] The ciphertext
 
4275
       @param tag        [out] The destination tag
 
4276
       @param taglen     [in/out] The max size and resulting size of the authentication tag
 
4277
       @param direction  Encrypt or Decrypt direction (0 or 1)
 
4278
       @return CRYPT_OK if successful
 
4279
   */
 
4280
   void (*accel_ccm_memory)(
 
4281
       const unsigned char *key,    unsigned long keylen,
 
4282
       const unsigned char *nonce,  unsigned long noncelen,
 
4283
       const unsigned char *header, unsigned long headerlen,
 
4284
             unsigned char *pt,     unsigned long ptlen,
 
4285
             unsigned char *ct,
 
4286
             unsigned char *tag,    unsigned long *taglen,
 
4287
                       int  direction);
 
4288
 
 
4289
   /** Accelerated GCM packet (one shot)
 
4290
       @param key               The secret key
 
4291
       @param keylen            The length of the secret key
 
4292
       @param IV                The initial vector 
 
4293
       @param IVlen             The length of the initial vector
 
4294
       @param adata             The additional authentication data (header)
 
4295
       @param adatalen          The length of the adata
 
4296
       @param pt                The plaintext
 
4297
       @param ptlen             The length of the plaintext (ciphertext length is the same)
 
4298
       @param ct                The ciphertext
 
4299
       @param tag               [out] The MAC tag
 
4300
       @param taglen            [in/out] The MAC tag length
 
4301
       @param direction         Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
 
4302
   */
 
4303
   void (*accel_gcm_memory)(
 
4304
       const unsigned char *key,    unsigned long keylen,
 
4305
       const unsigned char *IV,     unsigned long IVlen,
 
4306
       const unsigned char *adata,  unsigned long adatalen,
 
4307
             unsigned char *pt,     unsigned long ptlen,
 
4308
             unsigned char *ct, 
 
4309
             unsigned char *tag,    unsigned long *taglen,
 
4310
                       int direction);
 
4311
 
 
4312
};
 
4313
\end{verbatim}
 
4314
\end{small}
 
4315
 
 
4316
\subsection{Name}
 
4317
The ``name'' parameter specifies the name of the cipher.  This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
 
4318
tables.
 
4319
 
 
4320
\subsection{Internal ID}
 
4321
This is a single byte Internal ID you can use to distingish ciphers from each other.
 
4322
 
 
4323
\subsection{Key Lengths}
 
4324
The minimum key length is ``min\_key\_length'' and is measured in octets.  Similarly the maximum key length is ``max\_key\_length''.  They can be equal
 
4325
and both must valid key sizes for the cipher.  Values in between are not assumed to be valid though they may be.
 
4326
 
 
4327
\subsection{Block Length}
 
4328
The size of the ciphers plaintext or ciphertext is ``block\_length'' and is measured in octets.
 
4329
 
 
4330
\subsection{Rounds}
 
4331
Some ciphers allow different number of rounds to be used.  Usually you just use the default.  The default round count is ``default\_rounds''.
 
4332
 
 
4333
\subsection{Setup}
 
4334
To initialize a cipher (for ECB mode) the function setup() was provided.  It accepts an array of key octets ``key'' of length ``keylen'' octets.  The user
 
4335
can specify the number of rounds they want through ``num\_rounds'' where $num\_rounds = 0$ means use the default.  The destination of a scheduled key is stored
 
4336
in ``skey''.
 
4337
 
 
4338
Inside the ``symmetric\_key'' union there is a ``void *data'' which you can use to allocate data if you need a data structure that doesn't fit with the existing
 
4339
ones provided.  Just make sure in your ``done()'' function that you free the allocated memory.
 
4340
 
 
4341
\subsection{Single block ECB}
 
4342
To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided.  The plaintext and ciphertext buffers are allowed to overlap so you 
 
4343
must make sure you do not overwrite the output before you are finished with the input.
 
4344
 
 
4345
\subsection{Testing}
 
4346
The test() function is used to self--test the ``device''.  It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly.
 
4347
 
 
4348
\subsection{Key Sizing}
 
4349
Occasionally a function will want to find a suitable key size to use since the input is oddly sized.  The keysize() function is for this case.  It accepts a 
 
4350
pointer to an integer which represents the desired size.  The function then has to match it to the exact or a lower key size that is valid for the cipher.  For
 
4351
example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer.  It must not round up and must return an error if the keysize
 
4352
 cannot be mapped to a valid key size for the cipher.
 
4353
 
 
4354
\subsection{Acceleration}
 
4355
The next set of functions cover the accelerated functionality of the cipher descriptor.  Any combination of these functions may be set to \textbf{NULL} to indicate
 
4356
it is not supported.  In those cases the software fallbacks are used (using the single ECB block routines).
 
4357
 
 
4358
\subsubsection{Accelerated ECB}
 
4359
These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks.  These functions are accessed
 
4360
through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers.  The ``blocks'' count is the number of complete blocks to process.
 
4361
 
 
4362
\subsubsection{Accelerated CBC} 
 
4363
These two functions are meant for accelerated CBC encryption.  These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
 
4364
The ``blocks'' value is the number of complete blocks to process.  The ``IV'' is the CBC initial vector.  It is an input upon calling this function and must be
 
4365
updated by the function before returning.  
 
4366
 
 
4367
\subsubsection{Accelerated CTR}
 
4368
This function is meant for accelerated CTR encryption.  It is accessible through the accel\_ctr\_encrypt pointer.
 
4369
The ``blocks'' value is the number of complete blocks to process.  The ``IV'' is the CTR counter vector.  It is an input upon calling this function and must be
 
4370
updated by the function before returning.  The ``mode'' value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or 
 
4371
little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.
 
4372
 
 
4373
This function (and the way it's called) differs from the other two since ctr\_encrypt() allows any size input plaintext.  The accelerator will only be
 
4374
called if the following conditions are met.
 
4375
 
 
4376
\begin{enumerate}
 
4377
   \item The accelerator is present
 
4378
   \item The CTR pad is empty
 
4379
   \item The remaining length of the input to process is greater than or equal to the block size.
 
4380
\end{enumerate}
 
4381
 
 
4382
The ``CTR pad'' is empty when a multiple (including zero) blocks of text have been processed.  That is, if you pass in seven bytes to AES--CTR mode you would have to 
 
4383
pass in a minimum of nine extra bytes before the accelerator could be called.  The CTR accelerator must increment the counter (and store it back into the 
 
4384
buffer provided) before encrypting it to create the pad.  
 
4385
 
 
4386
The accelerator will only be used to encrypt whole blocks.  Partial blocks are always handled in software.
 
4387
 
 
4388
\subsubsection{Accelerated CCM}
 
4389
This function is meant for accelerated CCM encryption or decryption.  It processes the entire packet in one call.  Note that the setup() function will not
 
4390
be called prior to this.  This function must handle scheduling the key provided on its own.
 
4391
 
 
4392
\subsubsection{Accelerated GCM}
 
4393
This function is meant for accelerated GCM encryption or decryption.  It processes the entire packet in one call.  Note that the setup() function will not
 
4394
be called prior to this.  This function must handle scheduling the key provided on its own.
 
4395
 
 
4396
\section{One--Way Hashes}
 
4397
The hash functions are accessed through the ltc\_hash\_descriptor structure.
 
4398
 
 
4399
\begin{small}
 
4400
\begin{verbatim}
 
4401
struct ltc_hash_descriptor {
 
4402
    /** name of hash */
 
4403
    char *name;
 
4404
    /** internal ID */
 
4405
    unsigned char ID;
 
4406
    /** Size of digest in octets */
 
4407
    unsigned long hashsize;
 
4408
    /** Input block size in octets */
 
4409
    unsigned long blocksize;
 
4410
    /** ASN.1 OID */
 
4411
    unsigned long OID[16];
 
4412
    /** Length of DER encoding */
 
4413
    unsigned long OIDlen;
 
4414
    /** Init a hash state
 
4415
      @param hash   The hash to initialize
 
4416
      @return CRYPT_OK if successful
 
4417
    */
 
4418
    int (*init)(hash_state *hash);
 
4419
    /** Process a block of data 
 
4420
      @param hash   The hash state
 
4421
      @param in     The data to hash
 
4422
      @param inlen  The length of the data (octets)
 
4423
      @return CRYPT_OK if successful
 
4424
    */
 
4425
    int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
 
4426
    /** Produce the digest and store it
 
4427
      @param hash   The hash state
 
4428
      @param out    [out] The destination of the digest
 
4429
      @return CRYPT_OK if successful
 
4430
    */
 
4431
    int (*done)(hash_state *hash, unsigned char *out);
 
4432
    /** Self-test
 
4433
      @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
 
4434
    */
 
4435
    int (*test)(void);
 
4436
};
 
4437
\end{verbatim}
 
4438
\end{small}
 
4439
 
 
4440
\subsection{Name}
 
4441
This is the name the hash is known by and what find\_hash() will look for.
 
4442
 
 
4443
\subsection{Internal ID}
 
4444
This is the internal ID byte used to distinguish the hash from other hashes.
 
4445
 
 
4446
\subsection{Digest Size}
 
4447
The ``hashsize'' variable indicates the length of the output in octets.
 
4448
 
 
4449
\subsection{Block Size}
 
4450
The `blocksize'' variable indicates the length of input (in octets) that the hash processes in a given
 
4451
invokation.
 
4452
 
 
4453
\subsection{OID Identifier}
 
4454
This is the universal ASN.1 Object Identifier for the hash.
 
4455
 
 
4456
\subsection{Initialization}
 
4457
The init function initializes the hash and prepares it to process message bytes.
 
4458
 
 
4459
\subsection{Process}
 
4460
This processes message bytes.  The algorithm must accept any length of input that the hash would allow.  The input is not
 
4461
guaranteed to be a multiple of the block size in length.
 
4462
 
 
4463
\subsection{Done}
 
4464
The done function terminates the hash and returns the message digest.
 
4465
 
 
4466
\subsection{Acceleration}
 
4467
A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.  
 
4468
 
 
4469
\section{Pseudo--Random Number Generators}
 
4470
The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
 
4471
 
 
4472
\begin{small}
 
4473
\begin{verbatim}
 
4474
struct ltc_prng_descriptor {
 
4475
    /** Name of the PRNG */
 
4476
    char *name;
 
4477
    /** size in bytes of exported state */
 
4478
    int  export_size;
 
4479
    /** Start a PRNG state
 
4480
        @param prng   [out] The state to initialize
 
4481
        @return CRYPT_OK if successful
 
4482
    */
 
4483
    int (*start)(prng_state *prng);
 
4484
    /** Add entropy to the PRNG
 
4485
        @param in         The entropy
 
4486
        @param inlen      Length of the entropy (octets)\
 
4487
        @param prng       The PRNG state
 
4488
        @return CRYPT_OK if successful
 
4489
    */
 
4490
    int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
 
4491
    /** Ready a PRNG state to read from
 
4492
        @param prng       The PRNG state to ready
 
4493
        @return CRYPT_OK if successful
 
4494
    */
 
4495
    int (*ready)(prng_state *prng);
 
4496
    /** Read from the PRNG
 
4497
        @param out     [out] Where to store the data
 
4498
        @param outlen  Length of data desired (octets)
 
4499
        @param prng    The PRNG state to read from
 
4500
        @return Number of octets read
 
4501
    */
 
4502
    unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
 
4503
    /** Terminate a PRNG state
 
4504
        @param prng   The PRNG state to terminate
 
4505
        @return CRYPT_OK if successful
 
4506
    */
 
4507
    int (*done)(prng_state *prng);
 
4508
    /** Export a PRNG state  
 
4509
        @param out     [out] The destination for the state
 
4510
        @param outlen  [in/out] The max size and resulting size of the PRNG state
 
4511
        @param prng    The PRNG to export
 
4512
        @return CRYPT_OK if successful
 
4513
    */
 
4514
    int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
 
4515
    /** Import a PRNG state
 
4516
        @param in      The data to import
 
4517
        @param inlen   The length of the data to import (octets)
 
4518
        @param prng    The PRNG to initialize/import
 
4519
        @return CRYPT_OK if successful
 
4520
    */
 
4521
    int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
 
4522
    /** Self-test the PRNG
 
4523
        @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
 
4524
    */
 
4525
    int (*test)(void);
 
4526
};
 
4527
\end{verbatim}
 
4528
\end{small}
 
4529
 
 
4530
\subsection{Name}
 
4531
The name by which find\_prng() will find the PRNG.
 
4532
 
 
4533
\subsection{Export Size}
 
4534
When an PRNG state is to be exported for future use you specify the space required in this variable.
 
4535
 
 
4536
\subsection{Start}
 
4537
Initialize the PRNG and make it ready to accept entropy.
 
4538
 
 
4539
\subsection{Entropy Addition}
 
4540
Add entropy to the PRNG state.  The exact behaviour of this function depends on the particulars of the PRNG.
 
4541
 
 
4542
\subsection{Ready}
 
4543
This function makes the PRNG ready to read from by processing the entropy added.  The behaviour of this function depends
 
4544
on the specific PRNG used.
 
4545
 
 
4546
\subsection{Read}
 
4547
Read from the PRNG and return the number of bytes read.  This function does not have to fill the buffer but it is best 
 
4548
if it does as many protocols do not retry reads and will fail on the first try.
 
4549
 
 
4550
\subsection{Done}
 
4551
Terminate a PRNG state.  The behaviour of this function depends on the particular PRNG used.
 
4552
 
 
4553
\subsection{Exporting and Importing}
 
4554
An exported PRNG state is data that the PRNG can later import to resume activity.  They're not meant to resume ``the same session''
 
4555
but should at least maintain the same level of state entropy.
3461
4556
 
3462
4557
\input{crypt.ind}
3463
4558
 
3464
4559
\end{document}
 
4560
 
 
4561
% $Source: /cvs/libtom/libtomcrypt/crypt.tex,v $   
 
4562
% $Revision: 1.39 $   
 
4563
% $Date: 2005/06/27 13:08:28 $