2004-06-20 02:41:49 +00:00
\documentclass [a4paper] { book}
2003-06-11 21:10:22 +00:00
\usepackage { hyperref}
2003-03-03 00:59:24 +00:00
\usepackage { makeidx}
\usepackage { amssymb}
2003-03-13 02:12:16 +00:00
\usepackage { color}
\usepackage { alltt}
\usepackage { graphicx}
\usepackage { layout}
2003-03-03 00:59:24 +00:00
\def \union { \cup }
\def \intersect { \cap }
\def \getsrandom { \stackrel { \rm R} { \gets } }
\def \cross { \times }
\def \cat { \hspace { 0.5em} \| \hspace { 0.5em} }
\def \catn { $ \| $ }
\def \divides { \hspace { 0.3em} | \hspace { 0.3em} }
\def \nequiv { \not \equiv }
\def \approx { \raisebox { 0.2ex} { \mbox { \small $ \sim $ } } }
\def \lcm { { \rm lcm} }
\def \gcd { { \rm gcd} }
\def \log { { \rm log} }
\def \ord { { \rm ord} }
\def \abs { { \mathit abs} }
\def \rep { { \mathit rep} }
\def \mod { { \mathit \ mod\ } }
\renewcommand { \pmod } [1]{ \ ({ \rm mod\ } { #1} )}
\newcommand { \floor } [1]{ \left \lfloor { #1} \right \rfloor }
\newcommand { \ceil } [1]{ \left \lceil { #1} \right \rceil }
\def \Or { { \rm \ or\ } }
\def \And { { \rm \ and\ } }
\def \iff { \hspace { 1em} \Longleftrightarrow \hspace { 1em} }
\def \implies { \Rightarrow }
\def \undefined { { \rm ``undefined"} }
\def \Proof { \vspace { 1ex} \noindent { \bf Proof:} \hspace { 1em} }
\let \oldphi \phi
\def \phi { \varphi }
\def \Pr { { \rm Pr} }
\newcommand { \str } [1]{ { \mathbf { #1} } }
\def \F { { \mathbb F} }
\def \N { { \mathbb N} }
\def \Z { { \mathbb Z} }
\def \R { { \mathbb R} }
\def \C { { \mathbb C} }
\def \Q { { \mathbb Q} }
\def \twiddle { \raisebox { 0.3ex} { \mbox { \tiny $ \sim $ } } }
\def \gap { \vspace { 0.5ex} }
\makeindex
\begin { document}
2006-01-26 18:11:56 +00:00
\title { LibTomCrypt \\ Version 1.09}
2003-03-03 00:59:24 +00:00
\author { Tom St Denis \\
\\
2005-04-17 11:37:13 +00:00
tomstdenis@gmail.com \\
2004-06-20 02:41:49 +00:00
http://libtomcrypt.org
2003-03-03 00:59:24 +00:00
}
\maketitle
2003-12-24 18:59:57 +00:00
This text and source code library are both hereby placed in the public domain. This book has been
2004-06-20 02:41:49 +00:00
formatted for A4 paper using the \LaTeX { } { \em book} macro package.
2003-12-24 18:59:57 +00:00
2005-06-09 00:08:13 +00:00
\vspace { 15cm}
2003-12-24 18:59:57 +00:00
\begin { flushright} Open Source. Open Academia. Open Minds.
\mbox { }
Tom St Denis,
2004-06-20 02:41:49 +00:00
Phone: 1-613-836-3160
111 Banning Rd
Kanata, Ontario
K2L 1C3
Canada
2003-12-24 18:59:57 +00:00
\end { flushright}
2003-03-03 00:59:24 +00:00
\newpage
\tableofcontents
\chapter { Introduction}
2003-06-01 18:55:11 +00:00
\section { What is the LibTomCrypt?}
2004-12-30 23:55:53 +00:00
LibTomCrypt is a portable ISO C cryptographic library that is meant to be a toolset for cryptographers who are
designing a cryptosystem. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
public key cryptography (via PKCS \# 1 RSA, DH or ECCDH) and a plethora of support
routines.
2003-03-03 00:59:24 +00:00
2004-12-30 23:55:53 +00:00
The library was designed such that new ciphers/hashes/PRNGs can be added at runtime and the existing API
(and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
also performs extensive parameter error checking to prevent any number of runtime exploits or errors.
2003-03-03 00:59:24 +00:00
\subsection { What the library IS for?}
2004-12-30 23:55:53 +00:00
The library serves as a toolkit for developers who have to solve cryptographic problems. Out of the box LibTomCrypt
does not process SSL or OpenPGP messages, it doesn't read x.591 certificates or write PEM encoded data. It does, however,
provide all of the tools required to build such functionality. LibTomCrypt was designed to be a flexible library that
was not tied to any particular cryptographic problem.
2003-03-03 00:59:24 +00:00
\section { Why did I write it?}
You may be wondering, ``Tom, why did you write a crypto library. I already have one.''. Well the reason falls into
two categories:
\begin { enumerate}
\item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
\item It was (still is) good coding practice.
\end { enumerate}
The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
{ \bf own} crypto library and hopefully along the way others will appreciate the work.
With this library all core functions (ciphers, hashes, prngs) have the { \bf exact} same prototype definition. They all load
and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
2004-12-30 23:55:53 +00:00
on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with my library you
2003-03-03 00:59:24 +00:00
know how to use Safer+ or RC6 or Serpent or ... as well. With all of the core functions there are central descriptor tables
that can be used to make a program automatically pick between ciphers, hashes and PRNGs at runtime. That means your
application can support all ciphers/hashes/prngs without changing the source code.
2004-12-30 23:55:53 +00:00
Not only did I strive to make a consistent and simple API to work with but I also strived to make the library
configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
without having to use configure scripts. This means that the library will work with platforms where development
tools may be limited (e.g. no autoconf).
On top of making the build simple and the API approachable I've also strived for a reasonably high level of
robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
with ``cycles per byte'' timings that are comparable (and often favourable) to other libraries such as OpenSSL and
Crypto++.
2003-03-13 02:12:16 +00:00
\subsection { Modular}
2004-12-30 23:55:53 +00:00
The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes and
pseudo--random number generators (PRNG) are all used within the API through ``descriptor'' tables which
2003-03-13 02:12:16 +00:00
are essentially structures with pointers to functions. While you can still call particular functions
directly (\textit { e.g. sha256\_ process()} ) this descriptor interface allows the developer to customize their
usage of the library.
For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
2004-12-30 23:55:53 +00:00
that for the PRNG needs within the library (\textit { e.g. making a RSA key} ). All the developer has to do
2003-03-13 02:12:16 +00:00
is write a descriptor and the few support routines required for the device. After that the rest of the
2004-12-30 23:55:53 +00:00
API can make use of it without change. Similiarly imagine a few years down the road when AES2
(\textit { or whatever they call it} ) has been invented. It can be added to the library and used within applications
with zero modifications to the end applications provided they are written properly.
2003-03-13 02:12:16 +00:00
This flexibility within the library means it can be used with any combination of primitive algorithms and
unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
mode routines for every single cipher. That means every time you add or remove a cipher from the library
you have to update the associated support code as well. In LibTomCrypt the associated code (\textit { chaining modes in this case} )
are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
can make use of the cipher right away.
2003-03-03 00:59:24 +00:00
\section { License}
All of the source code except for the following files have been written by the author or donated to the project
2003-09-08 01:06:11 +00:00
under a public domain license:
2003-03-03 00:59:24 +00:00
\begin { enumerate}
\item rc2.c
\end { enumerate}
2004-12-30 23:55:53 +00:00
`mpi.c'' was originally written by Michael Fromberger (sting@linguist.dartmouth.edu) but has since been replaced with
my LibTomMath library which is public domain.
2003-09-08 01:06:11 +00:00
2005-04-17 11:37:13 +00:00
``rc2.c'' is based on publicly available code that is not attributed to a person from the given source.
2003-03-03 00:59:24 +00:00
2003-09-08 01:06:11 +00:00
The project is hereby released as public domain.
2003-03-03 00:59:24 +00:00
\section { Patent Disclosure}
The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
of the authors knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
2005-04-19 11:30:30 +00:00
They can be removed from a build by simply commenting out the two appropriate lines in ``tomcrypt\_ custom.h''. The rest
2003-03-03 00:59:24 +00:00
of the ciphers and hashes are patent free or under patents that have since expired.
The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
the ciphers you just can't advertise that you are doing so.
\section { Thanks}
2004-06-20 02:41:49 +00:00
I would like to give thanks to the following people (in no particular order) for helping me develop this project from
early on:
2003-03-03 00:59:24 +00:00
\begin { enumerate}
\item Richard van de Laarschot
\item Richard Heathfield
\item Ajay K. Agrawal
\item Brian Gladman
\item Svante Seleborg
\item Clay Culver
\item Jason Klapste
\item Dobes Vandermeer
\item Daniel Richards
\item Wayne Scott
\item Andrew Tyler
\item Sky Schulz
2003-03-03 01:02:10 +00:00
\item Christopher Imes
2003-03-03 00:59:24 +00:00
\end { enumerate}
2004-06-20 02:41:49 +00:00
There have been quite a few other people as well. Please check the change log to see who else has contributed from
time to time.
2003-03-03 00:59:24 +00:00
\chapter { The Application Programming Interface (API)}
\section { Introduction}
\index { CRYPT\_ ERROR} \index { CRYPT\_ OK}
In general the API is very simple to memorize and use. Most of the functions return either { \bf void} or { \bf int} . Functions
that return { \bf int} will return { \bf CRYPT\_ OK} if the function was successful or one of the many error codes
if it failed. Certain functions that return int will return $ - 1 $ to indicate an error. These functions will be explicitly
commented upon. When a function does return a CRYPT error code it can be translated into a string with
2004-05-31 02:36:47 +00:00
\index { error\_ to\_ string()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-05-31 02:36:47 +00:00
const char *error_ to_ string(int err);
2003-03-03 00:59:24 +00:00
\end { verbatim}
An example of handling an error is:
\begin { verbatim}
void somefunc(void)
{
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* call a cryptographic function */
2004-05-31 02:36:47 +00:00
if ((err = some_ crypto_ function(...)) != CRYPT_ OK) {
printf("A crypto error occured, %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
/* perform error handling */
}
/* continue on if no error occured */
}
\end { verbatim}
There is no initialization routine for the library and for the most part the code is thread safe. The only thread
related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
that is not an issue.
2004-12-30 23:55:53 +00:00
To include the prototypes for ``LibTomCrypt.a'' into your own program simply include ``tomcrypt.h'' like so:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void) {
return 0;
}
\end { verbatim}
2005-11-18 05:15:37 +00:00
The header file ``tomcrypt.h'' also includes ``stdio.h'', ``string.h'', ``stdlib.h'', ``time.h'' and ``ctype.h''.
2003-03-03 00:59:24 +00:00
\section { Macros}
There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
32/64-bit words in little/big endian format. The macros are:
2005-04-17 11:37:13 +00:00
\index { STORE32L} \index { STORE64L} \index { LOAD32L} \index { LOAD64L} \index { STORE32H} \index { STORE64H} \index { LOAD32H} \index { LOAD64H} \index { BSWAP}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |c|c|c|}
\hline STORE32L(x, y) & { \bf unsigned long} x, { \bf unsigned char} *y & $ x \to y [ 0 \ldots 3 ] $ \\
\hline STORE64L(x, y) & { \bf unsigned long long} x, { \bf unsigned char} *y & $ x \to y [ 0 \ldots 7 ] $ \\
\hline LOAD32L(x, y) & { \bf unsigned long} x, { \bf unsigned char} *y & $ y [ 0 \ldots 3 ] \to x $ \\
\hline LOAD64L(x, y) & { \bf unsigned long long} x, { \bf unsigned char} *y & $ y [ 0 \ldots 7 ] \to x $ \\
\hline STORE32H(x, y) & { \bf unsigned long} x, { \bf unsigned char} *y & $ x \to y [ 3 \ldots 0 ] $ \\
\hline STORE64H(x, y) & { \bf unsigned long long} x, { \bf unsigned char} *y & $ x \to y [ 7 \ldots 0 ] $ \\
\hline LOAD32H(x, y) & { \bf unsigned long} x, { \bf unsigned char} *y & $ y [ 3 \ldots 0 ] \to x $ \\
\hline LOAD64H(x, y) & { \bf unsigned long long} x, { \bf unsigned char} *y & $ y [ 7 \ldots 0 ] \to x $ \\
2005-04-17 11:37:13 +00:00
\hline BSWAP(x) & { \bf unsigned long} x & Swaps byte order (32--bits only) \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\end { small}
2004-12-30 23:55:53 +00:00
There are 32 and 64-bit cyclic rotations as well:
2005-04-17 11:37:13 +00:00
\index { ROL} \index { ROR} \index { ROL64} \index { ROR64} \index { ROLc} \index { RORc} \index { ROL64c} \index { ROR64c}
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|c|}
2004-12-30 23:55:53 +00:00
\hline ROL(x, y) & { \bf unsigned long} x, { \bf unsigned long} y & $ x << y, 0 \le y \le 31 $ \\
\hline ROLc(x, y) & { \bf unsigned long} x, { \bf const unsigned long} y & $ x << y, 0 \le y \le 31 $ \\
\hline ROR(x, y) & { \bf unsigned long} x, { \bf unsigned long} y & $ x >> y, 0 \le y \le 31 $ \\
\hline RORc(x, y) & { \bf unsigned long} x, { \bf const unsigned long} y & $ x >> y, 0 \le y \le 31 $ \\
\hline & & \\
\hline ROL64(x, y) & { \bf unsigned long} x, { \bf unsigned long} y & $ x << y, 0 \le y \le 63 $ \\
\hline ROL64c(x, y) & { \bf unsigned long} x, { \bf const unsigned long} y & $ x << y, 0 \le y \le 63 $ \\
\hline ROR64(x, y) & { \bf unsigned long} x, { \bf unsigned long} y & $ x >> y, 0 \le y \le 63 $ \\
\hline ROR64c(x, y) & { \bf unsigned long} x, { \bf const unsigned long} y & $ x >> y, 0 \le y \le 63 $ \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\section { Functions with Variable Length Output}
Certain functions such as (for example) ``rsa\_ export()'' give an output that is variable length. To prevent buffer overflows you
must pass it the length of the buffer\footnote { Extensive error checking is not in place but it will be in future releases so it is a good idea to follow through with these guidelines.} where
the output will be stored. For example:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void) {
rsa_ key key;
unsigned char buffer[1024];
unsigned long x;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
/* ... Make up the RSA key somehow ... */
2003-03-03 00:59:24 +00:00
/* lets export the key, set x to the size of the output buffer */
x = sizeof(buffer);
2004-05-31 02:36:47 +00:00
if ((err = rsa_ export(buffer, & x, PK_ PUBLIC, & key)) != CRYPT_ OK) {
printf("Export error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* if rsa_ export() was successful then x will have the size of the output */
printf("RSA exported key takes %d bytes\n", x);
/* ... do something with the buffer */
return 0;
}
\end { verbatim}
\end { small}
2004-12-30 23:55:53 +00:00
In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
indicating a buffer overflow would have occurred. If the function succeeds it stores the length of the output
back into ``x'' so that the calling application will know how many bytes were used.
2003-03-03 00:59:24 +00:00
\section { Functions that need a PRNG}
2004-12-30 23:55:53 +00:00
\index { Pseudo Random Number Generator} \index { PRNG}
Certain functions such as ``rsa\_ make\_ key()'' require a Pseudo Random Number Generator (PRNG). These functions do not setup
the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
Certain PRNG algorithms do not require a ``prng\_ state'' argument (sprng for example). The ``prng\_ state'' argument
may be passed as \textbf { NULL} in such situations.
2003-03-03 00:59:24 +00:00
\section { Functions that use Arrays of Octets}
Most functions require inputs that are arrays of the data type ``unsigned char''. Whether it is a symmetric key, IV
for a chaining mode or public key packet it is assumed that regardless of the actual size of ``unsigned char'' only the
lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine
you must pass it in (a pointer to) an array of 32 ``unsigned char'' variables. Certain routines
(such as SAFER+) take special care to work properly on platforms where an ``unsigned char'' is not eight bits.
For the purposes of this library the term ``byte'' will refer to an octet or eight bit word. Typically an array of
type ``byte'' will be synonymous with an array of type ``unsigned char''.
\chapter { Symmetric Block Ciphers}
\section { Core Functions}
2004-12-30 23:55:53 +00:00
LibTomCrypt provides several block ciphers with an ECB block mode interface. It's important to first note that you
2003-03-03 00:59:24 +00:00
should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode
or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
the API to grow in a modular fashion.
2005-04-17 11:37:13 +00:00
\subsection { Key Scheduling}
2003-03-03 00:59:24 +00:00
All ciphers store their scheduled keys in a single data type called ``symmetric\_ key''. This allows all ciphers to
2004-12-30 23:55:53 +00:00
have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
allocation and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers provide five visible
functions which are (given that XXX is the name of the cipher):
2003-03-03 00:59:24 +00:00
\index { Cipher Setup}
\begin { verbatim}
2003-09-08 01:06:11 +00:00
int XXX_ setup(const unsigned char *key, int keylen, int rounds,
2003-03-03 00:59:24 +00:00
symmetric_ key *skey);
\end { verbatim}
The XXX\_ setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
The number of rounds can be set to zero to use the default, which is generally a good idea.
2004-12-30 23:55:53 +00:00
If the function returns successfully the variable ``skey'' will have a scheduled key stored in it. It's important to note
that you should only used this scheduled key with the intended cipher. For example, if you call ``blowfish\_ setup()'' do not
pass the scheduled key onto ``rc5\_ ecb\_ encrypt()''. All setup functions do not allocate memory off the heap so when you are
done with a key you can simply discard it (e.g. they can be on the stack).
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { ECB Encryption and Decryption}
2004-12-30 23:55:53 +00:00
To encrypt or decrypt a block in ECB mode there are these two function classes
2003-03-03 00:59:24 +00:00
\index { Cipher Encrypt} \index { Cipher Decrypt}
\begin { verbatim}
2005-11-18 05:15:37 +00:00
int XXX_ ecb_ encrypt(const unsigned char *pt, unsigned char *ct,
2003-03-03 00:59:24 +00:00
symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int XXX_ ecb_ decrypt(const unsigned char *ct, unsigned char *pt,
2003-03-03 00:59:24 +00:00
symmetric_ key *skey);
\end { verbatim}
These two functions will encrypt or decrypt (respectively) a single block of text\footnote { The size of which depends on
which cipher you are using.} and store the result where you want it. It is possible that the input and output buffer are
2004-12-30 23:55:53 +00:00
the same buffer. For the encrypt function ``pt''\footnote { pt stands for plaintext.} is the input and
2005-11-18 05:15:37 +00:00
``ct''\footnote { ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
return \textbf { CRYPT\_ OK} on success. To test a particular
2004-12-30 23:55:53 +00:00
cipher against test vectors\footnote { As published in their design papers.} call the self-test function
2005-04-17 11:37:13 +00:00
\subsection { Self--Testing}
2004-12-30 23:55:53 +00:00
\index { Cipher Testing}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
This function will return { \bf CRYPT\_ OK} if the cipher matches the test vectors from the design publication it is
2005-04-17 11:37:13 +00:00
based upon.
\subsection { Key Sizing}
For each cipher there is a function which will help find a desired key size:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ keysize(int *keysize);
\end { verbatim}
Essentially it will round the input keysize in ``keysize'' down to the next appropriate key size. This function
return { \bf CRYPT\_ OK} if the key size specified is acceptable. For example:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int keysize, err;
2003-03-03 00:59:24 +00:00
/* now given a 20 byte key what keysize does Twofish want to use? */
keysize = 20;
2004-05-31 02:36:47 +00:00
if ((err = twofish_ keysize(& keysize)) != CRYPT_ OK) {
printf("Error getting key size: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
printf("Twofish suggested a key size of %d\n", keysize);
return 0;
}
\end { verbatim}
\end { small}
2004-12-30 23:55:53 +00:00
This should indicate a keysize of sixteen bytes is suggested.
2005-04-17 11:37:13 +00:00
\subsection { Cipher Termination}
When you are finished with a cipher you can de--initialize it with the done function.
\begin { verbatim}
void XXX_ done(symmetric_ key *skey);
\end { verbatim}
For the software based ciphers within LibTomCrypt this function will not do anything. However, user supplied
cipher descriptors may require calls to it for resource management. To be compliant all functions which call a cipher
setup function must also call the respective cipher done function when finished.
2004-12-30 23:55:53 +00:00
\subsection { Simple Encryption Demonstration}
An example snippet that encodes a block with Blowfish in ECB mode is below.
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char pt[8], ct[8], key[8];
symmetric_ key skey;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* ... key is loaded appropriately in ``key'' ... */
/* ... load a block of plaintext in ``pt'' ... */
/* schedule the key */
2004-05-31 02:36:47 +00:00
if ((err = blowfish_ setup(key, /* the key we will use */
8, /* key is 8 bytes (64-bits) long */
0, /* 0 == use default # of rounds */
& skey) /* where to put the scheduled key */
) != CRYPT_ OK) {
printf("Setup error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* encrypt the block */
2004-05-31 02:36:47 +00:00
blowfish_ ecb_ encrypt(pt, /* encrypt this 8-byte array */
ct, /* store encrypted data here */
& skey); /* our previously scheduled key */
2004-12-30 23:55:53 +00:00
/* now ct holds the encrypted version of pt */
2003-03-03 00:59:24 +00:00
/* decrypt the block */
2004-05-31 02:36:47 +00:00
blowfish_ ecb_ decrypt(ct, /* decrypt this 8-byte array */
pt, /* store decrypted data here */
& skey); /* our previously scheduled key */
2003-03-03 00:59:24 +00:00
2004-12-30 23:55:53 +00:00
/* now we have decrypted ct to the original plaintext in pt */
2005-04-17 11:37:13 +00:00
/* Terminate the cipher context */
blowfish_ done(& skey);
2003-03-03 00:59:24 +00:00
return 0;
}
\end { verbatim}
\end { small}
\section { Key Sizes and Number of Rounds}
\index { Symmetric Keys}
As a general rule of thumb do not use symmetric keys under 80 bits if you can. Only a few of the ciphers support smaller
keys (mainly for test vectors anyways). Ideally your application should be making at least 256 bit keys. This is not
2004-12-30 23:55:53 +00:00
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
2003-03-03 00:59:24 +00:00
example, if you have $ \mbox { Pr } \left [ X = 1 \right ] = { 1 \over 2 } \pm \gamma $ where $ \vert \gamma \vert > 0 $ then the
total amount of entropy in N bits is $ N \cdot - log _ 2 \left ( { 1 \over 2 } + \vert \gamma \vert \right ) $ . So if $ \gamma $
were $ 0 . 25 $ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
only 53 bits of entropy.
The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
2004-12-30 23:55:53 +00:00
ciphers are configured such that the default number of rounds provide adequate security for the given block and key
size.
2003-03-03 00:59:24 +00:00
\section { The Cipher Descriptors}
\index { Cipher Descriptor}
To facilitate automatic routines an array of cipher descriptors is provided in the array ``cipher\_ descriptor''. An element
of this array has the following format:
2005-04-17 11:37:13 +00:00
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
struct _ cipher_ descriptor {
char *name;
2004-12-30 23:55:53 +00:00
unsigned char ID;
int min_ key_ length,
max_ key_ length,
block_ length,
default_ rounds;
2005-04-17 11:37:13 +00:00
int (*setup)(const unsigned char *key, int keylen, int num_ rounds, symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*ecb_ encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_ key *skey);
int (*ecb_ decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_ key *skey);
int (*test)(void);
2005-04-17 11:37:13 +00:00
void (*done)(symmetric_ key *skey);
2004-12-30 23:55:53 +00:00
int (*keysize)(int *keysize);
2005-04-17 11:37:13 +00:00
2005-11-18 05:15:37 +00:00
int (*accel_ ecb_ encrypt)(const unsigned char *pt,
2005-04-17 11:37:13 +00:00
unsigned char *ct,
unsigned long blocks, symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*accel_ ecb_ decrypt)(const unsigned char *ct,
2005-04-17 11:37:13 +00:00
unsigned char *pt,
unsigned long blocks, symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*accel_ cbc_ encrypt)(const unsigned char *pt,
2005-04-17 11:37:13 +00:00
unsigned char *ct,
unsigned long blocks, unsigned char *IV,
symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*accel_ cbc_ decrypt)(const unsigned char *ct,
2005-04-17 11:37:13 +00:00
unsigned char *pt,
unsigned long blocks, unsigned char *IV,
symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*accel_ ctr_ encrypt)(const unsigned char *pt,
2005-04-17 11:37:13 +00:00
unsigned char *ct,
unsigned long blocks, unsigned char *IV,
int mode, symmetric_ key *skey);
2006-01-26 18:11:56 +00:00
int (*accel_ lrw_ encrypt)(const unsigned char *pt,
unsigned char *ct,
unsigned long blocks,
unsigned char *IV,
const unsigned char *tweak,
symmetric_ key *skey);
int (*accel_ lrw_ decrypt)(const unsigned char *ct,
unsigned char *pt,
unsigned long blocks,
unsigned char *IV,
const unsigned char *tweak,
symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
int (*accel_ ccm_ memory)(
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
2005-11-18 05:15:37 +00:00
symmetric_ key *uskey,
2005-04-17 11:37:13 +00:00
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
2005-11-18 05:15:37 +00:00
int (*accel_ gcm_ memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
2003-03-03 00:59:24 +00:00
} ;
\end { verbatim}
2005-04-17 11:37:13 +00:00
\end { small}
2003-03-03 00:59:24 +00:00
2004-12-30 23:55:53 +00:00
Where ``name'' is the lower case ASCII version of the name. The fields ``min\_ key\_ length'' and ``max\_ key\_ length''
are the minimum and maximum key sizes in bytes. The ``block\_ length'' member is the block size of the cipher
in bytes. As a good rule of thumb it is assumed that the cipher supports
2003-03-03 00:59:24 +00:00
the min and max key lengths but not always everything in between. The ``default\_ rounds'' field is the default number
of rounds that will be used.
The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_ descriptor array is
marked when ``name'' equals { \bf NULL} .
As of this release the current cipher\_ descriptors elements are
2004-05-31 02:36:47 +00:00
\index { Cipher descriptor table}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |c|c|c|c|c|c|}
2003-12-24 18:59:57 +00:00
\hline Name & Descriptor Name & Block Size & Key Range & Rounds \\
2004-05-12 20:42:16 +00:00
\hline Blowfish & blowfish\_ desc & 8 & 8 $ \ldots $ 56 & 16 \\
2003-03-03 00:59:24 +00:00
\hline X-Tea & xtea\_ desc & 8 & 16 & 32 \\
2004-05-12 20:42:16 +00:00
\hline RC2 & rc2\_ desc & 8 & 8 $ \ldots $ 128 & 16 \\
\hline RC5-32/12/b & rc5\_ desc & 8 & 8 $ \ldots $ 128 & 12 $ \ldots $ 24 \\
\hline RC6-32/20/b & rc6\_ desc & 16 & 8 $ \ldots $ 128 & 20 \\
2003-03-03 00:59:24 +00:00
\hline SAFER+ & saferp\_ desc & 16 & 16, 24, 32 & 8, 12, 16 \\
2003-03-03 01:01:40 +00:00
\hline AES & aes\_ desc & 16 & 16, 24, 32 & 10, 12, 14 \\
2004-05-31 02:36:47 +00:00
& aes\_ enc\_ desc & 16 & 16, 24, 32 & 10, 12, 14 \\
2003-03-03 00:59:24 +00:00
\hline Twofish & twofish\_ desc & 16 & 16, 24, 32 & 16 \\
\hline DES & des\_ desc & 8 & 7 & 16 \\
\hline 3DES (EDE mode) & des3\_ desc & 8 & 21 & 16 \\
2004-05-12 20:42:16 +00:00
\hline CAST5 (CAST-128) & cast5\_ desc & 8 & 5 $ \ldots $ 16 & 12, 16 \\
2003-03-03 01:01:40 +00:00
\hline Noekeon & noekeon\_ desc & 16 & 16 & 16 \\
2003-12-24 18:59:57 +00:00
\hline Skipjack & skipjack\_ desc & 8 & 10 & 32 \\
2004-12-30 23:55:53 +00:00
\hline Anubis & anubis\_ desc & 16 & 16 $ \ldots $ 40 & 12 $ \ldots $ 18 \\
\hline Khazad & khazad\_ desc & 8 & 16 & 8 \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\end { small}
\subsection { Notes}
2004-05-31 02:36:47 +00:00
\begin { small}
\begin { enumerate}
\item
For AES (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
rijndael\_ desc and rijndael\_ enc\_ desc provide the cipher named ``rijndael''. The descriptors aes\_ desc and
aes\_ enc\_ desc provide the cipher name ``aes''. Functionally both ``rijndael'' and ``aes'' are the same cipher. The
only difference is when you call find\_ cipher() you have to pass the correct name. The cipher descriptors with ``enc''
in the middle (e.g. rijndael\_ enc\_ desc) are related to an implementation of Rijndael with only the encryption routine
and tables. The decryption and self--test function pointers of both ``encrypt only'' descriptors are set to \textbf { NULL} and
should not be called.
The ``encrypt only'' descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
as EAX, PMAC and OMAC only require the encryption function. So far this ``encrypt only'' functionality has only been implemented for
Rijndael as it makes the most sense for this cipher.
\item
2003-03-03 00:59:24 +00:00
Note that for ``DES'' and ``3DES'' they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
fact used for the purposes of encryption. My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
byte string from the real 7/21 byte key.
2004-05-31 02:36:47 +00:00
\item
2003-03-03 00:59:24 +00:00
Note that ``Twofish'' has additional configuration options that take place at build time. These options are found in
2005-04-19 11:30:30 +00:00
the file ``tomcrypt\_ cfg.h''. The first option is ``TWOFISH\_ SMALL'' which when defined will force the Twofish code
2003-03-03 00:59:24 +00:00
to not pre-compute the Twofish ``$ g ( X ) $ '' function as a set of four $ 8 \times 32 $ s-boxes. This means that a scheduled
key will require less ram but the resulting cipher will be slower. The second option is ``TWOFISH\_ TABLES'' which when
defined will force the Twofish code to use pre-computed tables for the two s-boxes $ q _ 0 , q _ 1 $ as well as the multiplication
by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
speed increase is useful when ``TWOFISH\_ SMALL'' is defined since the s-boxes and MDS multiply form the heart of the
Twofish round function.
2004-05-31 02:36:47 +00:00
\index { Twofish build options}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |l|l|l|}
\hline TWOFISH\_ SMALL & TWOFISH\_ TABLES & Speed and Memory (per key) \\
\hline undefined & undefined & Very fast, 4.2KB of ram. \\
2004-06-20 02:41:49 +00:00
\hline undefined & defined & Faster keysetup, larger code. \\
2003-03-03 00:59:24 +00:00
\hline defined & undefined & Very slow, 0.2KB of ram. \\
2004-06-20 02:41:49 +00:00
\hline defined & defined & Faster, 0.2KB of ram, larger code. \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\end { small}
2004-05-31 02:36:47 +00:00
\end { enumerate}
\end { small}
2003-03-03 00:59:24 +00:00
To work with the cipher\_ descriptor array there is a function:
2004-05-31 02:36:47 +00:00
\index { find\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int find_ cipher(char *name)
\end { verbatim}
Which will search for a given name in the array. It returns negative one if the cipher is not found, otherwise it returns
the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char key[8];
symmetric_ key skey;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* you must register a cipher before you use it */
if (register_ cipher(& blowfish_ desc)) == -1) {
printf("Unable to register Blowfish cipher.");
return -1;
}
/* generic call to function (assuming the key in key[] was already setup) */
2004-06-20 02:41:49 +00:00
if ((err = cipher_ descriptor[find_ cipher("blowfish")].setup(key, 8, 0, & skey)) !=
CRYPT_ OK) {
2004-05-31 02:36:47 +00:00
printf("Error setting up Blowfish: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* ... use cipher ... */
}
\end { verbatim}
\end { small}
A good safety would be to check the return value of ``find\_ cipher()'' before accessing the desired function. In order
to use a cipher with the descriptor table you must register it first using:
2004-05-31 02:36:47 +00:00
\index { register\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int register_ cipher(const struct _ cipher_ descriptor *cipher);
\end { verbatim}
Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
as there is no more room (it can have 32 ciphers at most) it will return { \bf { -1} } . If you try to add the same cipher more
than once it will just return the index of the first copy. To remove a cipher call:
2004-05-31 02:36:47 +00:00
\index { unregister\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int unregister_ cipher(const struct _ cipher_ descriptor *cipher);
\end { verbatim}
Which returns { \bf CRYPT\_ OK} if it removes it otherwise it returns { \bf CRYPT\_ ERROR} . Consider:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* register the cipher */
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael\n ");
return -1;
}
/* use Rijndael */
/* remove it */
2004-05-31 02:36:47 +00:00
if ((err = unregister_ cipher(& rijndael_ desc)) != CRYPT_ OK) {
printf("Error removing Rijndael: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
2004-05-12 20:42:16 +00:00
This snippet is a small program that registers only Rijndael only.
2003-03-03 00:59:24 +00:00
\section { Symmetric Modes of Operations}
\subsection { Background}
A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
size of the cipher. Given a key $ k $ , a plaintext $ P $ and a cipher $ E $ we shall denote the encryption of the block
$ P $ under the key $ k $ as $ E _ k ( P ) $ . In some modes there exists an initial vector denoted as $ C _ { - 1 } $ .
\subsubsection { ECB Mode}
2004-05-31 02:36:47 +00:00
\index { ECB mode}
2003-03-03 00:59:24 +00:00
ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
\begin { equation}
C_ i = E_ k(P_ i)
\end { equation}
This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
than once.
\subsubsection { CBC Mode}
2004-05-31 02:36:47 +00:00
\index { CBC mode}
2003-03-03 00:59:24 +00:00
CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
It is given as:
\begin { equation}
C_ i = E_ k(P_ i \oplus C_ { i - 1} )
\end { equation}
It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
\subsubsection { CTR Mode}
2004-05-31 02:36:47 +00:00
\index { CTR mode}
2003-03-03 00:59:24 +00:00
CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
treated as a large binary counter the CTR mode is given as:
\begin { eqnarray}
C_ { -1} = C_ { -1} + 1\mbox { } (\mbox { mod } 2^ W) \nonumber \\
C_ i = P_ i \oplus E_ k(C_ { -1} )
\end { eqnarray}
Where $ W $ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initial vector is random for each message
encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
\subsubsection { CFB Mode}
2004-05-31 02:36:47 +00:00
\index { CFB mode}
2003-03-03 00:59:24 +00:00
CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
\begin { eqnarray}
C_ i = P_ i \oplus C_ { -1} \nonumber \\
C_ { -1} = E_ k(C_ i)
\end { eqnarray}
Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
\subsubsection { OFB Mode}
2004-05-31 02:36:47 +00:00
\index { OFB mode}
2003-03-03 00:59:24 +00:00
OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
\begin { eqnarray}
C_ { -1} = E_ k(C_ { -1} ) \nonumber \\
C_ i = P_ i \oplus C_ { -1}
\end { eqnarray}
Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
\subsection { Choice of Mode}
My personal preference is for the CTR mode since it has several key benefits:
\begin { enumerate}
\item No short cycles which is possible in the OFB and CFB modes.
\item Provably as secure as the block cipher being used under a chosen plaintext attack.
\item Technically does not require the decryption routine of the cipher.
\item Allows random access to the plaintext.
\item Allows the encryption of block sizes that are not equal to the size of the block cipher.
\end { enumerate}
The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
block of memory with either of the three modes.
The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore they are less flexible than the
other modes.
2005-04-17 11:37:13 +00:00
\subsection { Initialization}
2003-03-03 00:59:24 +00:00
\index { CBC Mode} \index { CTR Mode}
\index { OFB Mode} \index { CFB Mode}
The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
you want is XXX there is a structure called ``symmetric\_ XXX'' that will contain the information required to
2005-06-09 00:08:13 +00:00
use that mode. They have identical setup routines (except CTR and ECB mode):
2004-05-31 02:36:47 +00:00
\index { ecb\_ start()} \index { cfb\_ start()} \index { cbc\_ start()} \index { ofb\_ start()} \index { ctr\_ start()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ start(int cipher, const unsigned char *IV,
const unsigned char *key, int keylen,
int num_ rounds, symmetric_ XXX *XXX);
2005-06-09 00:08:13 +00:00
int ctr_ start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
int num_ rounds, int ctr_ mode,
symmetric_ CTR *ctr);
2003-03-03 00:59:24 +00:00
int ecb_ start(int cipher, const unsigned char *key, int keylen,
int num_ rounds, symmetric_ ECB *ecb);
\end { verbatim}
In each case ``cipher'' is the index into the cipher\_ descriptor array of the cipher you want to use. The ``IV'' value is
the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
length as the block size\footnote { In otherwords the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
parameters ``key'', ``keylen'' and ``num\_ rounds'' are the same as in the XXX\_ setup() function call. The final parameter
is a pointer to the structure you want to hold the information for the mode of operation.
2005-06-09 00:08:13 +00:00
In the case of CTR mode there is an additional parameter ``ctr\_ mode'' which specifies the mode that the counter is to be used in.
If \textbf { CTR\_ COUNTER\_ LITTLE\_ ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
\textbf { CTR\_ COUNTER\_ BIG\_ ENDIAN} was specified the counter will be treated as a big endian value.
The routines return { \bf CRYPT\_ OK} if the cipher initialized correctly, otherwise they return an error code.
2005-04-17 11:37:13 +00:00
\subsection { Encryption and Decryption}
To actually encrypt or decrypt the following routines are provided:
2004-05-31 02:36:47 +00:00
\index { ecb\_ encrypt()} \index { ecb\_ decrypt()} \index { cfb\_ encrypt()} \index { cfb\_ decrypt()}
\index { cbc\_ encrypt()} \index { cbc\_ decrypt()} \index { ofb\_ encrypt()} \index { ofb\_ decrypt()} \index { ctr\_ encrypt()} \index { ctr\_ decrypt()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ encrypt(const unsigned char *pt, unsigned char *ct,
unsigned long len, symmetric_ YYY *YYY);
2005-04-17 11:37:13 +00:00
int XXX_ decrypt(const unsigned char *ct, unsigned char *pt,
2003-03-03 00:59:24 +00:00
unsigned long len, symmetric_ YYY *YYY);
\end { verbatim}
2005-04-17 11:37:13 +00:00
Where ``XXX'' is one of $ \lbrace ecb, cbc, ctr, cfb, ofb \rbrace $ .
In all cases ``len'' is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
2003-03-03 00:59:24 +00:00
chunk sensitive. That is you can encrypt ``ABCDEF'' in three calls like ``AB'', ``CD'', ``EF'' or two like ``ABCDE'' and ``F''
and end up with the same ciphertext. However, encrypting ``ABC'' and ``DABC'' will result in different ciphertexts. All
2003-03-03 01:01:40 +00:00
five of the modes will return { \bf CRYPT\_ OK} on success from the encrypt or decrypt functions.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
In the ECB and CBC cases ``len'' must be a multiple of the ciphers block size. In the CBC case you must manually pad the end of your message (either with
zeroes or with whatever your protocol requires).
2003-03-03 00:59:24 +00:00
To decrypt in either mode you simply perform the setup like before (recall you have to fetch the IV value you used)
2004-05-31 02:36:47 +00:00
and use the decrypt routine on all of the blocks.
2005-04-17 11:37:13 +00:00
\subsection { IV Manipulation}
2004-05-31 02:36:47 +00:00
To change or read the IV of a previously initialized chaining mode use the following two functions.
\index { cbc\_ setiv()} \index { cbc\_ getiv()} \index { ofb\_ setiv()} \index { ofb\_ getiv()} \index { cfb\_ setiv()} \index { cfb\_ getiv()}
\index { ctr\_ setiv()} \index { ctr\_ getiv()}
\begin { verbatim}
int XXX_ getiv(unsigned char *IV, unsigned long *len, symmetric_ XXX *XXX);
int XXX_ setiv(const unsigned char *IV, unsigned long len, symmetric_ XXX *XXX);
\end { verbatim}
2005-04-17 11:37:13 +00:00
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
2004-05-31 02:36:47 +00:00
stored in ``len''. The XXX\_ setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
of the IV passed in must be the size of the ciphers block size.
2005-04-17 11:37:13 +00:00
The XXX\_ setiv() functions are handy if you wish to change the IV without re--keying the cipher.
\subsection { Stream Termination}
To terminate an open stream call the done function.
\index { ecb\_ done()} \index { cbc\_ done()} \index { cfb\_ done()} \index { ofb\_ done()} \index { ctr\_ done()}
\begin { verbatim}
int XXX_ done(symmetric_ XXX *XXX);
\end { verbatim}
This will terminate the stream (by terminating the cipher) and return \textbf { CRYPT\_ OK} if successful.
\subsection { Examples}
2004-05-31 02:36:47 +00:00
2003-03-03 00:59:24 +00:00
\newpage
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char key[16], IV[16], buffer[512];
symmetric_ CTR ctr;
2004-05-31 02:36:47 +00:00
int x, err;
2003-03-03 00:59:24 +00:00
/* register twofish first */
if (register_ cipher(& twofish_ desc) == -1) {
printf("Error registering cipher.\n ");
return -1;
}
/* somehow fill out key and IV */
/* start up CTR mode */
2004-06-20 02:41:49 +00:00
if ((err = ctr_ start(
find_ cipher("twofish"), /* index of desired cipher */
IV, /* the initial vector */
key, /* the secret key */
16, /* length of secret key (16 bytes, 128 bits) */
0, /* 0 == default # of rounds */
2005-06-09 00:08:13 +00:00
CTR_ COUNTER_ LITTLE_ ENDIAN, /* Little endian counter */
2004-06-20 02:41:49 +00:00
& ctr) /* where to store initialized CTR state */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("ctr_ start error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* somehow fill buffer than encrypt it */
2004-05-31 02:36:47 +00:00
if ((err = ctr_ encrypt( buffer, /* plaintext */
buffer, /* ciphertext */
sizeof(buffer), /* length of data to encrypt */
& ctr) /* previously initialized CTR state */
) != CRYPT_ OK) {
printf("ctr_ encrypt error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* make use of ciphertext... */
2004-05-31 02:36:47 +00:00
/* now we want to decrypt so let's use ctr_ setiv */
if ((err = ctr_ setiv( IV, /* the initial IV we gave to ctr_ start */
16, /* the IV is 16 bytes long */
& ctr) /* the ctr state we wish to modify */
) != CRYPT_ OK) {
printf("ctr_ setiv error: %s\n", error_to_string(err));
return -1;
}
if ((err = ctr_ decrypt( buffer, /* ciphertext */
buffer, /* plaintext */
sizeof(buffer), /* length of data to encrypt */
& ctr) /* previously initialized CTR state */
) != CRYPT_ OK) {
printf("ctr_ decrypt error: %s\n", error_to_string(err));
return -1;
}
2005-04-17 11:37:13 +00:00
/* terminate the stream */
if ((err = ctr_ done(& ctr)) != CRYPT_ OK) {
printf("ctr_ done error: %s\n", error_to_string(err));
return -1;
}
2003-03-03 00:59:24 +00:00
/* clear up and return */
zeromem(key, sizeof(key));
zeromem(& ctr, sizeof(ctr));
return 0;
}
\end { verbatim}
\end { small}
2006-01-26 18:11:56 +00:00
\subsection { LRW Mode}
LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media. It is meant to have efficient seeking and overcome the
security problems of ECB mode while not increasing the storage requirements. It is used much like any other chaining mode except with two key differences.
The key is specified as two strings the first key $ K _ 1 $ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long). The second key
$ K _ 2 $ is the ``tweak'' key and is always 16 octets long. The tweak value is \textbf { NOT} a nonce or IV value it must be random and secret.
To initialize LRW mode use:
\index { lrw\_ start()}
\begin { verbatim}
int lrw_ start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
const unsigned char *tweak,
int num_ rounds,
symmetric_ LRW *lrw);
\end { verbatim}
This will initialize the LRW context with the given (16 octet) ``IV'', cipher $ K _ 1 $ ``key'' of length ``keylen'' octets and the (16 octet) $ K _ 2 $ ``tweak''.
While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by ``cipher''. The
number of rounds for the block cipher ``num\_ rounds'' can be 0 to use the default number of rounds for the given cipher.
To process data use the following functions:
\index { lrw\_ encrypt()} \index { lrw\_ decrypt()}
\begin { verbatim}
int lrw_ encrypt(const unsigned char *pt, unsigned char *ct,
unsigned long len, symmetric_ LRW *lrw);
int lrw_ decrypt(const unsigned char *ct, unsigned char *pt,
unsigned long len, symmetric_ LRW *lrw);
\end { verbatim}
These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa). The length is specified by ``len'' in octets but must be a multiple
of 16.
To manipulate the IV use the following functions:
\index { lrw\_ getiv()} \index { lrw\_ setiv()}
\begin { verbatim}
int lrw_ getiv(unsigned char *IV, unsigned long *len, symmetric_ LRW *lrw);
int lrw_ setiv(const unsigned char *IV, unsigned long len, symmetric_ LRW *lrw);
\end { verbatim}
These will get or set the 16--octet IV. Note that setting the IV is the same as ``seeking'' and unlike other modes is not a free operation. It requires
updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
To terminate the LRW state use the following:
\index { lrw\_ done()}
\begin { verbatim}
int lrw_ done(symmetric_ LRW *lrw);
\end { verbatim}
2004-01-25 17:40:34 +00:00
\section { Encrypt and Authenticate Modes}
\subsection { EAX Mode}
LibTomCrypt provides support for a mode called EAX\footnote { See
M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the
2004-05-31 02:36:47 +00:00
way it was intended to be used by the designers. First a short description of what EAX mode is before I explain how to use it.
EAX is a mode that requires a cipher, CTR and OMAC support and provides encryption and authentication\footnote { Note that since EAX only requires OMAC and CTR you may use ``encrypt only'' cipher descriptors with this mode.} .
It is initialized with a random ``nonce'' that can be shared publicly as well as a ``header'' which can be fixed and public as well as a random
secret symmetric key.
2004-01-25 17:40:34 +00:00
The ``header'' data is meant to be meta-data associated with a stream that isn't private (e.g. protocol messages). It can
be added at anytime during an EAX stream and is part of the authentication tag. That is, changes in the meta-data can
2004-05-31 02:36:47 +00:00
be detected by changes in the output tag.
2004-01-25 17:40:34 +00:00
The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
called a ``tag'' is only emitted when the message is finished. In the interim though the user can process any arbitrary
sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
of operation.
The mode is initialized with the following function.
2004-05-31 02:36:47 +00:00
\index { eax\_ init()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ init(eax_ state *eax, int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen);
\end { verbatim}
Where ``eax'' is the EAX state. ``cipher'' is the index of the desired cipher in the descriptor table.
``key'' is the shared secret symmetric key of length ``keylen''. ``nonce'' is the random public string of
length ``noncelen''. ``header'' is the random (or fixed or \textbf { NULL} ) header for the message of length
``headerlen''.
When this function completes ``eax'' will be initialized such that you can now either have data decrypted or
2004-05-31 02:36:47 +00:00
encrypted in EAX mode. Note that if ``headerlen'' is zero you may pass ``header'' as \textbf { NULL} to indicate
there is no initial header data.
2004-01-25 17:40:34 +00:00
To encrypt or decrypt data in a streaming mode use the following.
2004-05-31 02:36:47 +00:00
\index { eax\_ encrypt()} \index { eax\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ encrypt(eax_ state *eax, const unsigned char *pt,
unsigned char *ct, unsigned long length);
int eax_ decrypt(eax_ state *eax, const unsigned char *ct,
unsigned char *pt, unsigned long length);
\end { verbatim}
The function ``eax\_ encrypt'' will encrypt the bytes in ``pt'' of ``length'' bytes and store the ciphertext in
``ct''. Note that ``ct'' and ``pt'' may be the same region in memory. This function will also send the ciphertext
through the OMAC function. The function ``eax\_ decrypt'' decrypts ``ct'' and stores it in ``pt''. This also allows
``pt'' and ``ct'' to be the same region in memory.
2004-05-31 02:36:47 +00:00
You cannot both encrypt or decrypt with the same ``eax'' context. For bi-directional communication you
will need to initialize two EAX contexts (preferably with different headers and nonces).
2004-01-25 17:40:34 +00:00
Note that both of these functions allow you to send the data in any granularity but the order is important. While
the eax\_ init() function allows you to add initial header data to the stream you can also add header data during the
EAX stream with the following.
2004-05-31 02:36:47 +00:00
\index { eax\_ addheader()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ addheader(eax_ state *eax,
const unsigned char *header, unsigned long length);
\end { verbatim}
This will add the ``length'' bytes from ``header'' to the given ``eax'' stream. Once the message is finished the
``tag'' (checksum) may be computed with the following function.
2004-05-31 02:36:47 +00:00
\index { eax\_ done()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ done(eax_ state *eax,
unsigned char *tag, unsigned long *taglen);
\end { verbatim}
This will terminate the EAX state ``eax'' and store upto ``taglen'' bytes of the message tag in ``tag''. The function
then stores how many bytes of the tag were written out back into ``taglen''.
The EAX mode code can be tested to ensure it matches the test vectors by calling the following function.
2004-05-31 02:36:47 +00:00
\index { eax\_ test()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ test(void);
\end { verbatim}
This requires that the AES (or Rijndael) block cipher be registered with the cipher\_ descriptor table first.
2004-05-31 02:36:47 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-05-31 02:36:47 +00:00
int main(void)
{
int err;
eax_ state eax;
unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
unsigned long taglen;
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael");
return EXIT_ FAILURE;
}
/* ... make up random nonce and key ... */
/* initialize context */
if ((err = eax_ init( & eax, /* the context */
find_ cipher("rijndael"), /* cipher we want to use */
nonce, /* our state nonce */
16, /* none is 16 bytes */
"TestApp", /* example header, identifies this program */
7) /* length of the header */
) != CRYPT_ OK) {
printf("Error eax_ init: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* now encrypt data, say in a loop or whatever */
if ((err = eax_ encrypt( & eax, /* eax context */
pt, /* plaintext (source) */
ct, /* ciphertext (destination) */
sizeof(pt) /* size of plaintext */
) != CRYPT_ OK) {
printf("Error eax_ encrypt: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* finish message and get authentication tag */
taglen = sizeof(tag);
if ((err = eax_ done( & eax, /* eax context */
tag, /* where to put tag */
& taglen /* length of tag space */
) != CRYPT_ OK) {
printf("Error eax_ done: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* now we have the authentication tag in "tag" and it's taglen bytes long */
}
\end { verbatim}
You can also perform an entire EAX state on a block of memory in a single function call with the
following functions.
\index { eax\_ encrypt\_ authenticate\_ memory} \index { eax\_ decrypt\_ verify\_ memory}
\begin { verbatim}
int eax_ encrypt_ authenticate_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int eax_ decrypt_ verify_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
unsigned char *tag, unsigned long taglen,
int *res);
\end { verbatim}
Both essentially just call eax\_ init() followed by eax\_ encrypt() (or eax\_ decrypt() respectively) and eax\_ done(). The parameters
have the same meaning as with those respective functions.
The only difference is eax\_ decrypt\_ verify\_ memory() does not emit a tag. Instead you pass it a tag as input and it compares it against
the tag it computed while decrypting the message. If the tags match then it stores a $ 1 $ in ``res'', otherwise it stores a $ 0 $ .
2004-01-25 17:40:34 +00:00
\subsection { OCB Mode}
LibTomCrypt provides support for a mode called OCB\footnote { See
P. Rogaway, M. Bellare, J. Black, T. Krovetz, ``OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption''.}
2004-05-31 02:36:47 +00:00
. OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
2004-01-25 17:40:34 +00:00
but is less flexible. Let's review how to initialize an OCB context.
2004-05-31 02:36:47 +00:00
\index { ocb\_ init()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ init(ocb_ state *ocb, int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce);
\end { verbatim}
This will initialize the ``ocb'' context using cipher descriptor ``cipher''. It will use a ``key'' of length ``keylen''
and the random ``nonce''. Note that ``nonce'' must be a random (public) string the same length as the block ciphers
2004-05-31 02:36:47 +00:00
block size (e.g. 16 bytes for AES).
2004-01-25 17:40:34 +00:00
This mode has no ``Associated Data'' like EAX mode does which means you cannot authenticate metadata along with the stream.
To encrypt or decrypt data use the following.
2004-05-31 02:36:47 +00:00
\index { ocb\_ encrypt()} \index { ocb\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ encrypt(ocb_ state *ocb, const unsigned char *pt, unsigned char *ct);
int ocb_ decrypt(ocb_ state *ocb, const unsigned char *ct, unsigned char *pt);
\end { verbatim}
This will encrypt (or decrypt for the latter) a fixed length of data from ``pt'' to ``ct'' (vice versa for the latter).
They assume that ``pt'' and ``ct'' are the same size as the block cipher's block size. Note that you cannot call
both functions given a single ``ocb'' state. For bi-directional communication you will have to initialize two ``ocb''
2004-05-12 20:42:16 +00:00
states (with different nonces). Also ``pt'' and ``ct'' may point to the same location in memory.
2004-01-25 17:40:34 +00:00
2005-04-17 11:37:13 +00:00
\subsubsection { State Termination}
2004-01-25 17:40:34 +00:00
When you are finished encrypting the message you call the following function to compute the tag.
2004-05-31 02:36:47 +00:00
\index { ocb\_ done\_ encrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ done_ encrypt(ocb_ state *ocb,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
\end { verbatim}
This will terminate an encrypt stream ``ocb''. If you have trailing bytes of plaintext that will not complete a block
you can pass them here. This will also encrypt the ``ptlen'' bytes in ``pt'' and store them in ``ct''. It will also
store upto ``taglen'' bytes of the tag into ``tag''.
Note that ``ptlen'' must be less than or equal to the block size of block cipher chosen. Also note that if you have
an input message equal to the length of the block size then you pass the data here (not to ocb\_ encrypt()) only.
To terminate a decrypt stream and compared the tag you call the following.
2004-05-31 02:36:47 +00:00
\index { ocb\_ done\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ done_ decrypt(ocb_ state *ocb,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
2004-02-20 20:03:32 +00:00
const unsigned char *tag, unsigned long taglen,
int *res);
2004-01-25 17:40:34 +00:00
\end { verbatim}
Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
tag of the message (internally) and then compare it against the ``taglen'' bytes of ``tag'' provided. By default
``res'' is set to zero. If all ``taglen'' bytes of ``tag'' can be verified then ``res'' is set to one (authenticated
message).
2005-04-17 11:37:13 +00:00
\subsubsection { Packet Functions}
2004-01-25 17:40:34 +00:00
To make life simpler the following two functions are provided for memory bound OCB.
2004-05-31 02:36:47 +00:00
\index { ocb\_ encrypt\_ authenticate\_ memory()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ encrypt_ authenticate_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
\end { verbatim}
This will OCB encrypt the message ``pt'' of length ``ptlen'' and store the ciphertext in ``ct''. The length ``ptlen''
can be any arbitrary length.
2004-05-31 02:36:47 +00:00
\index { ocb\_ decrypt\_ verify\_ memory()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int ocb_ decrypt_ verify_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *res);
\end { verbatim}
Similarly this will OCB decrypt and compare the internally computed tag against the tag provided. ``res'' is set
appropriately.
2005-04-17 11:37:13 +00:00
\subsection { CCM Mode}
CCM is a NIST proposal for Encrypt+Authenticate that is centered around using AES (or any 16--byte cipher) as a primitive. Unlike EAX and OCB mode
it is only meant for ``packet'' mode where the length of the input is known in advance. Since it is a packet mode function CCM only has one
function that performs the protocol.
\index { ccm\_ memory()}
\begin { verbatim}
int ccm_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
2005-11-18 05:15:37 +00:00
symmetric_ key *uskey,
2005-04-17 11:37:13 +00:00
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
\end { verbatim}
This performs the ``CCM'' operation on the data. The ``cipher'' variable indicates which cipher in the descriptor table to use. It must have a
2005-11-18 05:15:37 +00:00
16--byte block size for CCM.
The key can be specified in one of two fashions. First it can be passed as an array of octets in ``key'' of length ``keylen''. Alternatively,
it can be passed in as a previously scheduled key in ``uskey''. The latter fashion saves time when the same key is used for multiple packets. If
``uskey'' is not \textbf { NULL} then ``key'' may be \textbf { NULL} (and vice-versa).
The nonce or salt is ``nonce'' of length ``noncelen'' octets. The header is meta--data you want to send with the message but not have
encrypted, it is stored in ``header'' of length ``headerlen'' octets. The header can be zero octets long (if $ headerlen = 0 $ then
you can pass ``header'' as \textbf { NULL} ).
2005-04-17 11:37:13 +00:00
The plaintext is stored in ``pt'' and the ciphertext in ``ct''. The length of both are expected to be equal and is passed in as ``ptlen''. It is
allowable that $ pt = ct $ . The ``direction'' variable indicates whether encryption (direction $ = $ \textbf { CCM\_ ENCRYPT} ) or
decryption (direction $ = $ \textbf { CCM\_ DECRYPT} ) is to be performed.
As implemented this copy of CCM cannot handle a header or plaintext longer than $ 2 ^ { 32 } - 1 $ octets long.
You can test the implementation of CCM with the following function.
\index { ccm\_ test()}
\begin { verbatim}
int ccm_ test(void);
\end { verbatim}
This will return \textbf { CRYPT\_ OK} if the CCM routine passes known test vectors.
\subsection { GCM Mode}
Galois counter mode is an IEEE proposal for authenticated encryption. Like EAX and OCB it can be used in a streaming capacity however, unlike EAX it cannot
accept ``additional authentication data'' (meta--data) after plaintext has been processed. This mode also only works with block ciphers with a sixteen
byte block.
A GCM stream is meant to be processed in three modes each one sequential serial. First the initial vector (per session) data is processed. This should be
unique to every session. Next the the optional additional authentication data is processed and finally the plaintext.
\subsubsection { Initialization}
To initialize the GCM context with a secret key call the following function.
\index { gcm\_ init()}
\begin { verbatim}
int gcm_ init(gcm_ state *gcm, int cipher,
const unsigned char *key, int keylen);
\end { verbatim}
This initializes the GCM state ``gcm'' for the given cipher indexed by ``cipher'' with a secret key ``key'' of length ``keylen'' octets. The cipher chosen
must have a 16--byte block size (e.g. AES).
\subsubsection { Initial Vector}
After the state has been initialized (or reset) the next step is to add the session (or packet) initial vector. It should be unique per packet encrypted.
\index { gcm\_ add\_ iv()}
\begin { verbatim}
int gcm_ add_ iv(gcm_ state *gcm,
const unsigned char *IV, unsigned long IVlen);
\end { verbatim}
This adds the initial vector octets from ``IV'' of length ``IVlen'' to the GCM state ``gcm''. You can call this function as many times as required
to process the entire IV.
Note that the GCM protocols provides a ``shortcut'' for 12--byte IVs where no preprocessing is to be done. If you want to minimize per packet latency it's ideal
to only use 12--byte IVs. You can just increment it like a counter for each packet and the CTR [privacy] will be ensured.
\subsubsection { Additional Authentication Data}
After the entire IV has been processed the additional authentication data can be processed. Unlike the IV a packet/session does not require additional
authentication data (AAD) for security. The AAD is meant to be used as side--channel data you want to be authenticated with the packet. Note that once
you begin adding AAD to the GCM state you cannot return to adding IV data until the state is reset.
\index { gcm\_ add\_ aad()}
\begin { verbatim}
int gcm_ add_ aad(gcm_ state *gcm,
const unsigned char *adata, unsigned long adatalen);
\end { verbatim}
This adds the additional authentication data ``adata'' of length ``adatalen'' to the GCM state ``gcm''.
\subsubsection { Plaintext Processing}
After the AAD has been processed the plaintext (or ciphertext depending on the direction) can be processed.
\index { gcm\_ process()}
\begin { verbatim}
int gcm_ process(gcm_ state *gcm,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
int direction);
\end { verbatim}
This processes message data where ``pt'' is the plaintext and ``ct'' is the ciphertext. The length of both are equal and stored in ``ptlen''. Depending on the
mode ``pt'' is the input and ``ct'' is the output (or vice versa). When ``direction'' equals \textbf { GCM\_ ENCRYPT} the plaintext is read, encrypted and stored
in the ciphertext buffer. When ``direction'' equals \textbf { GCM\_ DECRYPT} the opposite occurs.
\subsubsection { State Termination}
To terminate a GCM state and retrieve the message authentication tag call the following function.
\index { gcm\_ done()}
\begin { verbatim}
int gcm_ done(gcm_ state *gcm,
unsigned char *tag, unsigned long *taglen);
\end { verbatim}
This terminates the GCM state ``gcm'' and stores the tag in ``tag'' of length ``taglen'' octets.
\subsubsection { State Reset}
The call to gcm\_ init() will perform considerable pre--computation (when \textbf { GCM\_ TABLES} is defined) and if you're going to be dealing with a lot of packets
it is very costly to have to call it repeatedly. To aid in this endeavour the reset function has been provided.
\index { gcm\_ reset()}
\begin { verbatim}
int gcm_ reset(gcm_ state *gcm);
\end { verbatim}
This will reset the GCM state ``gcm'' to the state that gcm\_ init() left it. The user would then call gcm\_ add\_ iv(), gcm\_ add\_ aad(), etc.
\subsubsection { One--Shot Packet}
To process a single packet under any given key the following helper function can be used.
\index { gcm\_ memory()}
\begin { verbatim}
int gcm_ memory( int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
\end { verbatim}
This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
message tag. The definition of the variables is the same as it is for all the manual functions.
If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
\subsubsection { Example Usage}
The following is an example usage of how to use GCM over multiple packets with a shared secret key.
\begin { small}
\begin { verbatim}
#include <tomcrypt.h>
int send_ packet(const unsigned char *pt, unsigned long ptlen,
const unsigned char *iv, unsigned long ivlen,
const unsigned char *aad, unsigned long aadlen,
gcm_ state *gcm)
{
int err;
unsigned long taglen;
unsigned char tag[16];
/* reset the state */
if ((err = gcm_ reset(gcm)) != CRYPT_ OK) {
return err;
}
/* Add the IV */
if ((err = gcm_ add_ iv(gcm, iv, ivlen)) != CRYPT_ OK) {
return err;
}
/* Add the AAD (note: aad can be NULL if aadlen == 0) */
if ((err = gcm_ add_ aad(gcm, aad, aadlen)) != CRYPT_ OK) {
return err;
}
/* process the plaintext */
2005-06-09 00:08:13 +00:00
if ((err = gcm_ process(gcm, pt, ptlen, pt, GCM_ ENCRYPT)) != CRYPT_ OK) {
2005-04-17 11:37:13 +00:00
return err;
}
/* Finish up and get the MAC tag */
taglen = sizeof(tag);
if ((err = gcm_ done(gcm, tag, & taglen)) != CRYPT_ OK) {
return err;
}
2005-06-09 00:08:13 +00:00
/* ... send a header describing the lengths ... */
2005-04-17 11:37:13 +00:00
/* depending on the protocol and how IV is generated you may have to send it too... */
send(socket, iv, ivlen, 0);
/* send the aad */
send(socket, aad, aadlen, 0);
/* send the ciphertext */
send(socket, pt, ptlen, 0);
/* send the tag */
send(socket, tag, taglen, 0);
return CRYPT_ OK;
}
int main(void)
{
gcm_ state gcm;
unsigned char key[16], IV[12], pt[PACKET_ SIZE];
int err, x;
unsigned long ptlen;
/* somehow fill key/IV with random values */
/* register AES */
register_ cipher(& aes_ desc);
/* init the GCM state */
if ((err = gcm_ init(& gcm, find_ cipher("aes"), key, 16)) != CRYPT_ OK) {
whine_ and_ pout(err);
}
/* handle us some packets */
for (;;) {
ptlen = make_ packet_ we_ want_ to_ send(pt);
/* use IV as counter (12 byte counter) */
for (x = 11; x >= 0; x--) {
if (++IV[x]) {
break;
}
}
if ((err = send_ packet(pt, ptlen, iv, 12, NULL, 0, & gcm)) != CRYPT_ OK) {
whine_ and_ pout(err);
}
}
return EXIT_ SUCCESS;
}
\end { verbatim}
\end { small}
2003-03-03 00:59:24 +00:00
\chapter { One-Way Cryptographic Hash Functions}
\section { Core Functions}
Like the ciphers there are hash core functions and a universal data type to hold the hash state called ``hash\_ state''.
To initialize hash XXX (where XXX is the name) call:
\index { Hash Functions}
\begin { verbatim}
void XXX_ init(hash_ state *md);
\end { verbatim}
This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the
message being hashed call:
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int XXX_ process(hash_ state *md, const unsigned char *in, unsigned long inlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
Essentially all hash messages are virtually infinitely\footnote { Most hashes are limited to $ 2 ^ { 64 } $ bits or 2,305,843,009,213,693,952 bytes.} long message which
are buffered. The data can be passed in any sized chunks as long as the order of the bytes are the same the message digest
(hash output) will be the same. For example, this means that:
\begin { verbatim}
md5_ process(& md, "hello ", 6);
md5_ process(& md, "world", 5);
\end { verbatim}
Will produce the same message digest as the single call:
\index { Message Digest}
\begin { verbatim}
md5_ process(& md, "hello world", 11);
\end { verbatim}
To finally get the message digest (the hash) call:
\begin { verbatim}
2003-12-24 18:59:57 +00:00
int XXX_ done(hash_ state *md,
2003-03-03 00:59:24 +00:00
unsigned char *out);
\end { verbatim}
This function will finish up the hash and store the result in the ``out'' array. You must ensure that ``out'' is long
enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the ``XXX\_ done()'' functions
will wipe the ``md'' variable before returning automatically.
To test a hash function call:
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
This will return { \bf CRYPTO\_ OK} if the hash matches the test vectors, otherwise it returns an error code. An
example snippet that hashes a message with md5 is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
hash_ state md;
unsigned char *in = "hello world", out[16];
/* setup the hash */
md5_ init(& md);
/* add the message */
md5_ process(& md, in, strlen(in));
2003-03-13 02:12:16 +00:00
/* get the hash in out[0..15] */
2003-03-03 00:59:24 +00:00
md5_ done(& md, out);
return 0;
}
\end { verbatim}
\end { small}
\section { Hash Descriptors}
Like the set of ciphers the set of hashes have descriptors too. They are stored in an array called ``hash\_ descriptor'' and
are defined by:
\begin { verbatim}
struct _ hash_ descriptor {
char *name;
unsigned long hashsize; /* digest output size in bytes */
unsigned long blocksize; /* the block size the hash uses */
2004-12-30 23:55:53 +00:00
void (*init) (hash_ state *hash);
int (*process)(hash_ state *hash,
const unsigned char *in, unsigned long inlen);
int (*done) (hash_ state *hash, unsigned char *out);
2003-03-03 00:59:24 +00:00
int (*test) (void);
} ;
\end { verbatim}
2005-08-01 16:36:47 +00:00
\index { find\_ hash()}
2003-03-03 00:59:24 +00:00
Similarly ``name'' is the name of the hash function in ASCII (all lowercase). ``hashsize'' is the size of the digest output
in bytes. The remaining fields are pointers to the functions that do the respective tasks. There is a function to
search the array as well called ``int find\_ hash(char *name)''. It returns -1 if the hash is not found, otherwise the
position in the descriptor table of the hash.
2005-08-01 16:36:47 +00:00
In addition to find\_ hash() there is also find\_ hash\_ oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
\index { find\_ hash\_ oid()}
\begin { verbatim}
int find_ hash_ oid(const unsigned long *ID, unsigned long IDlen);
\end { verbatim}
2003-03-03 00:59:24 +00:00
You can use the table to indirectly call a hash function that is chosen at runtime. For example:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char buffer[100], hash[MAXBLOCKSIZE];
int idx, x;
hash_ state md;
/* register hashes .... */
if (register_ hash(& md5_ desc) == -1) {
printf("Error registering MD5.\n ");
return -1;
}
/* register other hashes ... */
/* prompt for name and strip newline */
printf("Enter hash name: \n ");
fgets(buffer, sizeof(buffer), stdin);
buffer[strlen(buffer) - 1] = 0;
/* get hash index */
idx = find_ hash(buffer);
if (idx == -1) {
printf("Invalid hash name!\n ");
return -1;
}
/* hash input until blank line */
hash_ descriptor[idx].init(& md);
while (fgets(buffer, sizeof(buffer), stdin) != NULL)
hash_ descriptor[idx].process(& md, buffer, strlen(buffer));
hash_ descriptor[idx].done(& md, hash);
/* dump to screen */
for (x = 0; x < hash_ descriptor[idx].hashsize; x++)
printf("%02x ", hash[x]);
printf("\n ");
return 0;
}
\end { verbatim}
\end { small}
Note the usage of ``MAXBLOCKSIZE''. In Libtomcrypt no symmetric block, key or hash digest is larger than MAXBLOCKSIZE in
length. This provides a simple size you can set your automatic arrays to that will not get overrun.
There are three helper functions as well:
\index { hash\_ memory()} \index { hash\_ file()}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int hash_ memory(int hash,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
int hash_ file(int hash, const char *fname,
2004-12-30 23:55:53 +00:00
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
int hash_ filehandle(int hash, FILE *in,
2004-12-30 23:55:53 +00:00
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2003-06-01 18:55:11 +00:00
The ``hash'' parameter is the location in the descriptor table of the hash (\textit { e.g. the return of find\_ hash()} ).
2004-12-30 23:55:53 +00:00
The ``*outlen'' variable is used to keep track of the output size. You must set it to the size of your output buffer before
calling the functions. When they complete succesfully they store the length of the message digest back in it. The functions
are otherwise straightforward. The ``hash\_ filehandle'' function assumes that ``in'' is an file handle opened in binary mode.
It will hash to the end of file and not reset the file position when finished.
2003-03-03 00:59:24 +00:00
To perform the above hash with md5 the following code could be used:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int idx, err;
2003-03-03 00:59:24 +00:00
unsigned long len;
unsigned char out[MAXBLOCKSIZE];
/* register the hash */
if (register_ hash(& md5_ desc) == -1) {
printf("Error registering MD5.\n ");
return -1;
}
/* get the index of the hash */
idx = find_ hash("md5");
/* call the hash */
len = sizeof(out);
2004-05-31 02:36:47 +00:00
if ((err = hash_ memory(idx, "hello world", 11, out, & len)) != CRYPT_ OK) {
printf("Error hashing data: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
The following hashes are provided as of this release:
2004-05-31 02:36:47 +00:00
\index { Hash descriptor table}
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|c|}
\hline Name & Descriptor Name & Size of Message Digest (bytes) \\
2004-02-20 20:03:32 +00:00
\hline WHIRLPOOL & whirlpool\_ desc & 64 \\
2003-03-03 00:59:24 +00:00
\hline SHA-512 & sha512\_ desc & 64 \\
\hline SHA-384 & sha384\_ desc & 48 \\
\hline SHA-256 & sha256\_ desc & 32 \\
2003-12-24 18:59:57 +00:00
\hline SHA-224 & sha224\_ desc & 28 \\
2003-03-03 00:59:24 +00:00
\hline TIGER-192 & tiger\_ desc & 24 \\
\hline SHA-1 & sha1\_ desc & 20 \\
2003-09-08 01:06:11 +00:00
\hline RIPEMD-160 & rmd160\_ desc & 20 \\
\hline RIPEMD-128 & rmd128\_ desc & 16 \\
2003-03-03 00:59:24 +00:00
\hline MD5 & md5\_ desc & 16 \\
\hline MD4 & md4\_ desc & 16 \\
\hline MD2 & md2\_ desc & 16 \\
\hline
\end { tabular}
\end { center}
Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
work exactly like those of the cipher registration code. The functions are:
2004-05-31 02:36:47 +00:00
\index { register\_ hash()} \index { unregister\_ hash()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int register_ hash(const struct _ hash_ descriptor *hash);
int unregister_ hash(const struct _ hash_ descriptor *hash);
\end { verbatim}
2004-10-30 03:00:26 +00:00
\section { Cipher Hash Construction}
\index { Cipher Hash Construction}
An addition to the suite of hash functions is the ``Cipher Hash Construction'' or ``CHC'' mode. In this mode
applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
particular this allows a cryptosystem to be designed using very few moving parts.
In order to use the CHC system the developer will have to take a few extra steps. First the ``chc\_ desc'' hash
descriptor must be registered with register\_ hash(). At this point the CHC hash cannot be used to hash
data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
via the chc\_ register() function.
\index { chc\_ register()}
\begin { verbatim}
int chc_ register(int cipher);
\end { verbatim}
A cipher has to be registered with CHC (and also in the cipher descriptor tables with
register\_ cipher()). The chc\_ register() function will bind a cipher to the CHC system. Only one cipher can
be bound to the CHC hash at a time. There are additional requirements for the system to work.
\begin { enumerate}
\item The cipher must have a block size greater than 64--bits.
\item The cipher must allow an input key the size of the block size.
\end { enumerate}
Example of using CHC with the AES block cipher.
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-10-30 03:00:26 +00:00
int main(void)
{
int err;
/* register cipher and hash */
if (register_ cipher(& aes_ enc_ desc) == -1) {
printf("Could not register cipher\n ");
return EXIT_ FAILURE;
}
if (register_ hash(& chc_ desc) == -1) {
printf("Could not register hash\n ");
return EXIT_ FAILURE;
}
/* start chc with AES */
if ((err = chc_ register(find_ cipher("aes"))) != CRYPT_ OK) {
printf("Error binding AES to CHC: %s\n", error_to_string(err));
}
/* now you can use chc_ hash in any LTC function [aside from pkcs...] */
/* ... */
\end { verbatim}
\section { Notice}
2003-06-01 18:55:11 +00:00
It is highly recommended that you \textbf { not} use the MD4 or MD5 hashes for the purposes of digital signatures or authentication codes.
2003-03-03 00:59:24 +00:00
These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
(e.g. Yarrow).
The other hashes such as the SHA-1, SHA-2 (that includes SHA-512, SHA-384 and SHA-256) and TIGER-192 are still considered secure
for all purposes you would normally use a hash for.
2004-02-20 20:03:32 +00:00
\chapter { Message Authentication Codes}
\section { HMAC Protocol}
2003-03-03 00:59:24 +00:00
Thanks to Dobes Vandermeer the library now includes support for hash based message authenication codes or HMAC for short. An HMAC
of a message is a keyed authenication code that only the owner of a private symmetric key will be able to verify. The purpose is
to allow an owner of a private symmetric key to produce an HMAC on a message then later verify if it is correct. Any impostor or
eavesdropper will not be able to verify the authenticity of a message.
The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
and its length. The key is much like a key you would pass to a cipher. That is, it is simply an array of octets stored in
chars. The initialization routine is:
2004-05-31 02:36:47 +00:00
\index { hmac\_ init()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int hmac_ init(hmac_ state *hmac, int hash,
const unsigned char *key, unsigned long keylen);
\end { verbatim}
The ``hmac'' parameter is the state for the HMAC code. ``hash'' is the index into the descriptor table of the hash you want
to use to authenticate the message. ``key'' is the pointer to the array of chars that make up the key. ``keylen'' is the
length (in octets) of the key you want to use to authenticate the message. To send octets of a message through the HMAC system you must use the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ process()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int hmac_ process(hmac_ state *hmac,
const unsigned char *in, unsigned long inlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
``hmac'' is the HMAC state you are working with. ``buf'' is the array of octets to send into the HMAC process. ``len'' is the
number of octets to process. Like the hash process routines you can send the data in arbitrarly sized chunks. When you
are finished with the HMAC process you must call the following function to get the HMAC code:
2004-05-31 02:36:47 +00:00
\index { hmac\_ done()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int hmac_ done(hmac_ state *hmac,
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
``hmac'' is the HMAC state you are working with. ``out'' is the array of octets where the HMAC code should be stored. You must
2003-09-08 01:06:11 +00:00
set ``outlen'' to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
2003-12-24 18:59:57 +00:00
produced (depending on which hash was picked). If ``outlen'' is less than the size of the message digest (and ultimately
the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first ``outlen'' bytes).
2003-03-13 02:12:16 +00:00
There are two utility functions provided to make using HMACs easier todo. They accept the key and information about the
message (file pointer, address in memory) and produce the HMAC result in one shot. These are useful if you want to avoid
calling the three step process yourself.
2004-05-31 02:36:47 +00:00
\index { hmac\_ memory()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int hmac_ memory(int hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will produce an HMAC code for the array of octets in ``in'' of length ``inlen''. The index into the hash descriptor
2003-06-01 18:55:11 +00:00
table must be provided in ``hash''. It uses the key from ``key'' with a key length of ``keylen''.
2004-12-30 23:55:53 +00:00
The result is stored in the array of octets ``out'' and the length in ``outlen''. The value of ``outlen'' must be set
2003-06-01 18:55:11 +00:00
to the size of the destination buffer before calling this function. Similarly for files there is the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ file()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int hmac_ file(int hash, const char *fname,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2003-06-01 18:55:11 +00:00
``hash'' is the index into the hash descriptor table of the hash you want to use. ``fname'' is the filename to process.
2004-12-30 23:55:53 +00:00
``key'' is the array of octets to use as the key of length ``keylen''. ``out'' is the array of octets where the
2003-03-13 02:12:16 +00:00
result should be stored.
2003-03-03 00:59:24 +00:00
To test if the HMAC code is working there is the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ test()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int hmac_ test(void);
\end { verbatim}
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code. Some example code for using the
HMAC system is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int idx, err;
2003-03-03 00:59:24 +00:00
hmac_ state hmac;
unsigned char key[16], dst[MAXBLOCKSIZE];
2003-09-08 01:06:11 +00:00
unsigned long dstlen;
2003-03-03 00:59:24 +00:00
/* register SHA-1 */
if (register_ hash(& sha1_ desc) == -1) {
printf("Error registering SHA1\n ");
return -1;
}
/* get index of SHA1 in hash descriptor table */
idx = find_ hash("sha1");
/* we would make up our symmetric key in "key[]" here */
/* start the HMAC */
2004-05-31 02:36:47 +00:00
if ((err = hmac_ init(& hmac, idx, key, 16)) != CRYPT_ OK) {
printf("Error setting up hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* process a few octets */
2004-05-31 02:36:47 +00:00
if((err = hmac_ process(& hmac, "hello", 5) != CRYPT_ OK) {
printf("Error processing hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* get result (presumably to use it somehow...) */
2003-09-08 01:06:11 +00:00
dstlen = sizeof(dst);
2004-05-31 02:36:47 +00:00
if ((err = hmac_ done(& hmac, dst, & dstlen)) != CRYPT_ OK) {
printf("Error finishing hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
2003-09-08 01:06:11 +00:00
printf("The hmac is %lu bytes long\n", dstlen);
2003-03-03 00:59:24 +00:00
/* return */
return 0;
}
\end { verbatim}
\end { small}
2003-12-24 18:59:57 +00:00
\section { OMAC Support}
OMAC\footnote { \url { http://crypt.cis.ibaraki.ac.jp/omac/omac.html} } , which stands for \textit { One-Key CBC MAC} is an
algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. From an API
standpoint the OMAC routines work much like the HMAC routines do. Instead in this case a cipher is used instead of a hash.
To start an OMAC state you call
2004-05-31 02:36:47 +00:00
\index { omac\_ init()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ init(omac_ state *omac, int cipher,
const unsigned char *key, unsigned long keylen);
\end { verbatim}
The ``omac'' variable is the state for the OMAC algorithm. ``cipher'' is the index into the cipher\_ descriptor table
of the cipher\footnote { The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
wish to use. ``key'' and ``keylen'' are the keys used to authenticate the data.
To send data through the algorithm call
2004-05-31 02:36:47 +00:00
\index { omac\_ process()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ process(omac_ state *state,
2004-12-30 23:55:53 +00:00
const unsigned char *in, unsigned long inlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will send ``inlen'' bytes from ``in'' through the active OMAC state ``state''. Returns \textbf { CRYPT\_ OK} if the
2004-02-20 20:03:32 +00:00
function succeeds. The function is not sensitive to the granularity of the data. For example,
\begin { verbatim}
omac_ process(& mystate, "hello", 5);
omac_ process(& mystate, " world", 6);
\end { verbatim}
Would produce the same result as,
\begin { verbatim}
omac_ process(& mystate, "hello world", 11);
\end { verbatim}
When you are done processing the message you can call the following to compute the message tag.
2003-12-24 18:59:57 +00:00
2004-05-31 02:36:47 +00:00
\index { omac\_ done()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ done(omac_ state *state,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
Which will terminate the OMAC and output the \textit { tag} (MAC) to ``out''. Note that unlike the HMAC and other code
``outlen'' can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
specification states that the output may be truncated. So if you pass in $ outlen = 5 $ and use AES as your cipher than
the output MAC code will only be five bytes long. If ``outlen'' is larger than the default size it is set to the default
size to show how many bytes were actually used.
Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
following function.
2004-05-31 02:36:47 +00:00
\index { omac\_ memory()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
2004-12-30 23:55:53 +00:00
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will compute the OMAC of ``inlen'' bytes of ``in'' using the key ``key'' of length ``keylen'' bytes and the cipher
2003-12-24 18:59:57 +00:00
specified by the ``cipher'''th entry in the cipher\_ descriptor table. It will store the MAC in ``out'' with the same
rules as omac\_ done.
To OMAC a file use
2004-05-31 02:36:47 +00:00
\index { omac\_ file()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
2004-12-30 23:55:53 +00:00
unsigned char *out, unsigned long *outlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
Which will OMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
and the cipher specified by the ``cipher'''th entry in the cipher\_ descriptor table. It will store the MAC in ``out'' with
the same rules as omac\_ done.
To test if the OMAC code is working there is the following function:
2004-05-31 02:36:47 +00:00
\index { omac\_ test()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ test(void);
\end { verbatim}
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code. Some example code for using the
OMAC system is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-12-24 18:59:57 +00:00
int main(void)
{
2004-02-20 20:03:32 +00:00
int idx, err;
2003-12-24 18:59:57 +00:00
omac_ state omac;
unsigned char key[16], dst[MAXBLOCKSIZE];
unsigned long dstlen;
/* register Rijndael */
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael\n ");
return -1;
}
/* get index of Rijndael in cipher descriptor table */
idx = find_ cipher("rijndael");
/* we would make up our symmetric key in "key[]" here */
/* start the OMAC */
2004-02-20 20:03:32 +00:00
if ((err = omac_ init(& omac, idx, key, 16)) != CRYPT_ OK) {
printf("Error setting up omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
/* process a few octets */
2004-02-20 20:03:32 +00:00
if((err = omac_ process(& omac, "hello", 5) != CRYPT_ OK) {
printf("Error processing omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
/* get result (presumably to use it somehow...) */
dstlen = sizeof(dst);
2004-02-20 20:03:32 +00:00
if ((err = omac_ done(& omac, dst, & dstlen)) != CRYPT_ OK) {
printf("Error finishing omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
printf("The omac is %lu bytes long\n", dstlen);
/* return */
return 0;
}
\end { verbatim}
\end { small}
2004-02-20 20:03:32 +00:00
\section { PMAC Support}
The PMAC\footnote { J.Black, P.Rogaway, ``A Block--Cipher Mode of Operation for Parallelizable Message Authentication''}
protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
API as the provided OMAC code.
A PMAC state is initialized with the following.
2004-05-31 02:36:47 +00:00
\index { pmac\_ init()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ init(pmac_ state *pmac, int cipher,
const unsigned char *key, unsigned long keylen);
\end { verbatim}
Which initializes the ``pmac'' state with the given ``cipher'' and ``key'' of length ``keylen'' bytes. The chosen cipher
must have a 64 or 128 bit block size (e.x. AES).
To MAC data simply send it through the process function.
2004-05-31 02:36:47 +00:00
\index { pmac\_ process()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ process(pmac_ state *state,
2004-12-30 23:55:53 +00:00
const unsigned char *in, unsigned long inlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will process ``inlen'' bytes of ``in'' in the given ``state''. The function is not sensitive to the granularity of the
2004-02-20 20:03:32 +00:00
data. For example,
\begin { verbatim}
pmac_ process(& mystate, "hello", 5);
pmac_ process(& mystate, " world", 6);
\end { verbatim}
Would produce the same result as,
\begin { verbatim}
pmac_ process(& mystate, "hello world", 11);
\end { verbatim}
When a complete message has been processed the following function can be called to compute the message tag.
2004-05-31 02:36:47 +00:00
\index { pmac\_ done()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ done(pmac_ state *state,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
This will store upto ``outlen'' bytes of the tag for the given ``state'' into ``out''. Note that if ``outlen'' is larger
than the size of the tag it is set to the amount of bytes stored in ``out''.
Similar to the PMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
following function.
2004-05-31 02:36:47 +00:00
\index { pmac\_ memory()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ memory(int cipher,
2004-12-30 23:55:53 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
This will compute the PMAC of ``msglen'' bytes of ``msg'' using the key ``key'' of length ``keylen'' bytes and the cipher
specified by the ``cipher'''th entry in the cipher\_ descriptor table. It will store the MAC in ``out'' with the same
rules as omac\_ done.
To PMAC a file use
2004-05-31 02:36:47 +00:00
\index { pmac\_ file()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
Which will PMAC the entire contents of the file specified by ``filename'' using the key ``key'' of length ``keylen'' bytes
and the cipher specified by the ``cipher'''th entry in the cipher\_ descriptor table. It will store the MAC in ``out'' with
the same rules as omac\_ done.
To test if the PMAC code is working there is the following function:
2005-04-17 11:37:13 +00:00
\index { pmac\_ test()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ test(void);
\end { verbatim}
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code.
2005-04-17 11:37:13 +00:00
\section { Pelican MAC}
Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a ``mixing function''. It achieves a very high
rate of processing and is potentially very secure. It requires AES to be enabled to function. You do not have to register\_ cipher() AES first though
as it calls AES directly.
\index { pelican\_ init()}
\begin { verbatim}
int pelican_ init(pelican_ state *pelmac, const unsigned char *key, unsigned long keylen);
\end { verbatim}
This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
\index { pelican\_ process()}
\begin { verbatim}
int pelican_ process(pelican_ state *pelmac, const unsigned char *in, unsigned long inlen);
\end { verbatim}
This will process ``inlen'' bytes of ``in'' through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
an entire message.
\index { pelican\_ done()}
\begin { verbatim}
int pelican_ done(pelican_ state *pelmac, unsigned char *out);
\end { verbatim}
This terminates a Pelican MAC and writes the 16--octet tag to ``out''.
\subsection { Example}
\begin { verbatim}
#include <tomcrypt.h>
int main(void)
{
pelican_ state pelstate;
unsigned char key[32], tag[16];
int err;
/* somehow initialize a key */
/* initialize pelican mac */
if ((err = pelican_ init(& pelstate, /* the state */
key, /* user key */
32 /* key length in octets */
)) != CRYPT_ OK) {
printf("Error initializing Pelican: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* MAC some data */
if ((err = pelican_ process(& pelstate, /* the state */
"hello world", /* data to mac */
11 /* length of data */
)) != CRYPT_ OK) {
printf("Error processing Pelican: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* Terminate the MAC */
if ((err = pelican_ done(& pelstate, /* the state */
tag /* where to store the tag */
)) != CRYPT_ OK) {
printf("Error terminating Pelican: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* tag[0..15] has the MAC output now */
return EXIT_ SUCCESS;
}
\end { verbatim}
2004-02-20 20:03:32 +00:00
2003-03-03 00:59:24 +00:00
\chapter { Pseudo-Random Number Generators}
\section { Core Functions}
The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
used to expand a shorter bit string into a longer bit string. PRNGs are used wherever random data is required such as Public Key (PK)
key generation. There is a universal structure called ``prng\_ state''. To initialize a PRNG call:
2004-08-06 16:42:41 +00:00
\index { PRNG start}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ start(prng_ state *prng);
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will setup the PRNG for future use and not seed it. In order for the PRNG to be cryptographically useful you must give it
entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
2004-08-06 16:42:41 +00:00
\index { PRNG add\_ entropy}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int XXX_ add_ entropy(const unsigned char *in, unsigned long inlen,
2003-03-03 00:59:24 +00:00
prng_ state *prng);
\end { verbatim}
Which returns { \bf CRYPTO\_ OK} if the entropy was accepted. Once you think you have enough entropy you call another
function to put the entropy into action.
2004-08-06 16:42:41 +00:00
\index { PRNG ready}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ ready(prng_ state *prng);
\end { verbatim}
Which returns { \bf CRYPTO\_ OK} if it is ready. Finally to actually read bytes call:
2004-08-06 16:42:41 +00:00
\index { PRNG read}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
unsigned long XXX_ read(unsigned char *out, unsigned long outlen,
2003-03-03 00:59:24 +00:00
prng_ state *prng);
\end { verbatim}
2004-08-06 16:42:41 +00:00
Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
the following.
\index { PRNG done}
\begin { verbatim}
void XXX_ done(prng_ state *prng);
\end { verbatim}
This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
so that you can later resume the PRNG call the following.
\index { PRNG export}
\begin { verbatim}
int XXX_ export(unsigned char *out, unsigned long *outlen,
prng_ state *prng);
\end { verbatim}
This will write a ``PRNG state'' to the buffer ``out'' of length ``outlen'' bytes. The idea of
the export is meant to be used as a ``seed file''. That is, when the program starts up there will not likely
be that much entropy available. To import a state to seed a PRNG call the following function.
\index { PRNG import}
\begin { verbatim}
int XXX_ import(const unsigned char *in, unsigned long inlen,
prng_ state *prng);
\end { verbatim}
This will call the start and add\_ entropy functions of the given PRNG. It will use the state in
``in'' of length ``inlen'' as the initial seed. You must pass the same seed length as was exported
by the corresponding export function.
Note that importing a state will not ``resume'' the PRNG from where it left off. That is, if you export
a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
specifically equal the 8 bytes you generated previously.
When a program is first executed the normal course of operation is
\begin { enumerate}
\item Gather entropy from your sources for a given period of time or number of events.
\item Start, use your entropy via add\_ entropy and ready the PRNG yourself.
\end { enumerate}
When your program is finished you simply call the export function and save the state to a medium (disk,
flash memory, etc). The next time your application starts up you can detect the state, feed it to the
import function and go on your way. It is ideal that (as soon as possible) after startup you export a
fresh state. This helps in the case that the program aborts or the machine is powered down without
being given a chance to exit properly.
Note that even if you have a state to import it is important to add new entropy to the state. However,
there is less pressure to do so.
To test a PRNG for operational conformity call the following functions.
\index { PRNG test}
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
This will return \textbf { CRYPT\_ OK} if PRNG is operating properly.
2003-03-03 00:59:24 +00:00
\subsection { Remarks}
It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
and call ready() you can now read from it. You can also keep adding new entropy to it. The new entropy will not be used
in the PRNG until ready() is called again. This allows the PRNG to be used and re-seeded at the same time. No real error
checking is guaranteed to see if the entropy is sufficient or if the PRNG is even in a ready state before reading.
\subsection { Example}
2004-08-06 16:42:41 +00:00
Below is a simple snippet to read 10 bytes from yarrow. Its important to note that this snippet is
{ \bf NOT} secure since the entropy added is not random.
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
prng_ state prng;
unsigned char buf[10];
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* start it */
2004-02-20 20:03:32 +00:00
if ((err = yarrow_ start(& prng)) != CRYPT_ OK) {
printf("Start error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
/* add entropy */
2004-02-20 20:03:32 +00:00
if ((err = yarrow_ add_ entropy("hello world", 11, & prng)) != CRYPT_ OK) {
printf("Add_ entropy error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
/* ready and read */
2004-02-20 20:03:32 +00:00
if ((err = yarrow_ ready(& prng)) != CRYPT_ OK) {
printf("Ready error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
printf("Read %lu bytes from yarrow\n", yarrow_read(buf, 10, &prng));
return 0;
}
\end { verbatim}
\section { PRNG Descriptors}
\index { PRNG Descriptor}
PRNGs have descriptors too (surprised?). Stored in the structure ``prng\_ descriptor''. The format of an element is:
\begin { verbatim}
struct _ prng_ descriptor {
char *name;
2004-08-06 16:42:41 +00:00
int export_ size; /* size in bytes of exported state */
2003-03-03 00:59:24 +00:00
int (*start) (prng_ state *);
int (*add_ entropy)(const unsigned char *, unsigned long, prng_ state *);
int (*ready) (prng_ state *);
unsigned long (*read)(unsigned char *, unsigned long len, prng_ state *);
2004-08-06 16:42:41 +00:00
void (*done)(prng_ state *);
int (*export)(unsigned char *, unsigned long *, prng_ state *);
int (*import)(const unsigned char *, unsigned long, prng_ state *);
int (*test)(void);
2003-03-03 00:59:24 +00:00
} ;
\end { verbatim}
2005-08-01 16:36:47 +00:00
\index { find\_ prng()}
2003-03-03 00:59:24 +00:00
There is a ``int find\_ prng(char *name)'' function as well. Returns -1 if the PRNG is not found, otherwise it returns
the position in the prng\_ descriptor array.
Just like the ciphers and hashes you must register your prng before you can use it. The two functions provided work
exactly as those for the cipher registry functions. They are:
\begin { verbatim}
int register_ prng(const struct _ prng_ descriptor *prng);
int unregister_ prng(const struct _ prng_ descriptor *prng);
\end { verbatim}
2004-08-06 16:42:41 +00:00
\subsection { PRNGs Provided}
\begin { figure} [here]
\begin { center}
\begin { small}
\begin { tabular} { |c|c|l|}
\hline \textbf { Name} & \textbf { Descriptor} & \textbf { Usage} \\
\hline Yarrow & yarrow\_ desc & Fast short-term PRNG \\
\hline Fortuna & fortuna\_ desc & Fast long-term PRNG (recommended) \\
\hline RC4 & rc4\_ desc & Stream Cipher \\
\hline SOBER-128 & sober128\_ desc & Stream Cipher (also very fast PRNG) \\
\hline
\end { tabular}
\end { small}
\end { center}
\caption { List of Provided PRNGs}
\end { figure}
\subsubsection { Yarrow}
Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
(keyboard, mouse, interrupts, etc) and produce an unbounded string of random bytes.
\textit { Note:} This PRNG is still secure for most taskings but is no longer recommended. Users
should use Fortuna instead.
\subsubsection { Fortuna}
Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
usage. It is faster than the default implementation of Yarrow\footnote { Yarrow has been implemented
to work with most cipher and hash combos based on which you have chosen to build into the library.} while
providing more security.
Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
and SHA--256 hash function. Technically Fortuna will work with any block cipher that accepts a 256--bit
key and any hash that produces at least a 256--bit output. However, to make the implementation simpler
it has been fixed to those choices.
Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
details Fortuna has the ability to recover from state determination attacks where the attacker starts
to learn information from the PRNGs output about the internal state. Yarrow on the other hand cannot
recover from that problem until new entropy is added to the pool and put to use through the ready() function.
\subsubsection { RC4}
RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You ``key'' it by
calling add\_ entropy() and setup the key by calling ready(). You can only add upto 256 bytes via
add\_ entropy().
When you read from RC4 the output of the RC4 algorithm is XOR'd against your buffer you provide. In this
manner you can use rc4\_ read() as an encrypt (and decrypt) function.
You really shouldn't use RC4 anymore. This isn't because RC4 is weak (though biases are known to exist) just
simply that faster alternatives exist.
\subsubsection { SOBER-128}
SOBER-128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4 you ``key'' it by
calling add\_ entropy(). There is no need to call ready() for this PRNG as it does not do anything.
Note that this cipher has several oddities about how it operates. The first time you call
add\_ entropy() that sets the cipher's key. Every other time you call the same function it sets
the cipher's IV variable. The IV mechanism allows you to encrypt several messages with the same
key and not re--use the same key material.
Unlike Yarrow and Fortuna all of the entropy (and hence security) of this algorithm rests in the data
you pass it on the first call to add\_ entropy(). All buffers sent to add\_ entropy() must have a length
that is a multiple of four bytes.
Like RC4 the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner you can use
sober128\_ read() as an encrypt (and decrypt) function.
2003-03-03 00:59:24 +00:00
2004-08-06 16:42:41 +00:00
Since SOBER-128 has a fixed keying scheme and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
key it from the output of Fortuna (or Yarrow) and use it to encrypt messages. It is also ideal for
simulations which need a high quality (and fast) stream of bytes.
2003-03-03 00:59:24 +00:00
2004-08-06 16:42:41 +00:00
\subsubsection { Example Usage}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
prng_ state prng;
unsigned char buf[32];
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
2004-02-20 20:03:32 +00:00
if ((err = rc4_ start(& prng)) != CRYPT_ OK) {
printf("RC4 init error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
/* use ``key'' as the key */
2004-02-20 20:03:32 +00:00
if ((err = rc4_ add_ entropy("key", 3, & prng)) != CRYPT_ OK) {
printf("RC4 add entropy error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
/* setup RC4 for use */
2004-02-20 20:03:32 +00:00
if ((err = rc4_ ready(& prng)) != CRYPT_ OK) {
printf("RC4 ready error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
/* encrypt buffer */
strcpy(buf,"hello world");
if (rc4_ read(buf, 11, & prng) != 11) {
printf("RC4 read error\n ");
exit(-1);
}
return 0;
}
\end { verbatim}
\end { small}
To decrypt you have to do the exact same steps.
\section { The Secure RNG}
\index { Secure RNG}
An RNG is related to a PRNG except that it doesn't expand a smaller seed to get the data. They generate their random bits
by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
PRNG. Computers are deterministic beasts that try hard not to stray from pre-determined paths. That makes gathering
entropy needed to seed the PRNG a hard task.
There is one small function that may help on certain platforms:
\index { rng\_ get\_ bytes()}
\begin { verbatim}
unsigned long rng_ get_ bytes(unsigned char *buf, unsigned long len,
void (*callback)(void));
\end { verbatim}
Which will try one of three methods of getting random data. The first is to open the popular ``/dev/random'' device which
on most *NIX platforms provides cryptographic random bits\footnote { This device is available in Windows through the Cygwin compiler suite. It emulates ``/dev/random'' via the Microsoft CSP.} .
The second method is to try the Microsoft Cryptographic Service Provider and read the RNG. The third method is an ANSI C
clock drift method that is also somewhat popular but gives bits of lower entropy. The ``callback'' parameter is a pointer to a function that returns void. Its used when the slower ANSI C RNG must be
used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of three
bytes a second. The callback pointer may be set to { \bf NULL} to avoid using it if you don't want to. The function
returns the number of bytes actually read from any RNG source. There is a function to help setup a PRNG as well:
\index { rng\_ make\_ prng()}
\begin { verbatim}
int rng_ make_ prng(int bits, int wprng, prng_ state *prng,
void (*callback)(void));
\end { verbatim}
This will try to setup the prng with a state of at least ``bits'' of entropy. The ``callback'' parameter works much like
the callback in ``rng\_ get\_ bytes()''. It is highly recommended that you use this function to setup your PRNGs unless you have a
platform where the RNG doesn't work well. Example usage of this function is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
ecc_ key mykey;
prng_ state prng;
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* register yarrow */
if (register_ prng(& yarrow_ desc) == -1) {
printf("Error registering Yarrow\n ");
return -1;
}
/* setup the PRNG */
2004-02-20 20:03:32 +00:00
if ((err = rng_ make_ prng(128, find_ prng("yarrow"), & prng, NULL)) != CRYPT_ OK) {
printf("Error setting up PRNG, %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* make a 192-bit ECC key */
2004-02-20 20:03:32 +00:00
if ((err = ecc_ make_ key(& prng, find_ prng("yarrow"), 24, & mykey)) != CRYPT_ OK) {
printf("Error making key: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
\subsection { The Secure PRNG Interface}
It is possible to access the secure RNG through the PRNG interface and in turn use it within dependent functions such
as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
requires to be started, that is you need not call the start, add\_ entropy or ready functions. For example, consider
the previous example using this PRNG.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
ecc_ key mykey;
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* register SPRNG */
if (register_ prng(& sprng_ desc) == -1) {
printf("Error registering SPRNG\n ");
return -1;
}
/* make a 192-bit ECC key */
2004-02-20 20:03:32 +00:00
if ((err = ecc_ make_ key(NULL, find_ prng("sprng"), 24, & mykey)) != CRYPT_ OK) {
printf("Error making key: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
2004-12-30 23:55:53 +00:00
2004-05-12 20:42:16 +00:00
\chapter { RSA Public Key Cryptography}
2004-05-31 02:36:47 +00:00
\section { Introduction}
RSA wrote the PKCS \# 1 specifications which detail RSA Public Key Cryptography. In the specifications are
2005-06-09 00:08:13 +00:00
padding algorithms for encryption and signatures. The standard includes the ``v2.1'' algorithms.
To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS
2004-05-31 02:36:47 +00:00
respectively.
2004-05-12 20:42:16 +00:00
\section { PKCS \# 1 Encryption}
PKCS \# 1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
the library is concerned we are only dealing with th OAEP padding of the message.
\subsection { OAEP Encoding}
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ oaep\_ encode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
int pkcs_ 1_ oaep_ encode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
2004-05-31 02:36:47 +00:00
unsigned long modulus_ bitlen, prng_ state *prng,
int prng_ idx, int hash_ idx,
2004-05-12 20:42:16 +00:00
unsigned char *out, unsigned long *outlen);
\end { alltt}
This accepts ``msg'' as input of length ``msglen'' which will be OAEP padded. The ``lparam'' variable is an additional system specific
tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
``lparam'' can be set to \textbf { NULL} .
OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output. This is passed as the parameter
``modulus\_ bitlen''. ``hash\_ idx'' is the index into the hash descriptor table of the hash desired. PKCS \# 1 allows any hash to be
used but both the encoder and decoder must use the same hash in order for this to succeed. The size of hash output affects the maximum
sized input message. ``prng\_ idx'' and ``prng'' are the random number generator arguments required to randomize the padding process.
The padded message is stored in ``out'' along with the length in ``outlen''.
If $ h $ is the length of the hash and $ m $ the length of the modulus (both in octets) then the maximum payload for ``msg'' is
$ m - 2 h - 2 $ . For example, with a $ 1024 $ --bit RSA key and SHA--1 as the hash the maximum payload is $ 86 $ bytes.
Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
rsa\_ exptmod() to encrypt it.
\subsection { OAEP Decoding}
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ oaep\_ decode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
int pkcs_ 1_ oaep_ decode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_ bitlen, int hash_ idx,
2004-05-31 02:36:47 +00:00
unsigned char *out, unsigned long *outlen,
int *res);
2004-05-12 20:42:16 +00:00
\end { alltt}
This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. ``msg'' is the
output of pkcs\_ 1\_ oaep\_ encode() of length ``msglen''. ``lparam'' is the same system variable passed to the OAEP encoder. If it does not
match what was used during encoding this function will not decode the packet. ``modulus\_ bitlen'' is the size of the RSA modulus in bits
and must match what was used during encoding. Similarly the ``hash\_ idx'' index into the hash descriptor table must match what was used
during encoding.
2004-05-31 02:36:47 +00:00
If the function succeeds it decodes the OAEP encoded message into ``out'' of length ``outlen'' and stores a
$ 1 $ in ``res''. If the packet is invalid it stores $ 0 $ in ``res'' and if the function fails for another reason
it returns an error code.
2004-05-12 20:42:16 +00:00
\section { PKCS \# 1 Digital Signatures}
\subsection { PSS Encoding}
PSS encoding is the second half of the PKCS \# 1 standard which is padding to be applied to messages that are signed.
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ pss\_ encode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
int pkcs_ 1_ pss_ encode(const unsigned char *msghash, unsigned long msghashlen,
2004-05-31 02:36:47 +00:00
unsigned long saltlen, prng_ state *prng,
int prng_ idx, int hash_ idx,
2004-05-12 20:42:16 +00:00
unsigned long modulus_ bitlen,
unsigned char *out, unsigned long *outlen);
\end { alltt}
This function assumes the message to be PSS encoded has previously been hashed. The input hash ``msghash'' is of length
``msghashlen''. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
``hash\_ idx'' is the index into the hash descriptor table of the hash to use. ``prng\_ idx'' and ``prng'' are the random
number generator information required for the salt.
2004-05-31 02:36:47 +00:00
Similar to OAEP encoding ``modulus\_ bitlen'' is the size of the RSA modulus (in bits). It limits the size of the salt. If $ m $ is the length
2004-05-12 20:42:16 +00:00
of the modulus $ h $ the length of the hash output (in octets) then there can be $ m - h - 2 $ bytes of salt.
This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_ exptmod().
\subsection { PSS Decoding}
To decode a PSS encoded signature block you have to use the following.
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ pss\_ decode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
int pkcs_ 1_ pss_ decode(const unsigned char *msghash, unsigned long msghashlen,
const unsigned char *sig, unsigned long siglen,
unsigned long saltlen, int hash_ idx,
unsigned long modulus_ bitlen, int *res);
\end { alltt}
This will decode the PSS encoded message in ``sig'' of length ``siglen'' and compare it to values in ``msghash'' of length
``msghashlen''. If the block is a valid PSS block and the decoded hash equals the hash supplied ``res'' is set to non--zero. Otherwise,
it is set to zero. The rest of the parameters are as in the PSS encode call.
It's important to use the same ``saltlen'' and hash for both encoding and decoding as otherwise the procedure will not work.
2004-05-31 02:36:47 +00:00
\section { RSA Operations}
\subsection { Background}
2003-03-03 00:59:24 +00:00
RSA is a public key algorithm that is based on the inability to find the ``e-th'' root modulo a composite of unknown
factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
not strictly equivalent.
The system begins with with two primes $ p $ and $ q $ and their product $ N = pq $ . The order or ``Euler totient'' of the
multiplicative sub-group formed modulo $ N $ is given as $ \phi ( N ) = ( p - 1 ) ( q - 1 ) $ which can be reduced to
$ \mbox { lcm } ( p - 1 , q - 1 ) $ . The public key consists of the composite $ N $ and some integer $ e $ such that
$ \mbox { gcd } ( e, \phi ( N ) ) = 1 $ . The private key consists of the composite $ N $ and the inverse of $ e $ modulo $ \phi ( N ) $
often simply denoted as $ de \equiv 1 \mbox { } ( \mbox { mod } \phi ( N ) ) $ .
A person who wants to encrypt with your public key simply forms an integer (the plaintext) $ M $ such that
$ 1 < M < N - 2 $ and computes the ciphertext $ C = M ^ e \mbox { } ( \mbox { mod } N ) $ . Since finding the inverse exponent $ d $
given only $ N $ and $ e $ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
$ C ^ d \equiv \left ( M ^ e \right ) ^ d \equiv M ^ 1 \equiv M \mbox { } ( \mbox { mod } N ) $ . Similarly the owner of the private key
can sign a message by ``decrypting'' it. Others can verify it by ``encrypting'' it.
Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
Ideally $ e $ should be larger than $ 100 $ to prevent direct analysis. For example, if $ e $ is three and you do not pad
the plaintext to be encrypted than it is possible that $ M ^ 3 < N $ in which case finding the cube-root would be trivial.
The most often suggested value for $ e $ is $ 65537 $ since it is large enough to make such attacks impossible and also well
designed for fast exponentiation (requires 16 squarings and one multiplication).
It is important to pad the input to RSA since it has particular mathematical structure. For instance
$ M _ 1 ^ dM _ 2 ^ d = ( M _ 1 M _ 2 ) ^ d $ which can be used to forge a signature. Suppose $ M _ 3 = M _ 1 M _ 2 $ is a message you want
to have a forged signature for. Simply get the signatures for $ M _ 1 $ and $ M _ 2 $ on their own and multiply the result
together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
the hash of documents only but also to pad the inputs with data to remove such structure.
2004-05-31 02:36:47 +00:00
\subsection { RSA Key Generation}
2003-03-03 00:59:24 +00:00
For RSA routines a single ``rsa\_ key'' structure is used. To make a new RSA key call:
\index { rsa\_ make\_ key()}
\begin { verbatim}
int rsa_ make_ key(prng_ state *prng,
int wprng, int size,
long e, rsa_ key *key);
\end { verbatim}
Where ``wprng'' is the index into the PRNG descriptor array. ``size'' is the size in bytes of the RSA modulus desired.
``e'' is the encryption exponent desired, typical values are 3, 17, 257 and 65537. I suggest you stick with 65537 since its big
enough to prevent trivial math attacks and not super slow. ``key'' is where the key is placed. All keys must be at
2003-06-01 18:55:11 +00:00
least 128 bytes and no more than 512 bytes in size (\textit { that is from 1024 to 4096 bits} ).
2003-03-03 00:59:24 +00:00
Note that the ``rsa\_ make\_ key()'' function allocates memory at runtime when you make the key. Make sure to call
``rsa\_ free()'' (see below) when you are finished with the key. If ``rsa\_ make\_ key()'' fails it will automatically
free the ram allocated itself.
2004-10-30 03:00:26 +00:00
\index { PK\_ PRIVATE} \index { PK\_ PUBLIC}
There are two types of RSA keys. The types are { \bf PK\_ PRIVATE} and { \bf PK\_ PUBLIC} . The first type is a private
RSA key which includes the CRT parameters\footnote { As of v0.99 the PK\_ PRIVATE\_ OPTIMIZED type has been deprecated
and has been replaced by the PK\_ PRIVATE type.} in the form of a RSAPrivateKey. The second type is a public RSA key
which only includes the modulus and public exponent. It takes the form of a RSAPublicKey.
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\subsection { RSA Exponentiation}
2003-03-03 00:59:24 +00:00
To do raw work with the RSA function call:
\index { rsa\_ exptmod()}
\begin { verbatim}
2004-05-31 02:36:47 +00:00
int rsa_ exptmod(const unsigned char *in, unsigned long inlen,
2004-12-30 23:55:53 +00:00
unsigned char *out, unsigned long *outlen,
int which, prng_ state *prng, int prng_ idx,
2004-05-31 02:36:47 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2003-03-03 01:01:40 +00:00
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
2003-03-03 00:59:24 +00:00
in ``out'' and the size of the result in ``outlen''. ``which'' is set to { \bf PK\_ PUBLIC} to use ``e''
(i.e. for encryption/verifying) and set to { \bf PK\_ PRIVATE} to use ``d'' as the exponent (i.e. for decrypting/signing).
2004-05-31 02:36:47 +00:00
Note that the output of his function is zero-padded as per PKCS \# 1 specifications. This allows this routine to
interoprate with PKCS \# 1 padding functions properly.
2003-12-24 18:59:57 +00:00
2004-05-31 02:36:47 +00:00
\subsection { RSA Key Encryption}
Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
To facilitate encrypting short keys the following functions have been provided.
\index { rsa\_ encrypt\_ key()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int rsa_ encrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
2004-05-31 02:36:47 +00:00
const unsigned char *lparam, unsigned long lparamlen,
prng_ state *prng, int prng_ idx, int hash_ idx, rsa_ key *key);
2003-06-01 18:55:11 +00:00
\end { verbatim}
2004-12-30 23:55:53 +00:00
This function will OAEP pad ``in'' of length inlen bytes then RSA encrypt it and store the ciphertext
in ``out'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2004-05-31 02:36:47 +00:00
to pkcs\_ 1\_ oaep\_ encode().
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\index { rsa\_ decrypt\_ key()}
2003-06-01 18:55:11 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int rsa_ decrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
2004-05-31 02:36:47 +00:00
const unsigned char *lparam, unsigned long lparamlen,
2005-06-09 00:08:13 +00:00
int hash_ idx, int *stat,
2004-05-31 02:36:47 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2004-05-31 02:36:47 +00:00
This function will RSA decrypt ``in'' of length ``inlen'' then OAEP depad the resulting data and store it in
2004-12-30 23:55:53 +00:00
``out'' of length ``outlen''. The ``lparam'' and ``lparamlen'' are the same parameters you would pass
2004-05-31 02:36:47 +00:00
to pkcs\_ 1\_ oaep\_ decode().
2005-06-09 00:08:13 +00:00
If the RSA decrypted data isn't a valid OAEP packet then ``stat'' is set to $ 0 $ . Otherwise, it is set to $ 1 $ .
2004-05-31 02:36:47 +00:00
\subsection { RSA Hash Signatures}
Similar to RSA key encryption RSA is also used to ``digitally sign'' message digests (hashes). To facilitate this
process the following functions have been provided.
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\index { rsa\_ sign\_ hash()}
2003-03-03 01:01:40 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int rsa_ sign_ hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
2004-05-31 02:36:47 +00:00
prng_ state *prng, int prng_ idx,
int hash_ idx, unsigned long saltlen,
2003-03-03 01:01:40 +00:00
rsa_ key *key);
\end { verbatim}
2004-12-30 23:55:53 +00:00
This will PSS encode the message hash ``in'' of length ``inlen''. Next the PSS encoded message will be RSA ``signed'' and
the output is stored in ``out'' of length ``outlen''.
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\index { rsa\_ verify\_ hash()}
\begin { verbatim}
int rsa_ verify_ hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *msghash, unsigned long msghashlen,
int hash_ idx, unsigned long saltlen,
int *stat, rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2004-05-31 02:36:47 +00:00
This will RSA ``verify'' the signature in ``sig'' of length ``siglen''. Next the RSA decoded data is PSS decoded
and the extracted hash is compared against the message hash ``msghash'' of length ``msghashlen''.
If the RSA decoded data is not a valid PSS message or if the PSS decoded hash does not match the ``msghash''
the value ``res'' is set to $ 0 $ . Otherwise, if the function succeeds and signature is valid ``res'' is set
to $ 1 $ .
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-05-31 02:36:47 +00:00
int main(void)
{
int err, hash_ idx, prng_ idx, res;
unsigned long l1, l2;
unsigned char pt[16], pt2[16], out[1024];
rsa_ key key;
/* register prng/hash */
if (register_ prng(& sprng_ desc) == -1) {
printf("Error registering sprng");
return EXIT_ FAILURE;
}
2005-08-01 16:36:47 +00:00
/* register a math library (in this case TomFastMath)
ltc_ mp = tfm_ desc;
2004-05-31 02:36:47 +00:00
if (register_ hash(& sha1_ desc) == -1) {
printf("Error registering sha1");
return EXIT_ FAILURE;
}
hash_ idx = find_ hash("sha1");
prng_ idx = find_ prng("sprng");
/* make an RSA-1024 key */
if ((err = rsa_ make_ key(NULL, /* PRNG state */
prng_ idx, /* PRNG idx */
1024/8, /* 1024-bit key */
65537, /* we like e=65537 */
& key) /* where to store the key */
) != CRYPT_ OK) {
printf("rsa_ make_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* fill in pt[] with a key we want to send ... */
l1 = sizeof(out);
if ((err = rsa_ encrypt_ key(pt, /* data we wish to encrypt */
16, /* data is 16 bytes long */
out, /* where to store ciphertext */
& l1, /* length of ciphertext */
"TestApp", /* our lparam for this program */
7, /* lparam is 7 bytes long */
NULL, /* PRNG state */
prng_ idx, /* prng idx */
hash_ idx, /* hash idx */
& key) /* our RSA key */
) != CRYPT_ OK) {
printf("rsa_ encrypt_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* now let's decrypt the encrypted key */
l2 = sizeof(pt2);
if ((err = rsa_ decrypt_ key(out, /* encrypted data */
l1, /* length of ciphertext */
pt2, /* where to put plaintext */
& l2, /* plaintext length */
"TestApp", /* lparam for this program */
7, /* lparam is 7 bytes long */
hash_ idx, /* hash idx */
& res, /* validity of data */
& key) /* our RSA key */
) != CRYPT_ OK) {
printf("rsa_ decrypt_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* if all went well pt == pt2, l2 == 16, res == 1 */
}
2003-03-03 00:59:24 +00:00
\end { verbatim}
2005-08-01 16:36:47 +00:00
\subsection { RSA Key Export}
To export a RSA key use the following function.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\index { rsa\_ export()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2005-08-01 16:36:47 +00:00
int rsa_ export(unsigned char *out, unsigned long *outlen, int type, rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2005-08-01 16:36:47 +00:00
This will export the RSA key in either a RSAPublicKey or RSAPrivateKey (PKCS \# 1 types) depending on the value of ``type''. When it is
set to \textbf { PK\_ PRIVATE} the export format will be RSAPrivateKey and otherwise it will be RSAPublicKey.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\subsection { RSA Key Import}
To import a RSA key use the following function.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\index { rsa\_ import()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2005-08-01 16:36:47 +00:00
int rsa_ import(const unsigned char *in, unsigned long inlen, rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2005-08-01 16:36:47 +00:00
This will import the key stored in ``inlen'' and import it to ``key''. If the function fails it will automatically free any allocated memory. This
function can import both RSAPublicKey and RSAPrivateKey formats.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
As of v1.06 this function can also import OpenSSL DER formatted public RSA keys. They are essentially encapsulated RSAPublicKeys. LibTomCrypt will
import the key, strip off the additional data (it's the preferred hash) and fill in the rsa\_ key structure as if it were a native RSAPublicKey. Note that
there is no function provided to export in this format.
2003-03-03 01:01:40 +00:00
2003-03-03 00:59:24 +00:00
\chapter { Elliptic Curve Cryptography}
\section { Background}
The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
of the order of the base point in time. That means if you use a base point of order $ 2 ^ { 192 } $ (which would represent a
192-bit key) then the work factor is $ 2 ^ { 96 } $ in order to find the secret key.
The curves in this library are taken from the following website:
\begin { verbatim}
http://csrc.nist.gov/cryptval/dss.htm
\end { verbatim}
They are all curves over the integers modulo a prime. The curves have the basic equation that is:
\begin { equation}
y^ 2 = x^ 3 - 3x + b\mbox { } (\mbox { mod } p)
\end { equation}
The variable $ b $ is chosen such that the number of points is nearly maximal. In fact the order of the base points $ \beta $
provided are very close to $ p $ that is $ \vert \vert \phi ( \beta ) \vert \vert \approx \vert \vert p \vert \vert $ . The curves
range in order from $ \approx 2 ^ { 192 } $ points to $ \approx 2 ^ { 521 } $ . According to the source document any key size greater
than or equal to 256-bits is sufficient for long term security.
2005-06-09 00:08:13 +00:00
\section { Key Format}
LibTomCrypt uses it's own format for ECC public and private keys. While ANSI X9.62 partially specifies key formats (it covers public keys) it does it in a less
than ideally simple manner. In the case of LibTomCrypt it is meant \textbf { solely} for NIST $ GF ( p ) $ curves. The format of the keys is as follows:
\begin { small}
\begin { verbatim}
ECCPublicKey ::= SEQUENCE {
2005-06-14 22:16:11 +00:00
flags BIT STRING(1), -- public/private flag (always zero),
2005-06-09 00:08:13 +00:00
keySize INTEGER, -- Curve size (in bits) divided by eight
-- and rounded down, e.g. 521 => 65
pubkey.x INTEGER, -- The X co-ordinate of the public key point
2005-06-14 22:16:11 +00:00
pubkey.y INTEGER, -- The Y co-ordinate of the public key point
2005-06-09 00:08:13 +00:00
}
ECCPrivateKey ::= SEQUENCE {
2005-06-14 22:16:11 +00:00
flags BIT STRING(1), -- public/private flag (always one),
2005-06-09 00:08:13 +00:00
keySize INTEGER, -- Curve size (in bits) divided by eight
-- and rounded down, e.g. 521 => 65
pubkey.x INTEGER, -- The X co-ordinate of the public key point
2005-06-14 22:16:11 +00:00
pubkey.y INTEGER, -- The Y co-ordinate of the public key point
2005-06-09 00:08:13 +00:00
secret.k INTEGER, -- The secret key scalar
}
\end { verbatim}
\end { small}
2005-06-14 22:16:11 +00:00
The first flags bit denotes whether the key is public (zero) or private (one).
2005-06-09 00:08:13 +00:00
2003-03-03 00:59:24 +00:00
\section { Core Functions}
2005-08-01 16:36:47 +00:00
\subsection { ECC Key Generation}
There is a key structure called ``ecc\_ key'' used by the ECC functions. There is a function to make a key:
2003-03-03 00:59:24 +00:00
\index { ecc\_ make\_ key()}
\begin { verbatim}
int ecc_ make_ key(prng_ state *prng, int wprng,
int keysize, ecc_ key *key);
\end { verbatim}
2005-06-27 11:47:35 +00:00
The ``keysize'' is the size of the modulus in bytes desired. Currently directly supported values are 24, 28, 32, 48 and 65 bytes which
2005-08-01 16:36:47 +00:00
correspond to key sizes of 192, 224, 256, 384 and 521 bits respectively. If you pass a key size that is between any key size it will round
the keysize up to the next available one. To free the ram allocated by a ecc\_ make\_ key() or ecc\_ import() call use the following function.
2003-03-03 00:59:24 +00:00
\index { ecc\_ free()}
\begin { verbatim}
void ecc_ free(ecc_ key *key);
\end { verbatim}
2005-08-01 16:36:47 +00:00
\subsection { ECC Key Export}
To export an ECC key.
2003-03-03 00:59:24 +00:00
\index { ecc\_ export()}
\begin { verbatim}
int ecc_ export(unsigned char *out, unsigned long *outlen,
int type, ecc_ key *key);
2005-08-01 16:36:47 +00:00
\end { verbatim}
This will export the key with the given ``type'' (\textbf { PK\_ PUBLIC} or \textbf { PK\_ PRIVATE} ) and store it to ``out''.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\subsection { ECC Key Import}
\index { ecc\_ import()}
\begin { verbatim}
2003-03-03 01:01:40 +00:00
int ecc_ import(const unsigned char *in, unsigned long inlen, ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2005-08-01 16:36:47 +00:00
This will import the ECC key from ``in'' and store it in the ecc\_ key structure ``key''. If the operation fails it will free
any allocated memory automatically.
\subsection { ECC Shared Secret}
Finally when you share your public key you can make a shared secret with the following.
2003-03-03 00:59:24 +00:00
\index { ecc\_ shared\_ secret()}
\begin { verbatim}
int ecc_ shared_ secret(ecc_ key *private_ key,
ecc_ key *public_ key,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
2005-08-01 16:36:47 +00:00
The ``private\_ key'' is your own key and ``public\_ key'' is the key the other user sent you. Note that this function stores only the
$ x $ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.
2003-03-03 00:59:24 +00:00
2005-11-18 05:15:37 +00:00
\section { ECC Diffie-Hellman Encryption}
2003-03-03 01:01:40 +00:00
Similar to the RSA API there are two functions which encrypt and decrypt symmetric keys using the ECC public key
algorithms.
2004-05-31 02:36:47 +00:00
2005-11-18 05:15:37 +00:00
\index { ecc\_ encrypt\_ key()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int ecc_ encrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
2003-03-03 00:59:24 +00:00
prng_ state *prng, int wprng, int hash,
ecc_ key *key);
2005-11-18 05:15:37 +00:00
\end { verbatim}
Where ``in'' is an input symmetric key of no more than 64 bytes. This function creates a random public key
and computes the hash of the shared secret. The message digest is then XOR'ed against the symmetric key. All of the required
data is placed in ``out'' by ``ecc\_ encrypt\_ key()''. The hash chosen must produce a message digest at least as large
as the symmetric key you are trying to share.
The data is encrypted to the public ECC ``key'' such that only the holder of the private key can decrypt the payload. If you want
to have multiple recipients you will have to call this function for each public ECC key you want to encrypt to.
2003-03-03 00:59:24 +00:00
2005-11-18 05:15:37 +00:00
\index { ecc\_ decrypt\_ key()}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
int ecc_ decrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
2003-03-03 01:02:10 +00:00
ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2003-03-03 01:01:40 +00:00
2005-11-18 05:15:37 +00:00
This function will decrypt an encrypted payload. The ``key'' provided must be the private key corresponding to the public key
used during encryption. If the wrong key is provided the function won't specifically return an error code. It is important
to use some form of challenge response in that case (e.g. compute a MAC of a known string).
2003-03-03 01:01:40 +00:00
2005-11-18 05:15:37 +00:00
\subsection { Encrypt Encryption Format}
2005-06-09 00:08:13 +00:00
The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
\begin { verbatim}
ECCEncrypt ::= SEQUENCE {
hashID OBJECT IDENTIFIER, -- OID of hash used
pubkey OCTET STRING , -- Encapsulated ECCPublicKey (see above)
skey OCTET STRING -- xor of plaintext and "hash of shared secret"
}
\end { verbatim}
2005-11-18 05:15:37 +00:00
\section { ECC DSA Signatures}
2003-03-03 01:01:40 +00:00
There are also functions to sign and verify the hash of a message.
2005-11-18 05:15:37 +00:00
\index { ecc\_ sign\_ hash()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int ecc_ sign_ hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_ state *prng, int wprng, ecc_ key *key);
2005-11-18 05:15:37 +00:00
\end { verbatim}
2003-03-03 00:59:24 +00:00
2005-11-18 05:15:37 +00:00
This function will EC--DSA sign the message digest stored in the buffer ``in'' of length inlen octets. The signature
will be stored in the ``out'' buffer of length ``outlen''. The function requires a properly seeded PRNG and
the ECC ``key'' provided must be a private key.
\index { ecc\_ verify\_ hash()}
\begin { verbatim}
2003-03-03 01:02:10 +00:00
int ecc_ verify_ hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2005-11-18 05:15:37 +00:00
This function will verify the EC-DSA signature in ``sig'' of length ``siglen'' against the message digest ``hash''.
It will store a non--zero value in ``stat'' if the signature is valid. Note that the function will not return
an error if the signature is invalid. It will if the actual signature payload is an invalid format. They ECC ``key''
must be the public (or private) ECC key corresponding to the key that performed the signature.
2003-03-03 01:01:40 +00:00
2005-06-09 00:08:13 +00:00
\subsection { Signature Format}
2005-11-18 05:15:37 +00:00
The signature code is an implementation of X9.62 EC--DSA and the output is comformant for GF(p) curves.
2003-03-03 01:01:40 +00:00
2003-03-03 01:01:00 +00:00
\section { ECC Keysizes}
With ECC if you try and sign a hash that is bigger than your ECC key you can run into problems. The math will still work
and in effect the signature will still work. With ECC keys the strength of the signature is limited by the size of
2005-06-27 11:47:35 +00:00
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
2005-11-18 05:15:37 +00:00
you have 96-bits of security.
2003-03-03 01:01:00 +00:00
The library will not warn you if you make this mistake so it is important to check yourself before using the
signatures.
2003-12-24 18:59:57 +00:00
\chapter { Digital Signature Algorithm}
\section { Introduction}
The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
reduce the bandwidth of a signature. For example, to have ``80-bits of security'' with ElGamal you need a group of
order at least 1024-bits. With DSA you need a group of order at least 160-bits. By comparison the ElGamal signature
would require at least 256 bytes where as the DSA signature would require only at least 40 bytes.
The API for the DSA is essentially the same as the other PK algorithms. Except in the case of DSA no encryption or
decryption routines are provided.
2005-06-09 00:08:13 +00:00
\section { Key Format}
Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
now so that others can interoperate with this library.
\begin { verbatim}
DSAPublicKey ::= SEQUENCE {
publicFlags BIT STRING(1), -- must be 0
g INTEGER , -- base generator, check that g^ q mod p == 1
-- and that 1 < g < p - 1
p INTEGER , -- prime modulus
q INTEGER , -- order of sub-group (must be prime)
y INTEGER , -- public key, specifically, g^ x mod p,
-- check that y^ q mod p == 1
-- and that 1 < y < p - 1
}
DSAPrivateKey ::= SEQUENCE {
publicFlags BIT STRING(1), -- must be 1
g INTEGER , -- base generator, check that g^ q mod p == 1
-- and that 1 < g < p - 1
p INTEGER , -- prime modulus
q INTEGER , -- order of sub-group (must be prime)
y INTEGER , -- public key, specifically, g^ x mod p,
-- check that y^ q mod p == 1
-- and that 1 < y < p - 1
x INTEGER -- private key
}
\end { verbatim}
The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys. This makes the structure uniquely decodable and easy
to work with.
2003-12-24 18:59:57 +00:00
\section { Key Generation}
To make a DSA key you must call the following function
\begin { verbatim}
int dsa_ make_ key(prng_ state *prng, int wprng,
int group_ size, int modulus_ size,
dsa_ key *key);
\end { verbatim}
The variable ``prng'' is an active PRNG state and ``wprng'' the index to the descriptor. ``group\_ size'' and
``modulus\_ size'' control the difficulty of forging a signature. Both parameters are in bytes. The larger the
``group\_ size'' the more difficult a forgery becomes upto a limit. The value of $ group \_ size $ is limited by
$ 15 < group \_ size < 1024 $ and $ modulus \_ size - group \_ size < 512 $ . Suggested values for the pairs are as follows.
\begin { center}
\begin { tabular} { |c|c|c|}
\hline \textbf { Bits of Security} & \textbf { group\_ size} & \textbf { modulus\_ size} \\
\hline 80 & 20 & 128 \\
\hline 120 & 30 & 256 \\
\hline 140 & 35 & 384 \\
\hline 160 & 40 & 512 \\
\hline
\end { tabular}
\end { center}
When you are finished with a DSA key you can call the following function to free the memory used.
2004-05-31 02:36:47 +00:00
\index { dsa\_ free()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
void dsa_ free(dsa_ key *key);
\end { verbatim}
\section { Key Verification}
Each DSA key is composed of the following variables.
\begin { enumerate}
\item $ q $ a small prime of magnitude $ 256 ^ { group \_ size } $ .
\item $ p = qr + 1 $ a large prime of magnitude $ 256 ^ { modulus \_ size } $ where $ r $ is a random even integer.
\item $ g = h ^ r \mbox { ( mod } p \mbox { ) } $ a generator of order $ q $ modulo $ p $ . $ h $ can be any non-trivial random
value. For this library they start at $ h = 2 $ and step until $ g $ is not $ 1 $ .
\item $ x $ a random secret (the secret key) in the range $ 1 < x < q $
\item $ y = g ^ x \mbox { ( mod } p \mbox { ) } $ the public key.
\end { enumerate}
A DSA key is considered valid if it passes all of the following tests.
\begin { enumerate}
\item $ q $ must be prime.
\item $ p $ must be prime.
\item $ g $ cannot be one of $ \lbrace - 1 , 0 , 1 \rbrace $ (modulo $ p $ ).
\item $ g $ must be less than $ p $ .
\item $ ( p - 1 ) \equiv 0 \mbox { ( mod } q \mbox { ) } $ .
\item $ g ^ q \equiv 1 \mbox { ( mod } p \mbox { ) } $ .
\item $ 1 < y < p - 1 $
\item $ y ^ q \equiv 1 \mbox { ( mod } p \mbox { ) } $ .
\end { enumerate}
Tests one and two ensure that the values will at least form a field which is required for the signatures to
function. Tests three and four ensure that the generator $ g $ is not set to a trivial value which would make signature
forgery easier. Test five ensures that $ q $ divides the order of multiplicative sub-group of $ \Z / p \Z $ . Test six
ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
is within range and belongs to a group of prime order. Note that test eight does not prove that $ g $ generated $ y $ only
that $ y $ belongs to a multiplicative sub-group of order $ q $ .
The following function will perform these tests.
2004-05-31 02:36:47 +00:00
\index { dsa\_ verify\_ key()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ verify_ key(dsa_ key *key, int *stat);
\end { verbatim}
This will test ``key'' and store the result in ``stat''. If the result is $ stat = 0 $ the DSA key failed one of the tests
and should not be used at all. If the result is $ stat = 1 $ the DSA key is valid (as far as valid mathematics are concerned).
\section { Signatures}
2005-11-18 05:15:37 +00:00
\subsection { Signature Generation}
2003-12-24 18:59:57 +00:00
To generate a DSA signature call the following function
2004-05-31 02:36:47 +00:00
\index { dsa\_ sign\_ hash()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ sign_ hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_ state *prng, int wprng, dsa_ key *key);
\end { verbatim}
Which will sign the data in ``in'' of length ``inlen'' bytes. The signature is stored in ``out'' and the size
of the signature in ``outlen''. If the signature is longer than the size you initially specify in ``outlen'' nothing
is stored and the function returns an error code. The DSA ``key'' must be of the \textbf { PK\_ PRIVATE} persuasion.
2005-11-18 05:15:37 +00:00
\subsection { Signature Verification}
2003-12-24 18:59:57 +00:00
To verify a hash created with that function use the following function
2004-05-31 02:36:47 +00:00
\index { dsa\_ verify\_ hash()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ verify_ hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long inlen,
int *stat, dsa_ key *key);
\end { verbatim}
Which will verify the data in ``hash'' of length ``inlen'' against the signature stored in ``sig'' of length ``siglen''.
It will set ``stat'' to $ 1 $ if the signature is valid, otherwise it sets ``stat'' to $ 0 $ .
2005-11-18 05:15:37 +00:00
\section { DSA Encrypt and Decrypt}
As of version 1.07 the DSA keys can be used to encrypt and decrypt small payloads. It works similar to the ECC encryption where
a shared key is computed and the hash of the shared key xor'ed against the plaintext forms the ciphertext.
\subsection { DSA Encryption}
This function will encrypt a small payload with a recipients public DSA key.
\index { dsa\_ encrypt\_ key()}
\begin { verbatim}
int dsa_ encrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_ state *prng, int wprng, int hash,
dsa_ key *key);
\end { verbatim}
This will encrypt the payload in ``in'' of length ``inlen'' and store the ciphertext in the output buffer ``out''. The
length of the ciphertext ``outlen'' must be originally set to the length of the output buffer. The DSA ``key'' can be
a public key.
\subsection { DSA Decryption}
\index { dsa\_ decrypt\_ key()}
\begin { verbatim}
int dsa_ decrypt_ key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
dsa_ key *key);
\end { verbatim}
This will decrypt the ciphertext ``in'' of length ``inlen'' and store the original payload in ``out'' of length ``outlen''. The DSA ``key'' must be a private key.
2003-12-24 18:59:57 +00:00
\section { Import and Export}
To export a DSA key so that it can be transported use the following function
2004-05-31 02:36:47 +00:00
\index { dsa\_ export()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ export(unsigned char *out, unsigned long *outlen,
int type,
dsa_ key *key);
\end { verbatim}
This will export the DSA ``key'' to the buffer ``out'' and set the length in ``outlen'' (which must have been previously
initialized to the maximum buffer size). The ``type`` variable may be either \textbf { PK\_ PRIVATE} or \textbf { PK\_ PUBLIC}
depending on whether you want to export a private or public copy of the DSA key.
To import an exported DSA key use the following function
2004-05-31 02:36:47 +00:00
\index { dsa\_ import()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ import(const unsigned char *in, unsigned long inlen,
dsa_ key *key);
\end { verbatim}
This will import the DSA key from the buffer ``in'' of length ``inlen'' to the ``key''. If the process fails the function
will automatically free all of the heap allocated in the process (you don't have to call dsa\_ free()).
2004-10-30 03:00:26 +00:00
\chapter { Standards Support}
2005-06-09 00:08:13 +00:00
\section { ASN.1 Formats}
LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
are all provided with three basic functions with \textit { similar} prototypes. One function has been dedicated to calculate the length in octets of a given
format and two functions have been dedicated to encoding and decoding the format.
2004-10-30 03:00:26 +00:00
2005-11-24 11:57:58 +00:00
On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types. They are provided
2005-06-09 00:08:13 +00:00
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
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
\index { ltc\_ asn1\_ list structure}
\begin { verbatim}
typedef struct {
2005-11-18 05:15:37 +00:00
int type;
void *data;
unsigned long size;
int used;
struct ltc_ asn1_ list_ *prev, *next,
*child, *parent;
2005-06-09 00:08:13 +00:00
} ltc_ asn1_ list;
\end { verbatim}
2004-10-30 03:00:26 +00:00
2005-11-18 05:15:37 +00:00
\index { LTC\_ SET\_ ASN1 macro}
2005-06-09 00:08:13 +00:00
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
2005-06-27 11:47:35 +00:00
``size'' field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type). The ``used'' field is primarily for the CHOICE decoder
and reflects if the particular member of a list was the decoded data type. To help build the lists in an orderly fashion the macro
2005-06-09 00:08:13 +00:00
``LTC\_ SET\_ ASN1(list, index, Type, Data, Size)'' has been provided.
It will assign to the ``index''th position in the ``list'' the tripplet (Type, Data, Size). An example usage would be:
\begin { small}
\begin { verbatim}
...
ltc_ asn1_ list sequence[3];
unsigned long three=3;
LTC_ SET_ ASN1(sequence, 0, LTC_ ASN1_ IA5_ STRING, "hello", 5);
LTC_ SET_ ASN1(sequence, 1, LTC_ ASN1_ SHORT_ INTEGER, & three, 1);
LTC_ SET_ ASN1(sequence, 2, LTC_ ASN1_ NULL, NULL, 0);
\end { verbatim}
\end { small}
The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
\begin { small}
\begin { verbatim}
...
ltc_ asn1_ list sequence[3];
unsigned long three=3;
int x=0;
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ IA5_ STRING, "hello", 5);
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ SHORT_ INTEGER, & three, 1);
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ NULL, NULL, 0);
\end { verbatim}
\end { small}
\begin { figure} [here]
\begin { center}
\begin { small}
\begin { tabular} { |l|l|}
\hline \textbf { Definition} & \textbf { ASN.1 Type} \\
\hline LTC\_ ASN1\_ EOL & End of a ASN.1 list structure. \\
\hline LTC\_ ASN1\_ INTEGER & INTEGER (uses mp\_ int) \\
\hline LTC\_ ASN1\_ SHORT\_ INTEGER & INTEGER (32--bit using unsigned long) \\
\hline LTC\_ ASN1\_ BIT\_ STRING & BIT STRING (one bit per char) \\
\hline LTC\_ ASN1\_ OCTET\_ STRING & OCTET STRING (one octet per char) \\
\hline LTC\_ ASN1\_ NULL & NULL \\
\hline LTC\_ ASN1\_ OBJECT\_ IDENTIFIER & OBJECT IDENTIFIER (words are in unsigned long) \\
\hline LTC\_ ASN1\_ IA5\_ STRING & IA5 STRING (one octet per char) \\
\hline LTC\_ ASN1\_ PRINTABLE\_ STRING & PRINTABLE STIRNG (one octet per char) \\
2005-06-27 11:47:35 +00:00
\hline LTC\_ ASN1\_ UTCTIME & UTCTIME (see ltc\_ utctime structure) \\
2005-11-24 11:57:58 +00:00
\hline LTC\_ ASN1\_ SEQUENCE & SEQUENCE (and SEQUENCE OF) \\
\hline LTC\_ ASN1\_ SET & SET \\
\hline LTC\_ ASN1\_ SETOF & SET OF \\
2005-06-27 11:47:35 +00:00
\hline LTC\_ ASN1\_ CHOICE & CHOICE \\
2005-06-09 00:08:13 +00:00
\hline
\end { tabular}
\caption { List of ASN.1 Supported Types}
\end { small}
\end { center}
\end { figure}
\subsection { SEQUENCE Type}
The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
\subsubsection { SEUQNECE Encoding}
To encode a sequence a \textbf { ltc\_ asn1\_ list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
with the following function.
\index { der\_ encode\_ sequence()}
\begin { verbatim}
int der_ encode_ sequence(ltc_ asn1_ list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
This encodes a sequence of items pointed to by ``list'' where the list has ``inlen'' items in it. The SEQUENCE will be encoded to ``out'' and of length ``outlen''. The
function will terminate when it reads all the items out of the list (upto ``inlen'') or it encounters an item in the list with a type of \textbf { LTC\_ ASN1\_ EOL} .
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
The ``data'' pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_ encode\_ bit\_ string()) and it is simply passed on
verbatim to the dependent encoder. The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions. In these cases
the ``data'' pointer is simply a pointer to another \textbf { ltc\_ asn1\_ list} .
\subsubsection { SEQUENCE Decoding}
\index { der\_ decode\_ sequence()}
Decoding a SEQUENCE is similar to encoding. You set up an array of \textbf { ltc\_ asn1\_ list} where in this case the ``size'' member is the maximum size
(in certain cases). For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the ``size'' field is updated after successful decoding to reflect how many
units of the respective type has been loaded.
\begin { verbatim}
int der_ decode_ sequence(const unsigned char *in, unsigned long inlen,
ltc_ asn1_ list *list, unsigned long outlen);
\end { verbatim}
This will decode upto ``outlen'' items from the input buffer ``in'' of length ``inlen'' octets. The function will stop (gracefully) when it runs out of items to decode.
It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occured.
For the following types the ``size'' field will be updated to reflect the number of units read of the given type.
\begin { enumerate}
\item BIT STRING
\item OCTET STRING
\item OBJECT IDENTIFIER
\item IA5 STRING
\item PRINTABLE STRING
\end { enumerate}
\subsubsection { SEQUENCE Length}
The length of a SEQUENCE can be determined with the following function.
\index { der\_ length\_ sequence()}
\begin { verbatim}
int der_ length_ sequence(ltc_ asn1_ list *list, unsigned long inlen,
unsigned long *outlen);
\end { verbatim}
This will get the encoding size for the given ``list'' of length ``inlen'' and store it in ``outlen''.
\subsubsection { SEQUENCE Multiple Argument Lists}
For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
\index { der\_ encode\_ sequence\_ multi()}
\index { der\_ decode\_ sequence\_ multi()}
\begin { verbatim}
int der_ encode_ sequence_ multi(unsigned char *out, unsigned long *outlen, ...);
int der_ decode_ sequence_ multi(const unsigned char *in, unsigned long inlen, ...);
\end { verbatim}
These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
The list of items are specified as a triple of the form ``(type, size, data)'' where ``type'' is an \textbf { int} , ``size'' is a \textbf { unsigned long}
and ``data'' is \textbf { void} pointer. The list of items must be terminated with an item with the type \textbf { LTC\_ ASN1\_ EOL} .
It's ideal that you cast the ``size'' values to unsigned long to ensure that the proper data type is passed to the function. Constants such as ``1'' without
a cast or prototype are of type \textbf { int} by default. Appending \textit { UL} or prepending \textit { (unsigned long)} is enough to cast it to the correct type.
2005-11-24 11:57:58 +00:00
\subsection { SET and SET OF}
\index { SET} \index { SET OF}
SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code. However, they are different and they should
be carefully noted. The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier) whereas the SET OF type is an ordered array of
a \textbf { single} ASN.1 object sorted in ascending order by the DER their respective encodings.
\subsubsection { SET Encoding}
SETs use the same array structure of ltc\_ asn1\_ list that the SEQUENCE functions use. They are encoded with the following function.
\index { der\_ encode\_ set()}
\begin { verbatim}
int der_ encode_ set(ltc_ asn1_ list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
This will encode the list of ASN.1 objects in ``list'' of length ``inlen'' objects and store the output in ``out'' of length ``outlen'' bytes. The function
will make a copy of the list provided and sort it by the TAG. Objects with identical TAGs are additionally sorted on their original placement in the
array (to make the process deterministic).
This function will \textbf { NOT} recognize ``DEFAULT'' objects and it is the responsibility of the caller to remove them as required.
\subsubsection { SET Decoding}
The SET type can be decoded with the following function.
\index { der\_ decode\_ set()}
\begin { verbatim}
int der_ decode_ set(const unsigned char *in, unsigned long inlen,
ltc_ asn1_ list *list, unsigned long outlen);
\end { verbatim}
This will decode the SET specified by ``list'' of length ``outlen'' objects from the input buffer ``in'' of length ``inlen'' octets.
It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.
\subsubsection { SET Length}
The length of a SET can be determined by calling der\_ length\_ sequence() since they have the same encoding length.
\subsubsection { SET OF Encoding}
A ``SET OF'' object is an array of identifical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object. They are
used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_ asn1\_ list that the SEQUENCE functions
use. They are encoded with the following function.
\index { der\_ encode\_ setof()}
\begin { verbatim}
int der_ encode_ setof(ltc_ asn1_ list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
This will encode a ``SET OF'' containing the ``list'' of ``inlen'' ASN.1 objects and store the encoding in the output buffer ``out'' of length ``outlen''.
The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer. This
means you need at least enough memory to keep an additional copy of the output on the heap.
\subsubsection { SET OF Decoding}
Since the decoding of a ``SET OF'' object is unambiguous it can be decoded with der\_ decode\_ sequence().
\subsubsection { SET OF Length}
Like the SET type the der\_ length\_ sequence() function can be used to determine the length of a ``SET OF'' object.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 INTEGER}
2005-06-09 00:08:13 +00:00
To encode or decode INTEGER data types use the following functions.
\index { der\_ encode\_ integer()}
\index { der\_ decode\_ integer()}
2004-10-30 03:00:26 +00:00
\index { der\_ length\_ integer()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
int der_ encode_ integer(mp_ int *num, unsigned char *out, unsigned long *outlen);
int der_ decode_ integer(const unsigned char *in, unsigned long inlen, mp_ int *num);
2004-10-30 03:00:26 +00:00
int der_ length_ integer(mp_ int *num, unsigned long *len);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
These will encode or decode a signed INTEGER data type using the ``mp\_ int'' data type to store the large INTEGER. To encode smaller values without allocating
an mp\_ int to store the value the ``short'' INTEGER functions were made available.
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ short\_ integer()}
\index { der\_ decode\_ short\_ integer()}
\index { der\_ length\_ short\_ integer()}
\begin { verbatim}
int der_ encode_ short_ integer(unsigned long num,
unsigned char *out, unsigned long *outlen);
int der_ decode_ short_ integer(const unsigned char *in, unsigned long inlen,
unsigned long *num);
int der_ length_ short_ integer(unsigned long num, unsigned long *outlen);
\end { verbatim}
These will encode or decode an unsigned \textbf { unsigned long} type (only reads upto 32--bits). For values in the range $ 0 \dots 2 ^ { 32 } - 1 $ the integer
and short integer functions can encode and decode each others outputs.
2004-10-30 03:00:26 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 BIT STRING}
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ bit\_ string()}
\index { der\_ decode\_ bit\_ string()}
\index { der\_ length\_ bit\_ string()}
2004-10-30 03:00:26 +00:00
\begin { verbatim}
2005-06-09 00:08:13 +00:00
int der_ encode_ bit_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
int der_ decode_ bit_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
int der_ length_ bit_ string(unsigned long nbits, unsigned long *outlen);
\end { verbatim}
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf { char} per bit. A non--zero value will be interpretted
as a one bit and a zero value a zero bit.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 OCTET STRING}
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ octet\_ string()}
\index { der\_ decode\_ octet\_ string()}
\index { der\_ length\_ octet\_ string()}
\begin { verbatim}
int der_ encode_ octet_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ decode_ octet_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ length_ octet_ string(unsigned long noctets, unsigned long *outlen);
\end { verbatim}
These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf { char} each.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 OBJECT IDENTIFIER}
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ object\_ identifier()}
\index { der\_ decode\_ object\_ identifier()}
\index { der\_ length\_ object\_ identifier()}
\begin { verbatim}
int der_ encode_ object_ identifier(unsigned long *words, unsigned long nwords,
unsigned char *out, unsigned long *outlen);
int der_ decode_ object_ identifier(const unsigned char *in, unsigned long inlen,
unsigned long *words, unsigned long *outlen);
int der_ length_ object_ identifier(unsigned long *words, unsigned long nwords,
unsigned long *outlen);
2004-10-30 03:00:26 +00:00
\end { verbatim}
2005-06-09 00:08:13 +00:00
These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf { unsigned long} elements and must be in the range
$ 0 \ldots 2 ^ { 32 } - 1 $ .
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 IA5 STRING}
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ ia5\_ string()}
\index { der\_ decode\_ ia5\_ string()}
\index { der\_ length\_ ia5\_ string()}
\begin { verbatim}
int der_ encode_ ia5_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ decode_ ia5_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ length_ ia5_ string(const unsigned char *octets, unsigned long noctets,
unsigned long *outlen);
\end { verbatim}
These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf { char} elements. This functions performs internal character
to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_ 32 machine 'A' == 65 but the same may not be true on
say a SPARC machine. Internally these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
that the build platform honours the runtime platforms character conventions.
If you're worried try building the test suite and running it. It has hard coded test vectors to ensure it is operating properly.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 PRINTABLE STRING}
2005-06-09 00:08:13 +00:00
\index { der\_ encode\_ printable\_ string()}
\index { der\_ decode\_ printable\_ string()}
\index { der\_ length\_ printable\_ string()}
\begin { verbatim}
int der_ encode_ printable_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ decode_ printable_ string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_ length_ printable_ string(const unsigned char *octets, unsigned long noctets,
unsigned long *outlen);
\end { verbatim}
These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf { char} elements. This functions performs internal character
to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_ 32 machine 'A' == 65 but the same may not be true on
say a SPARC machine. Internally these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
that the build platform honours the runtime platforms character conventions.
If you're worried try building the test suite and running it. It has hard coded test vectors to ensure it is operating properly.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 UTCTIME}
The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
\begin { verbatim}
typedef struct {
unsigned YY, /* year 00--99 */
MM, /* month 01--12 */
DD, /* day 01--31 */
hh, /* hour 00--23 */
mm, /* minute 00--59 */
ss, /* second 00--59 */
off_ dir, /* timezone offset direction 0 == +, 1 == - */
off_ hh, /* timezone offset hours */
off_ mm; /* timezone offset minutes */
} ltc_ utctime;
\end { verbatim}
The time can be offset plus or minus a set amount of hours (off\_ hh) and minutes (off\_ mm). When ``off\_ dir'' is zero the time will be added otherwise it
will be subtracted.
For instance, the array $ \lbrace 5 , 6 , 20 , 22 , 4 , 00 , 0 , 5 , 0 \rbrace $ represents the current time of 2005, June 20th, 22:04:00 with a time offset of +05h00.
\index { der\_ encode\_ utctime()}
\index { der\_ decode\_ utctime()}
\index { der\_ length\_ utctime()}
\begin { verbatim}
int der_ encode_ utctime(ltc_ utctime *utctime,
unsigned char *out, unsigned long *outlen);
int der_ decode_ utctime(const unsigned char *in, unsigned long *inlen,
ltc_ utctime *out);
int der_ length_ utctime(ltc_ utctime *utctime, unsigned long *outlen);
\end { verbatim}
The encoder will store time in one of the two ASN.1 formats, either ``YYMMDDhhmmssZ'' or ``YYMMDDhhmmss$ \pm $ hhmm'' and perform minimal error checking on the
input. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
\subsection { ASN.1 CHOICE}
The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a ``ltc\_ asn1\_ list''. There is no encoder for the CHOICE type, only a
decoder. The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet. The list can contain any ASN.1 data
type\footnote { Except it cannot have LTC\_ ASN1\_ INTEGER and LTC\_ ASN1\_ SHORT\_ INTEGER simultaneously.} except for other CHOICE types.
There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
\index { der\_ decode\_ choice()}
\begin { verbatim}
int der_ decode_ choice(const unsigned char *in, unsigned long *inlen,
ltc_ asn1_ list *list, unsigned long outlen);
\end { verbatim}
This will decode the input in the ``in'' field of length ``inlen''. It uses the provided ASN.1 list specified in the ``list'' field which has ``outlen'' elements.
The ``inlen'' field will be updated with the length of the decoded data type as well as the respective entry in the ``list'' field will have the ``used'' flag
set to non--zero to reflect it was the data type decoded.
2005-06-09 00:08:13 +00:00
2005-11-18 05:15:37 +00:00
\subsection { ASN.1 Flexi Decoder}
The ASN.1 ``flexi'' decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
the structure of the data. Where der\_ decode\_ sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
free form.
The flexi decoder uses the same ``ltc\_ asn1\_ list'' but instead of being stored in an array it uses the linked list pointers ``prev'', ``next'', ``parent''
and ``child''. The list works as a ``doubly-linked list'' structure where decoded items at the same level are sibblings (using next and prev) and items
encoded in a SEQUENCE are stored as a child element.
2005-11-24 11:57:58 +00:00
When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibbling (e.g. list.type == LTC\_ ASN1\_ SEQUENCE) and the child
pointer points to a new list of items contained within the object.
2005-11-18 05:15:37 +00:00
\index { der\_ decode\_ sequence\_ flexi()}
\begin { verbatim}
int der_ decode_ sequence_ flexi(const unsigned char *in, unsigned long *inlen,
ltc_ asn1_ list **out);
\end { verbatim}
This will decode items in the ``in'' buffer of max input length ``inlen'' and store the newly created pointer to the list in ``out''. This function allocates
all required memory for the decoding. It stores the number of octets read back into ``inlen''.
The function will terminate when either it hits an invalid ASN.1 type octet or it reads ``inlen'' octets. An early terminate is a soft error and returns
normally. The decoded list ``out'' will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf { NULL} ).
An invalid decoding will terminate the process and free the allocated memory automatically.
\textbf { Note} that the list decoded by this function is \textbf { NOT} in the correct form for der\_ encode\_ sequence() to use directly. You will have to first
have to convert the list by first storing all of the sibblings in an array then storing all the children as sub-lists of a sequence using the ``.data''
pointer. Currently no function in LibTomCrypt provides this ability.
To free the list use the following function.
\index { der\_ sequence\_ free()}
\begin { verbatim}
void der_ sequence_ free(ltc_ asn1_ list *in);
\end { verbatim}
This will free all of the memory allocated by der\_ decode\_ sequence\_ flexi().
2004-10-30 03:00:26 +00:00
\section { Password Based Cryptography}
\subsection { PKCS \# 5}
2005-06-09 00:08:13 +00:00
\index { PKCS \# 5}
2004-10-30 03:00:26 +00:00
In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \# 5 was drafted. PKCS \# 5
is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
for completeness. Algorithm Two is a bit more modern and more flexible to work with.
\subsection { Algorithm One}
Algorithm One accepts as input a password, an 8--byte salt and an iteration counter. The iteration counter is meant to act as delay for
people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
algorithm and produces an output no longer than the output of the hash.
\index { pkcs\_ 5\_ alg1()}
\begin { alltt}
int pkcs_ 5_ alg1(const unsigned char *password, unsigned long password_ len,
const unsigned char *salt,
int iteration_ count, int hash_ idx,
unsigned char *out, unsigned long *outlen)
\end { alltt}
Where ``password'' is the users password. Since the algorithm allows binary passwords you must also specify the length in ``password\_ len''.
The ``salt'' is a fixed size 8--byte array which should be random for each user and session. The ``iteration\_ count'' is the delay desired
on the password. The ``hash\_ idx'' is the index of the hash you wish to use in the descriptor table.
The output of length upto ``outlen'' is stored in ``out''. If ``outlen'' is initially larger than the size of the hash functions output
it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in ``out''.
\subsection { Algorithm Two}
Algorithm Two is the recommended algorithm for this task. It allows variable length salts and can produce outputs larger than the
hash functions output. As such it can easily be used to derive session keys for ciphers and MACs as well initial vectors as required
from a single password and invokation of this algorithm.
\index { pkcs\_ 5\_ alg2()}
\begin { alltt}
int pkcs_ 5_ alg2(const unsigned char *password, unsigned long password_ len,
const unsigned char *salt, unsigned long salt_ len,
int iteration_ count, int hash_ idx,
unsigned char *out, unsigned long *outlen)
\end { alltt}
Where ``password'' is the users password. Since the algorithm allows binary passwords you must also specify the length in ``password\_ len''.
The ``salt'' is an array of size ``salt\_ len''. It should be random for each user and session. The ``iteration\_ count'' is the delay desired
on the password. The ``hash\_ idx'' is the index of the hash you wish to use in the descriptor table. The output of length upto
``outlen'' is stored in ``out''.
\begin { alltt}
/* demo to show how to make session state material from a password */
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-10-30 03:00:26 +00:00
int main(void)
\{
unsigned char password[100], salt[100],
cipher_ key[16], cipher_ iv[16],
mac_ key[16], outbuf[48];
int err, hash_ idx;
unsigned long outlen, password_ len, salt_ len;
/* register hash and get it's idx .... */
/* get users password and make up a salt ... */
/* create the material (100 iterations in algorithm) */
outlen = sizeof(outbuf);
if ((err = pkcs_ 5_ alg2(password, password_ len, salt, salt_ len,
100, hash_ idx, outbuf, & outlen)) != CRYPT_ OK) \{
/* error handle */
\}
/* now extract it */
memcpy(cipher_ key, outbuf, 16);
memcpy(cipher_ iv, outbuf+16, 16);
memcpy(mac_ key, outbuf+32, 16);
/* use material (recall to store the salt in the output) */
\}
\end { alltt}
2003-03-03 00:59:24 +00:00
\chapter { Miscellaneous}
\section { Base64 Encoding and Decoding}
The library provides functions to encode and decode a RFC1521 base64 coding scheme. This means that it can decode what it
encodes but the format used does not comply to any known standard. The characters used in the mappings are:
\begin { verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
\end { verbatim}
Those characters should are supported in virtually any 7-bit ASCII system which means they can be used for transport over
common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
original input. After the first four characters is the rest of the message.
Often it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
break up the first four characters.
To encode a binary string in base64 call:
\index { base64\_ encode()} \index { base64\_ decode()}
\begin { verbatim}
int base64_ encode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
Where ``in'' is the binary string and ``out'' is where the ASCII output is placed. You must set the value of ``outlen'' prior
to calling this function and it sets the length of the base64 output in ``outlen'' when it is done. To decode a base64
string call:
\begin { verbatim}
int base64_ decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
\end { verbatim}
2005-08-01 16:36:47 +00:00
\section { Primality Testing}
2003-03-03 00:59:24 +00:00
\index { Primality Testing}
The library includes primality testing and random prime functions as well. The primality tester will perform the test in
2003-03-03 01:01:00 +00:00
two phases. First it will perform trial division by the first few primes. Second it will perform eight rounds of the
2003-03-03 00:59:24 +00:00
Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
the probability of a pseudo-prime by $ 1 \over 4 $ therefore after sixteen rounds the probability is no more than
2003-03-03 01:01:00 +00:00
$ \left ( { 1 \over 4 } \right ) ^ { 8 } = 2 ^ { - 16 } $ . In practice the probability of error is in fact much lower than that.
When making random primes the trial division step is in fact an optimized implementation of ``Implementation of Fast RSA Key Generation on Smart Cards''\footnote { Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel} .
In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candiate
is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
math operations. As a result the routine can scan ahead to the next number required for testing with very little work
involved.
In the event that a composite did make it through it would most likely cause the the algorithm trying to use it to fail. For
instance, in RSA two primes $ p $ and $ q $ are required. The order of the multiplicative sub-group (modulo $ pq $ ) is given
as $ \phi ( pq ) $ or $ ( p - 1 ) ( q - 1 ) $ . The decryption exponent $ d $ is found as $ de \equiv 1 \mbox { } ( \mbox { mod } \phi ( pq ) ) $ . If either $ p $ or $ q $ is composite the value of $ d $ will be incorrect and the user
2003-03-03 00:59:24 +00:00
will not be able to sign or decrypt messages at all. Suppose $ p $ was prime and $ q $ was composite this is just a variation of
the multi-prime RSA. Suppose $ q = rs $ for two primes $ r $ and $ s $ then $ \phi ( pq ) = ( p - 1 ) ( r - 1 ) ( s - 1 ) $ which clearly is
not equal to $ ( p - 1 ) ( rs - 1 ) $ .
2003-03-13 02:12:16 +00:00
These are not technically part of the LibTomMath library but this is the best place to document them.
To test if a ``mp\_ int'' is prime call:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int is_ prime(mp_ int *N, int *result);
\end { verbatim}
This puts a one in ``result'' if the number is probably prime, otherwise it places a zero in it. It is assumed that if
it returns an error that the value in ``result'' is undefined. To make
a random prime call:
\begin { verbatim}
int rand_ prime(mp_ int *N, unsigned long len, prng_ state *prng, int wprng);
\end { verbatim}
2003-03-03 01:01:00 +00:00
Where ``len'' is the size of the prime in bytes ($ 2 \le len \le 256 $ ). You can set ``len'' to the negative size you want
2003-03-03 00:59:24 +00:00
to get a prime of the form $ p \equiv 3 \mbox { } ( \mbox { mod } 4 ) $ . So if you want a 1024-bit prime of this sort pass
``len = -128'' to the function. Upon success it will return { \bf CRYPT\_ OK} and ``N'' will contain an integer which
is very likely prime.
\chapter { Programming Guidelines}
\section { Secure Pseudo Random Number Generators}
Probably the singal most vulnerable point of any cryptosystem is the PRNG. Without one generating and protecting secrets
would be impossible. The requirement that one be setup correctly is vitally important and to address this point the library
does provide two RNG sources that will address the largest amount of end users as possible. The ``sprng'' PRNG provided
provides and easy to access source of entropy for any application on a *NIX or Windows computer.
However, when the end user is not on one of these platforms the application developer must address the issue of finding
entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
\section { Preventing Trivial Errors}
Two simple ways to prevent trivial errors is to prevent overflows and to check the return values. All of the functions
which output variable length strings will require you to pass the length of the destination. If the size of your output
buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
Also virtually all of the functions return an error code or { \bf CRYPT\_ OK} . You should detect all errors as simple
typos or such can cause algorithms to fail to work as desired.
\section { Registering Your Algorithms}
To avoid linking and other runtime errors it is important to register the ciphers, hashes and PRNGs you intend to use
before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
write the few functions required plus a descriptor. After registering your PRNG all of the library functions that
need a PRNG can instantly take advantage of it.
\section { Key Sizes}
\subsection { Symmetric Ciphers}
For symmetric ciphers use as large as of a key as possible. For the most part ``bits are cheap'' so using a 256-bit key
is not a hard thing todo.
\subsection { Assymetric Ciphers}
The following chart gives the work factor for solving a DH/RSA public key using the NFS. The work factor for a key of order
$ n $ is estimated to be
\begin { equation}
e^ { 1.923 \cdot ln(n)^ { 1 \over 3} \cdot ln(ln(n))^ { 2 \over 3} }
\end { equation}
Note that $ n $ is not the bit-length but the magnitude. For example, for a 1024-bit key $ n = 2 ^ { 1024 } $ . The work required
is:
\begin { center}
\begin { tabular} { |c|c|}
\hline RSA/DH Key Size (bits) & Work Factor ($ log _ 2 $ ) \\
\hline 512 & 63.92 \\
\hline 768 & 76.50 \\
\hline 1024 & 86.76 \\
\hline 1536 & 103.37 \\
\hline 2048 & 116.88 \\
\hline 2560 & 128.47 \\
\hline 3072 & 138.73 \\
\hline 4096 & 156.49 \\
\hline
\end { tabular}
\end { center}
The work factor for ECC keys is much higher since the best attack is still fully exponentional. Given a key of magnitude
$ n $ it requires $ \sqrt n $ work. The following table sumarizes the work required:
\begin { center}
\begin { tabular} { |c|c|}
\hline ECC Key Size (bits) & Work Factor ($ log _ 2 $ ) \\
\hline 192 & 96 \\
\hline 224 & 112 \\
\hline 256 & 128 \\
\hline 384 & 192 \\
\hline 521 & 260.5 \\
\hline
\end { tabular}
\end { center}
Using the above tables the following suggestions for key sizes seems appropriate:
\begin { center}
\begin { tabular} { |c|c|c|}
\hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
\hline Short term (less than a year) & 1024 & 160 \\
\hline Short term (less than five years) & 1536 & 192 \\
\hline Long Term (less than ten years) & 2560 & 256 \\
\hline
\end { tabular}
\end { center}
\section { Thread Safety}
The library is not thread safe but several simple precautions can be taken to avoid any problems. The registry functions
such as register\_ cipher() are not thread safe no matter what you do. Its best to call them from your programs initializtion
code before threads are initiated.
The rest of the code uses state variables you must pass it such as hash\_ state, hmac\_ state, etc. This means that if each
thread has its own state variables then they will not affect each other. This is fairly simple with symmetric ciphers
and hashes. However, the keyring and PRNG support is something the threads will want to share. The simplest workaround
is create semaphores or mutexes around calls to those functions.
Since C does not have standard semaphores this support is not native to Libtomcrypt. Even a C based semaphore is not entire
possible as some compilers may ignore the ``volatile'' keyword or have multiple processors. Provide your host application
is modular enough putting the locks in the right place should not bloat the code significantly and will solve all thread
safety issues within the library.
2004-10-30 03:00:26 +00:00
\chapter { Configuring and Building the Library}
2003-03-03 00:59:24 +00:00
\section { Introduction}
The library is fairly flexible about how it can be built, used and generally distributed. Additions are being made with
2004-10-30 03:00:26 +00:00
each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
the build process to make a smaller library. This is particularly useful for shared libraries.
2005-08-01 16:36:47 +00:00
As of v1.06 of the library the build process has been moved to two steps for the typical LibTomCrypt application. This is because
LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath or TomsFastMath).
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
The build process now consists of installing a math library first then building and installing LibTomCrypt with a math library
configured. Note that LibTomCrypt can be built with no internal math descriptors. This means that one must be provided at either
build or run time for the application. LibTomCrypt comes with two math descriptors that provide a standard interface to math
libraries. One for LibTomMath and one for TomsFastMath.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\section { Makefile variables}
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process. Most of the
settings can be overwritten from the command line which makes custom installation a breeze.
2004-10-30 03:00:26 +00:00
2005-11-18 05:15:37 +00:00
\index { MAKE}
\index { CC}
\index { AR}
\subsection { MAKE, CC and AR}
The MAKE, CC and AR flags can all be overwritten. They default to ``make'', ``\$ CC'' and ``\$ AR'' respectively.
Changing MAKE allows you to change what program will be invoked to handle sub--directories. E.g.
\begin { verbatim}
MAKE=gmake gmake install
\end { verbatim}
Will build and install the libraries with the ``gmake'' tool. Similarly
\begin { verbatim}
CC=arm-gcc AR=arm-ar make
\end { verbatim}
Will build the library using ``arm--gcc'' as the compiler and ``arm--ar'' as the archiver.
2005-08-01 16:36:47 +00:00
\subsection { IGNORE\_ SPEED}
\index { IGNORE\_ SPEED}
When \textbf { IGNORE\_ SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
CFLAGS on the command line. E.g. to add debugging
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\begin { verbatim}
CFLAGS="-g3" make IGNORE_ SPEED=1
\end { verbatim}
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
This will turn off optimizations and add ``-g3'' to the CFLAGS which enables debugging.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\subsection { LIBNAME and LIBNAME\_ S}
\index { LIBNAME} \index { LIBNAME\_ S}
\textbf { LIBNAME} is the name of the output library (archive) to create. It defaults to ``libtomcrypt.a'' for static builds and ``libtomcrypt.la'' for
shared. The \textbf { LIBNAME\_ S} variable is the static name while doing shared builds. Ideally they should have the same prefix but don't have to.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\index { LIBTEST} \index { LIBTEST\_ S}
Similarly \textbf { LIBTEST} and \textbf { LIBTEST\_ S} are the names for the profiling and testing library. The default is ``libtomcrypt\_ prof.a'' for
static and ``libtomcrypt\_ prof.la'' for shared.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\subsection { Installation Directories}
\index { DESTDIR} \index { LIBPATH} \index { INCPATH} \index { DATADIR}
\textbf { DESTDIR} is the prefix for the installation directories. It defaults to an empty string. \textbf { LIBPATH} is the prefix for the library
directory which defaults to ``/usr/lib''. \textbf { INCPATH} is the prefix for the header file directory which defaults to ``/usr/include''.
\textbf { DATADIR} is the prefix for the data (documentation) directory which defaults to ``/usr/share/doc/libtomcrypt/pdf''.
All four can be used to create custom install locations depending on the nature of the OS and file system in use.
\begin { verbatim}
2005-11-18 05:15:37 +00:00
make LIBPATH=/home/tom/project/lib INCPATH=/home/tom/project/include \
DATAPATH=/home/tom/project/docs install
2005-08-01 16:36:47 +00:00
\end { verbatim}
This will build the library and install it to the directories under ``/home/tom/project/''. e.g.
\begin { small}
\begin { verbatim}
/home/tom/project/:
total 1
drwxr-xr-x 2 tom users 80 Jul 30 16:02 docs
drwxr-xr-x 2 tom users 528 Jul 30 16:02 include
drwxr-xr-x 2 tom users 80 Jul 30 16:02 lib
/home/tom/project/docs:
total 452
-rwxr-xr-x 1 tom users 459009 Jul 30 16:02 crypt.pdf
/home/tom/project/include:
total 132
-rwxr-xr-x 1 tom users 2482 Jul 30 16:02 tomcrypt.h
-rwxr-xr-x 1 tom users 702 Jul 30 16:02 tomcrypt_ argchk.h
-rwxr-xr-x 1 tom users 2945 Jul 30 16:02 tomcrypt_ cfg.h
-rwxr-xr-x 1 tom users 22763 Jul 30 16:02 tomcrypt_ cipher.h
-rwxr-xr-x 1 tom users 5174 Jul 30 16:02 tomcrypt_ custom.h
-rwxr-xr-x 1 tom users 11314 Jul 30 16:02 tomcrypt_ hash.h
-rwxr-xr-x 1 tom users 11571 Jul 30 16:02 tomcrypt_ mac.h
-rwxr-xr-x 1 tom users 13614 Jul 30 16:02 tomcrypt_ macros.h
-rwxr-xr-x 1 tom users 14714 Jul 30 16:02 tomcrypt_ math.h
-rwxr-xr-x 1 tom users 632 Jul 30 16:02 tomcrypt_ misc.h
-rwxr-xr-x 1 tom users 10934 Jul 30 16:02 tomcrypt_ pk.h
-rwxr-xr-x 1 tom users 2634 Jul 30 16:02 tomcrypt_ pkcs.h
-rwxr-xr-x 1 tom users 7067 Jul 30 16:02 tomcrypt_ prng.h
-rwxr-xr-x 1 tom users 1467 Jul 30 16:02 tomcrypt_ test.h
/home/tom/project/lib:
total 1073
-rwxr-xr-x 1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
\end { verbatim}
\end { small}
\section { Extra libraries}
\index { EXTRALIBS}
\textbf { EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
that GCC expects for global archives.
\begin { verbatim}
CFLAGS="-DTFM_ DESC -DUSE_ TFM" EXTRALIBS=-ltfm make install test timing
\end { verbatim}
This will install the library using the TomsFastMath library and link the ``libtfm.a'' library out of the default library search path. The two
defines are explained below. You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
the \textbf { EXTRALIBS} variable by separating them by a space.
Note that \textbf { EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
\section { Building a Static Library}
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
\begin { verbatim}
CFLAGS="-DTFM_ DESC" make install
\end { verbatim}
That will build LibTomCrypt (including the TomsFastMath descriptor) and install it in the default locations indicated previously. You can enable
the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly you can build the library with no built--in
math descriptors.
\begin { verbatim}
make install
\end { verbatim}
In this case no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
public key functions.
Note that even if you include the built--in descriptors you must link against the source library as well.
\begin { verbatim}
gcc -DTFM_ DESC myprogram.c -ltomcrypt -ltfm -o myprogram
\end { verbatim}
This will compile ``myprogram'' and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
we define \textbf { TFM\_ DESC} for compilation. This is so that the TFM descriptor symbol will be defined for the client application to make use of without
giving warnings.
2004-10-30 03:00:26 +00:00
\section { Building a Shared Library}
2005-08-01 16:36:47 +00:00
LibTomCrypt can also be built as a shared library through the ``makefile.shared'' make script. It is similar to use as the static script except
that you \textbf { must} specify the \textbf { EXTRALIBS} variable at install time.
\begin { verbatim}
2005-11-18 05:15:37 +00:00
CFLAGS="-DTFM_ DESC" EXTRALIBS=-ltfm make -f makefile.shared install
2005-08-01 16:36:47 +00:00
\end { verbatim}
2005-11-18 05:15:37 +00:00
This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
shared build process requires libtool to be installed.
2004-10-30 03:00:26 +00:00
2005-04-19 11:30:30 +00:00
\section { tomcrypt\_ cfg.h}
The file ``tomcrypt\_ cfg.h'' is what lets you control various high level macros which control the behaviour
2004-10-30 03:00:26 +00:00
of the library.
2003-03-03 00:59:24 +00:00
\subsubsection { ARGTYPE}
This lets you control how the \_ ARGCHK macro will behave. The macro is used to check pointers inside the functions against
NULL. There are three settings for ARGTYPE. When set to 0 it will have the default behaviour of printing a message to
stderr and raising a SIGABRT signal. This is provided so all platforms that use libtomcrypt can have an error that functions
2005-08-01 16:36:47 +00:00
similarly. When set to 1 it will simply pass on to the assert() macro. When set to 2 the macro will display the error to
stderr then return execution to the caller. This could lead to a segmentation fault (e.g. when a pointer is \textbf { NULL} ) but is useful
if you handle signals on your own. When set to 3 it will resolve to a empty macro and no error checking will be performed.
2003-03-03 00:59:24 +00:00
\subsubsection { Endianess}
2005-08-01 16:36:47 +00:00
There are five macros related to endianess issues. For little endian platforms define, \textbf { ENDIAN\_ LITTLE} . For big endian
platforms define \textbf { ENDIAN\_ BIG} . Similarly when the default word size of an ``unsigned long'' is 32-bits define \textbf { ENDIAN\_ 32BITWORD}
or define \textbf { ENDIAN\_ 64BITWORD} when its 64-bits. If you do not define any of them the library will automatically use \textbf { ENDIAN\_ NEUTRAL}
2004-10-30 03:00:26 +00:00
which will work on all platforms.
2005-08-01 16:36:47 +00:00
Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.
2003-03-03 00:59:24 +00:00
2003-03-13 02:12:16 +00:00
\section { The Configure Script}
2005-04-19 11:30:30 +00:00
There are also options you can specify from the configure script or ``tomcrypt\_ custom.h''.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { X memory routines}
2005-04-19 11:30:30 +00:00
At the top of tomcrypt\_ custom.h are four macros denoted as XMALLOC, XCALLOC, XREALLOC and XFREE which resolve to
2004-10-30 03:00:26 +00:00
the name of the respective functions. This lets you substitute in your own memory routines. If you substitute in
your own functions they must behave like the standard C library functions in terms of what they expect as input and
output. By default the library uses the standard C routines.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { X clock routines}
2003-03-03 00:59:24 +00:00
The rng\_ get\_ bytes() function can call a function that requires the clock() function. These macros let you override
the default clock() used with a replacement. By default the standard C library clock() function is used.
2005-04-17 11:37:13 +00:00
\subsection { NO\_ FILE}
2003-03-03 00:59:24 +00:00
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
2004-10-30 03:00:26 +00:00
functions and instead simply return CRYPT\_ NOP. This should help resolve any linker errors stemming from a lack of
2003-03-03 00:59:24 +00:00
file I/O on embedded platforms.
2005-04-17 11:37:13 +00:00
\subsection { CLEAN\_ STACK}
2004-10-30 03:00:26 +00:00
When this functions is defined the functions that store key material on the stack will clean up afterwards.
Assumes that you have no memory paging with the stack.
2005-04-17 11:37:13 +00:00
\subsection { LTC\_ TEST}
2004-10-30 03:00:26 +00:00
When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.
When this has been undefined the tests are removed and if called will return CRYPT\_ NOP.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
2004-10-30 03:00:26 +00:00
There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
cipher and a hash function.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
Also see technical note number five for more details.
2005-04-17 11:37:13 +00:00
\subsection { TWOFISH\_ SMALL and TWOFISH\_ TABLES}
2003-03-03 00:59:24 +00:00
Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
to allow some tradeoffs in the implementation. When TWOFISH\_ SMALL is defined the scheduled symmetric key for Twofish
requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
tables at a cost of 4KB of memory. The cipher will be much faster as a result.
When TWOFISH\_ TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
useful when TWOFISH\_ SMALL is defined as the table values are computed on the fly. When this is defined the code size
will increase by approximately 500 bytes. If this is defined but TWOFISH\_ SMALL is not the cipher will still work but
it will not speed up the encryption or decryption functions.
2005-04-17 11:37:13 +00:00
\subsection { GCM\_ TABLES}
2005-06-27 11:47:35 +00:00
When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
It also increases the initialization time and isn't suitable when you are going to use a key a few times only.
2005-04-17 11:37:13 +00:00
\subsection { SMALL\_ CODE}
2003-03-03 01:01:40 +00:00
When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
These variants are slower but can save quite a bit of code space.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { LTC\_ FAST}
This mode (autodetected with x86\_ 32,x86\_ 64 platforms with GCC or MSVC) configures various routines such as ctr\_ encrypt() or
cbc\_ encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
cutting down the overhead of the respective functions.
This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_ FAST
is not ``portable'' since unaligned accesses are not covered by the ISO C specifications.
In practice however, you can use it on pretty much any platform (even MIPS) with care.
By design the ``fast'' mode functions won't get unaligned on their own. For instance, if you call ctr\_ encrypt() right after calling
ctr\_ start() and all the inputs you gave are aligned than ctr\_ encrypt() will perform aligned memory operations only. However, if you
call ctr\_ encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
whole word XOR operations. These operations will be unaligned.
The simplest precaution is to make sure you process all data in power of two blocks and handle ``remainder'' at the end. e.g. If you are
CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.
If you do plan on using the ``LTC\_ FAST'' mode you have to also define a ``LTC\_ FAST\_ TYPE'' macro which resolves to an optimal sized
data type you can perform integer operations with. Ideally it should be four or eight bytes since it must properly divide the size
of your block cipher (e.g. 16 bytes for AES). This means sadly if you're on a platform with 57--bit words (or something) you can't
use this mode. So sad.
2005-06-27 11:47:35 +00:00
\subsection { LTC\_ PTHREAD}
When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
Generally the rule of thumb is to setup the tables once at startup and then leave them be. This added build flag simply makes updating
the tables safer.
2005-08-01 16:36:47 +00:00
\subsection { LTC\_ ECC\_ TIMING\_ RESISTANT}
When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multipication
algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
where timing side channels pose a significant threat.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\subsection { Math Descriptors}
The library comes with two math descriptors that allow you to interface the public key cryptography api to freely available math
libraries. In this case LibTomMath and TomsFastMath. When either of \textbf { LTM\_ DESC} or \textbf { TFM\_ DESC} are defined
descriptors for the respective library are built and included in the library as ``ltm\_ desc'' or ``tfm\_ desc'' respectively.
In the test demos that use the libraries the additional flags \textbf { USE\_ LTM} and \textbf { USE\_ TFM} can be defined
to tell the program which library to use. They cannot both be defined at once.
\index { LTM\_ DESC} \index { TFM\_ DESC} \index { USE\_ LTM} \index { USE\_ TFM}
\begin { small}
\begin { verbatim}
CFLAGS="-DLTM_ DESC -DTFM_ DESC -DUSE_ TFM" EXTRALIBS="-ltommath -ltfm"
make -f makefile.shared install timing
\end { verbatim}
\end { small}
That will build and install the library with both descriptors (and link against both) but then only use TomsFastMath in the timing demo.
2004-10-30 03:00:26 +00:00
2005-04-17 11:37:13 +00:00
\chapter { Optimizations}
\section { Introduction}
The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash or PRNG and dependent API will not require
updating. This has the nice benefit that I can add ciphers not have to re--write large portions of the API. For the most part LibTomCrypt has also been written
to be highly portable and easy to build out of the box on pretty much any platform. As such there are no assembler inlines throughout the code, I make no assumptions
about the platform, etc...
That works well for most cases but there are times where time is of the essence. This API also allows optimized routines to be dropped in--place of the existing
portable routines. For instance, hand optimized assembler versions of AES could be provided and any existing function that uses the cipher could automatically use
the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
At the heart of this flexibility is the ``descriptor'' system. A descriptor is essentially just a C ``struct'' which describes the algorithm and provides pointers
to functions that do the work. For a given class of operation (e.g. cipher, hash, prng) the functions have identical prototypes which makes development simple. In most
dependent routines all a developer has to do is register\_ XXX() the descriptor and they're set.
\section { Ciphers}
The ciphers in LibTomCrypt are accessed through the ltc\_ cipher\_ descriptor structure.
\begin { small}
\begin { verbatim}
struct ltc_ cipher_ descriptor {
/** name of cipher */
char *name;
/** internal ID */
unsigned char ID;
/** min keysize (octets) */
int min_ key_ length,
/** max keysize (octets) */
max_ key_ length,
/** block size (octets) */
block_ length,
/** default number of rounds */
default_ rounds;
/** Setup the cipher
@param key The input symmetric key
@param keylen The length of the input key (octets)
@param num_ rounds The requested number of rounds (0==default)
@param skey [out] The destination of the scheduled key
@return CRYPT_ OK if successful
*/
2005-11-18 05:15:37 +00:00
int (*setup)(const unsigned char *key, int keylen, int num_ rounds, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Encrypt a block
@param pt The plaintext
@param ct [out] The ciphertext
@param skey The scheduled key
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*ecb_ encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Decrypt a block
@param ct The ciphertext
@param pt [out] The plaintext
@param skey The scheduled key
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*ecb_ decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Test the block cipher
@return CRYPT_ OK if successful, CRYPT_ NOP if self-testing has been disabled
*/
int (*test)(void);
2005-11-18 05:15:37 +00:00
/** Terminate the context
@param skey The scheduled key
*/
void (*done)(symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Determine a key size
@param keysize [in/out] The size of the key desired and the suggested size
@return CRYPT_ OK if successful
*/
int (*keysize)(int *keysize);
/** Accelerators **/
/** Accelerated ECB encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ ecb_ encrypt)(const unsigned char *pt, unsigned char *ct,
unsigned long blocks, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Accelerated ECB decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ ecb_ decrypt)(const unsigned char *ct, unsigned char *pt,
unsigned long blocks, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Accelerated CBC encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ cbc_ encrypt)(const unsigned char *pt, unsigned char *ct,
unsigned long blocks, unsigned char *IV,
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Accelerated CBC decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ cbc_ decrypt)(const unsigned char *ct, unsigned char *pt,
unsigned long blocks, unsigned char *IV,
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Accelerated CTR encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param mode little or big endian counter (mode=0 or mode=1)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ ctr_ encrypt)(const unsigned char *pt, unsigned char *ct,
unsigned long blocks, unsigned char *IV,
int mode, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2006-01-26 18:11:56 +00:00
/** Accelerated LRW
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_ OK if successful
*/
int (*accel_ lrw_ encrypt)(const unsigned char *pt, unsigned char *ct,
unsigned long blocks, unsigned char *IV,
const unsigned char *tweak, symmetric_ key *skey);
/** Accelerated LRW
@param ct Ciphertext
@param pt Plaintext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_ OK if successful
*/
int (*accel_ lrw_ decrypt)(const unsigned char *ct, unsigned char *pt,
unsigned long blocks, unsigned char *IV,
const unsigned char *tweak, symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Accelerated CCM packet (one-shot)
@param key The secret key to use
@param keylen The length of the secret key (octets)
2005-11-18 05:15:37 +00:00
@param uskey A previously scheduled key [optional can be NULL]
2005-04-17 11:37:13 +00:00
@param nonce The session nonce [use once]
@param noncelen The length of the nonce
@param header The header for the session
@param headerlen The length of the header (octets)
@param pt [out] The plaintext
@param ptlen The length of the plaintext (octets)
@param ct [out] The ciphertext
@param tag [out] The destination tag
@param taglen [in/out] The max size and resulting size of the authentication tag
@param direction Encrypt or Decrypt direction (0 or 1)
@return CRYPT_ OK if successful
*/
2005-11-18 05:15:37 +00:00
int (*accel_ ccm_ memory)(
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
2005-11-18 05:15:37 +00:00
symmetric_ key *uskey,
2005-04-17 11:37:13 +00:00
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated GCM packet (one shot)
@param key The secret key
@param keylen The length of the secret key
@param IV The initial vector
@param IVlen The length of the initial vector
@param adata The additional authentication data (header)
@param adatalen The length of the adata
@param pt The plaintext
@param ptlen The length of the plaintext (ciphertext length is the same)
@param ct The ciphertext
@param tag [out] The MAC tag
@param taglen [in/out] The MAC tag length
@param direction Encrypt or Decrypt mode (GCM_ ENCRYPT or GCM_ DECRYPT)
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK on success
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ gcm_ memory)(
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
} ;
\end { verbatim}
\end { small}
\subsection { Name}
2005-08-01 16:36:47 +00:00
\index { find\_ cipher()}
2005-04-17 11:37:13 +00:00
The ``name'' parameter specifies the name of the cipher. This is what a developer would pass to find\_ cipher() to find the cipher in the descriptor
tables.
\subsection { Internal ID}
This is a single byte Internal ID you can use to distingish ciphers from each other.
\subsection { Key Lengths}
The minimum key length is ``min\_ key\_ length'' and is measured in octets. Similarly the maximum key length is ``max\_ key\_ length''. They can be equal
and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
\subsection { Block Length}
The size of the ciphers plaintext or ciphertext is ``block\_ length'' and is measured in octets.
\subsection { Rounds}
Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is ``default\_ rounds''.
\subsection { Setup}
To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets ``key'' of length ``keylen'' octets. The user
can specify the number of rounds they want through ``num\_ rounds'' where $ num \_ rounds = 0 $ means use the default. The destination of a scheduled key is stored
in ``skey''.
2005-06-09 00:08:13 +00:00
Inside the ``symmetric\_ key'' union there is a ``void *data'' which you can use to allocate data if you need a data structure that doesn't fit with the existing
ones provided. Just make sure in your ``done()'' function that you free the allocated memory.
2005-04-17 11:37:13 +00:00
\subsection { Single block ECB}
To process a single block in ECB mode the ecb\_ encrypt() and ecb\_ decrypt() functions were provided. The plaintext and ciphertext buffers are allowed to overlap so you
must make sure you do not overwrite the output before you are finished with the input.
\subsection { Testing}
The test() function is used to self--test the ``device''. It takes no arguments and returns \textbf { CRYPT\_ OK} if all is working properly.
\subsection { Key Sizing}
Occasionally a function will want to find a suitable key size to use since the input is oddly sized. The keysize() function is for this case. It accepts a
pointer to an integer which represents the desired size. The function then has to match it to the exact or a lower key size that is valid for the cipher. For
example, if the input is $ 25 $ and $ 24 $ is valid then it stores $ 24 $ back in the pointed to integer. It must not round up and must return an error if the keysize
cannot be mapped to a valid key size for the cipher.
\subsection { Acceleration}
The next set of functions cover the accelerated functionality of the cipher descriptor. Any combination of these functions may be set to \textbf { NULL} to indicate
it is not supported. In those cases the software fallbacks are used (using the single ECB block routines).
\subsubsection { Accelerated ECB}
These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks. These functions are accessed
through the accel\_ ecb\_ encrypt and accel\_ ecb\_ decrypt pointers. The ``blocks'' count is the number of complete blocks to process.
\subsubsection { Accelerated CBC}
These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_ cbc\_ encrypt and accel\_ cbc\_ decrypt pointers.
The ``blocks'' value is the number of complete blocks to process. The ``IV'' is the CBC initial vector. It is an input upon calling this function and must be
updated by the function before returning.
\subsubsection { Accelerated CTR}
This function is meant for accelerated CTR encryption. It is accessible through the accel\_ ctr\_ encrypt pointer.
The ``blocks'' value is the number of complete blocks to process. The ``IV'' is the CTR counter vector. It is an input upon calling this function and must be
2005-06-09 00:08:13 +00:00
updated by the function before returning. The ``mode'' value indicates whether the counter is big (mode = CTR\_ COUNTER\_ BIG\_ ENDIAN) or
little (mode = CTR\_ COUNTER\_ LITTLE\_ ENDIAN) endian.
2005-04-17 11:37:13 +00:00
This function (and the way it's called) differs from the other two since ctr\_ encrypt() allows any size input plaintext. The accelerator will only be
called if the following conditions are met.
\begin { enumerate}
\item The accelerator is present
\item The CTR pad is empty
\item The remaining length of the input to process is greater than or equal to the block size.
\end { enumerate}
The ``CTR pad'' is empty when a multiple (including zero) blocks of text have been processed. That is, if you pass in seven bytes to AES--CTR mode you would have to
pass in a minimum of nine extra bytes before the accelerator could be called. The CTR accelerator must increment the counter (and store it back into the
buffer provided) before encrypting it to create the pad.
The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
2006-01-26 18:11:56 +00:00
\subsubsection { Accelerated LRW}
These functions are meant for accelerated LRW. They process blocks of input in lengths of multiples of 16 octets. They must accept the ``IV'' and ``tweak''
state variables and updated them prior to returning. Note that you may want to disable \textbf { LRW\_ TABLES} in ``tomcrypt\_ custom.h'' if you intend
to use accelerators for LRW.
While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_ setiv() more efficient.
Note that calling lrw\_ done() will only invoke the cipher\_ descriptor[].done() function on the ``symmetric\_ key'' parameter of the LRW state. That means
if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
the plugin solely to do LRW with the cipher. That way cipher\_ descriptor[].setup() means to init LRW resources and cipher\_ descriptor[].done() means to
free them.
2005-04-17 11:37:13 +00:00
\subsubsection { Accelerated CCM}
2005-11-18 05:15:37 +00:00
This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance). This
function MUST support both key passing methods.
\begin { center}
\begin { small}
\begin { tabular} { |r|r|l|}
\hline \textbf { key} & \textbf { uskey} & \textbf { Source of key} \\
\hline NULL & NULL & Error, not supported \\
\hline non-NULL & NULL & Use key, do a key schedule \\
\hline NULL & non-NULL & Use uskey, key schedule not required \\
\hline non-NULL & non-NULL & Use uskey, key schedule not required \\
\hline
\end { tabular}
\end { small}
\end { center}
2005-04-17 11:37:13 +00:00
\subsubsection { Accelerated GCM}
This function is meant for accelerated GCM encryption or decryption. It processes the entire packet in one call. Note that the setup() function will not
be called prior to this. This function must handle scheduling the key provided on its own.
\section { One--Way Hashes}
The hash functions are accessed through the ltc\_ hash\_ descriptor structure.
\begin { small}
\begin { verbatim}
struct ltc_ hash_ descriptor {
/** name of hash */
char *name;
/** internal ID */
unsigned char ID;
/** Size of digest in octets */
unsigned long hashsize;
/** Input block size in octets */
unsigned long blocksize;
2005-06-09 00:08:13 +00:00
/** ASN.1 OID */
unsigned long OID[16];
2005-04-17 11:37:13 +00:00
/** Length of DER encoding */
2005-06-09 00:08:13 +00:00
unsigned long OIDlen;
2005-04-17 11:37:13 +00:00
/** Init a hash state
@param hash The hash to initialize
@return CRYPT_ OK if successful
*/
int (*init)(hash_ state *hash);
/** Process a block of data
@param hash The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_ OK if successful
*/
int (*process)(hash_ state *hash, const unsigned char *in, unsigned long inlen);
/** Produce the digest and store it
@param hash The hash state
@param out [out] The destination of the digest
@return CRYPT_ OK if successful
*/
int (*done)(hash_ state *hash, unsigned char *out);
/** Self-test
@return CRYPT_ OK if successful, CRYPT_ NOP if self-tests have been disabled
*/
int (*test)(void);
2005-08-01 16:36:47 +00:00
/* accelerated hmac callback: if you need to-do multiple packets just use the
generic hmac_ memory and provide a hash callback */
int (*hmac_ block)(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2005-04-17 11:37:13 +00:00
} ;
\end { verbatim}
\end { small}
\subsection { Name}
This is the name the hash is known by and what find\_ hash() will look for.
\subsection { Internal ID}
This is the internal ID byte used to distinguish the hash from other hashes.
\subsection { Digest Size}
The ``hashsize'' variable indicates the length of the output in octets.
\subsection { Block Size}
The `blocksize'' variable indicates the length of input (in octets) that the hash processes in a given
invokation.
2005-06-09 00:08:13 +00:00
\subsection { OID Identifier}
This is the universal ASN.1 Object Identifier for the hash.
2005-04-17 11:37:13 +00:00
\subsection { Initialization}
The init function initializes the hash and prepares it to process message bytes.
\subsection { Process}
This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
guaranteed to be a multiple of the block size in length.
\subsection { Done}
The done function terminates the hash and returns the message digest.
\subsection { Acceleration}
2005-08-01 16:36:47 +00:00
A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
\subsection { HMAC Acceleration}
The hmac\_ block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_ memory() if present. If you need
to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_ memory() as provided in LibTomCrypt.
2005-04-17 11:37:13 +00:00
\section { Pseudo--Random Number Generators}
The pseudo--random number generators are accessible through the ltc\_ prng\_ descriptor structure.
\begin { small}
\begin { verbatim}
struct ltc_ prng_ descriptor {
/** Name of the PRNG */
char *name;
/** size in bytes of exported state */
int export_ size;
/** Start a PRNG state
@param prng [out] The state to initialize
@return CRYPT_ OK if successful
*/
int (*start)(prng_ state *prng);
/** Add entropy to the PRNG
@param in The entropy
@param inlen Length of the entropy (octets)\
@param prng The PRNG state
@return CRYPT_ OK if successful
*/
int (*add_ entropy)(const unsigned char *in, unsigned long inlen, prng_ state *prng);
/** Ready a PRNG state to read from
@param prng The PRNG state to ready
@return CRYPT_ OK if successful
*/
int (*ready)(prng_ state *prng);
/** Read from the PRNG
@param out [out] Where to store the data
@param outlen Length of data desired (octets)
@param prng The PRNG state to read from
@return Number of octets read
*/
unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_ state *prng);
/** Terminate a PRNG state
@param prng The PRNG state to terminate
@return CRYPT_ OK if successful
*/
int (*done)(prng_ state *prng);
/** Export a PRNG state
@param out [out] The destination for the state
@param outlen [in/out] The max size and resulting size of the PRNG state
@param prng The PRNG to export
@return CRYPT_ OK if successful
*/
int (*pexport)(unsigned char *out, unsigned long *outlen, prng_ state *prng);
/** Import a PRNG state
@param in The data to import
@param inlen The length of the data to import (octets)
@param prng The PRNG to initialize/import
@return CRYPT_ OK if successful
*/
int (*pimport)(const unsigned char *in, unsigned long inlen, prng_ state *prng);
/** Self-test the PRNG
@return CRYPT_ OK if successful, CRYPT_ NOP if self-testing has been disabled
*/
int (*test)(void);
} ;
\end { verbatim}
\end { small}
\subsection { Name}
The name by which find\_ prng() will find the PRNG.
\subsection { Export Size}
When an PRNG state is to be exported for future use you specify the space required in this variable.
\subsection { Start}
Initialize the PRNG and make it ready to accept entropy.
\subsection { Entropy Addition}
Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
\subsection { Ready}
This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
on the specific PRNG used.
\subsection { Read}
Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
if it does as many protocols do not retry reads and will fail on the first try.
\subsection { Done}
Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
2004-10-30 03:00:26 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Exporting and Importing}
An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume ``the same session''
but should at least maintain the same level of state entropy.
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\section { BigNum Math Descriptors}
The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
it hasn't proven hard to write ``glue'' to use math libraries so far. The basic descriptor looks like.
\begin { small}
\begin { verbatim}
/** math descriptor */
typedef struct {
/** Name of the math provider */
char *name;
/** Bits per digit, amount of bits must fit in an unsigned long */
int bits_ per_ digit;
/* ---- init/deinit functions ---- */
/** initialize a bignum
@param a The number to initialize
@return CRYPT_ OK on success
*/
int (*init)(void **a);
/** init copy
@param dst The number to initialize and write to
@param src The number to copy from
@return CRYPT_ OK on success
*/
int (*init_ copy)(void **dst, void *src);
/** deinit
@param a The number to free
@return CRYPT_ OK on success
*/
void (*deinit)(void *a);
/* ---- data movement ---- */
/** copy
@param src The number to copy from
@param dst The number to write to
@return CRYPT_ OK on success
*/
int (*copy)(void *src, void *dst);
/* ---- trivial low level functions ---- */
/** set small constant
@param a Number to write to
@param n Source upto bits_ per_ digit (actually meant for very small constants)
@return CRYPT_ OK on succcess
*/
int (*set_ int)(void *a, unsigned long n);
/** get small constant
@param a Number to read, only fetches upto bits_ per_ digit from the number
@return The lower bits_ per_ digit of the integer (unsigned)
*/
unsigned long (*get_ int)(void *a);
/** get digit n
@param a The number to read from
@param n The number of the digit to fetch
@return The bits_ per_ digit sized n'th digit of a
*/
unsigned long (*get_ digit)(void *a, int n);
/** Get the number of digits that represent the number
@param a The number to count
@return The number of digits used to represent the number
*/
int (*get_ digit_ count)(void *a);
/** compare two integers
@param a The left side integer
@param b The right side integer
@return LTC_ MP_ LT if a < b,
LTC_ MP_ GT if a > b and
LTC_ MP_ EQ otherwise. (signed comparison)
*/
int (*compare)(void *a, void *b);
/** compare against int
@param a The left side integer
@param b The right side integer (upto bits_ per_ digit)
@return LTC_ MP_ LT if a < b,
LTC_ MP_ GT if a > b and
LTC_ MP_ EQ otherwise. (signed comparison)
*/
int (*compare_ d)(void *a, unsigned long n);
/** Count the number of bits used to represent the integer
@param a The integer to count
@return The number of bits required to represent the integer
*/
int (*count_ bits)(void * a);
/** Compute a power of two
@param a The integer to store the power in
@param n The power of two you want to store (a = 2^ n)
@return CRYPT_ OK on success
*/
int (*twoexpt)(void *a , int n);
/* ---- radix conversions ---- */
/** read ascii string
@param a The integer to store into
@param str The string to read
@param radix The radix the integer has been represented in (2-64)
@return CRYPT_ OK on success
*/
int (*read_ radix)(void *a, const char *str, int radix);
/** write number to string
@param a The integer to store
@param str The destination for the string
@param radix The radix the integer is to be represented in (2-64)
@return CRYPT_ OK on success
*/
int (*write_ radix)(void *a, char *str, int radix);
/** get size as unsigned char string
@param a The integer to get the size (when stored in array of octets)
@return The length of the integer
*/
unsigned long (*unsigned_ size)(void *a);
/** store an integer as an array of octets
@param src The integer to store
@param dst The buffer to store the integer in
@return CRYPT_ OK on success
*/
int (*unsigned_ write)(void *src, unsigned char *dst);
/** read an array of octets and store as integer
@param dst The integer to load
@param src The array of octets
@param len The number of octets
@return CRYPT_ OK on success
*/
int (*unsigned_ read)(void *dst, unsigned char *src, unsigned long len);
/* ---- basic math ---- */
/** add two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a + b"
@return CRYPT_ OK on success
*/
int (*add)(void *a, void *b, void *c);
/** add two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_ per_ digit in length)
@param c The destination of "a + b"
@return CRYPT_ OK on success
*/
int (*addi)(void *a, unsigned long b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a - b"
@return CRYPT_ OK on success
*/
int (*sub)(void *a, void *b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_ per_ digit in length)
@param c The destination of "a - b"
@return CRYPT_ OK on success
*/
int (*subi)(void *a, unsigned long b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_ per_ digit in length)
@param c The destination of "a * b"
@return CRYPT_ OK on success
*/
int (*mul)(void *a, void *b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_ per_ digit in length)
@param c The destination of "a * b"
@return CRYPT_ OK on success
*/
int (*muli)(void *a, unsigned long b, void *c);
/** Square an integer
@param a The integer to square
@param b The destination
@return CRYPT_ OK on success
*/
int (*sqr)(void *a, void *b);
/** Divide an integer
@param a The dividend
@param b The divisor
@param c The quotient (can be NULL to signify don't care)
@param d The remainder (can be NULL to signify don't care)
@return CRYPT_ OK on success
*/
int (*div)(void *a, void *b, void *c, void *d);
/** divide by two
@param a The integer to divide (shift right)
@param b The destination
@return CRYPT_ OK on success
*/
int (*div_ 2)(void *a, void *b);
/** Get remainder (small value)
@param a The integer to reduce
@param b The modulus (upto bits_ per_ digit in length)
@param c The destination for the residue
@return CRYPT_ OK on success
*/
int (*modi)(void *a, unsigned long b, unsigned long *c);
/** gcd
@param a The first integer
@param b The second integer
@param c The destination for (a, b)
@return CRYPT_ OK on success
*/
int (*gcd)(void *a, void *b, void *c);
/** lcm
@param a The first integer
@param b The second integer
@param c The destination for [a, b]
@return CRYPT_ OK on success
*/
int (*lcm)(void *a, void *b, void *c);
/** Modular multiplication
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a*b mod c)
@return CRYPT_ OK on success
*/
int (*mulmod)(void *a, void *b, void *c, void *d);
/** Modular inversion
@param a The value to invert
@param b The modulus
@param c The destination (1/a mod b)
@return CRYPT_ OK on success
*/
int (*invmod)(void *, void *, void *);
/* ---- reduction ---- */
/** setup montgomery
@param a The modulus
@param b The destination for the reduction digit
@return CRYPT_ OK on success
*/
int (*montgomery_ setup)(void *a, void **b);
/** get normalization value
@param a The destination for the normalization value
@param b The modulus
@return CRYPT_ OK on success
*/
int (*montgomery_ normalization)(void *a, void *b);
/** reduce a number
@param a The number [and dest] to reduce
@param b The modulus
@param c The value "b" from montgomery_ setup()
@return CRYPT_ OK on success
*/
int (*montgomery_ reduce)(void *a, void *b, void *c);
/** clean up (frees memory)
@param a The value "b" from montgomery_ setup()
@return CRYPT_ OK on success
*/
void (*montgomery_ deinit)(void *a);
/* ---- exponentiation ---- */
/** Modular exponentiation
@param a The base integer
@param b The power (can be negative) integer
@param c The modulus integer
@param d The destination
@return CRYPT_ OK on success
*/
int (*exptmod)(void *a, void *b, void *c, void *d);
/** Primality testing
@param a The integer to test
@param b The destination of the result (FP_ YES if prime)
@return CRYPT_ OK on success
*/
int (*isprime)(void *a, int *b);
/* ---- (optional) ecc point math ---- */
/** ECC GF(p) point multiplication (from the NIST curves)
@param k The integer to multiply the point by
@param G The point to multiply
@param R The destination for kG
@param modulus The modulus for the field
@param map Boolean indicated whether to map back to affine or not (can be
ignored if you work in affine only)
@return CRYPT_ OK on success
*/
int (*ecc_ ptmul)(void *k, ecc_ point *G, ecc_ point *R, void *modulus, int map);
/** ECC GF(p) point addition
@param P The first point
@param Q The second point
@param R The destination of P + Q
@param modulus The modulus
@param mp The "b" value from montgomery_ setup()
@return CRYPT_ OK on success
*/
int (*ecc_ ptadd)(ecc_ point *P, ecc_ point *Q, ecc_ point *R, void *modulus, void *mp);
/** ECC mapping from projective to affine, currently uses (x,y,z) => (x/z^ 2, y/z^ 3, 1)
@param P The point to map
@param modulus The modulus
@param mp The "b" value from montgomery_ setup()
@return CRYPT_ OK on success
@remark The mapping can be different but keep in mind a ecc_ point only has
three integers (x,y,z) so if you use a different mapping you have to make it fit.
*/
int (*ecc_ map)(ecc_ point *P, void *modulus, void *mp);
/* ---- (optional) rsa optimized math (for internal CRT) ---- */
2005-11-18 05:15:37 +00:00
/** RSA Key Generation
@param prng An active PRNG state
@param wprng The index of the PRNG desired
@param size The size of the modulus (key size) desired (octets)
@param e The "e" value (public key). e==65537 is a good choice
@param key [out] Destination of a newly created private key pair
@return CRYPT_ OK if successful, upon error all allocated ram is freed
*/
int (*rsa_ keygen)(prng_ state *prng, int wprng, int size, long e, rsa_ key *key);
2005-08-01 16:36:47 +00:00
/** RSA exponentiation
@param in The octet array representing the base
@param inlen The length of the input
@param out The destination (to be stored in an octet array format)
@param outlen The length of the output buffer and the resulting size (zero padded to the
size of the modulus)
@param which PK_ PUBLIC for public RSA and PK_ PRIVATE for private RSA
@param key The RSA key to use
@return CRYPT_ OK on success
*/
int (*rsa_ me)(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_ key *key);
} ltc_ math_ descriptor;
\end { verbatim}
\end { small}
Most of the functions are fairly straightfoward and do not need documentation. We'll cover the basic conventions of the API and then explain the accelerated functions.
\subsection { Conventions}
All ``bignums'' are accessed through an opaque ``void *'' data type. You must interally cast the pointer if you need to access members of your bignum structure. During
the init calls a ``void **'' will be passed where you allocate your structure and set the pointer then initialize the number to zero. During the deinit calls you must
free the bignum as well as the structure you allocated to place it in.
All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $ c \leftarrow ab $ .
All functions (except where noted otherwise) return \textbf { CRYPT\_ OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
The digit routines (including functions with the ``i'' suffix) use a ``unsigned long'' to represent the digit. If your internal digit is larger than this you must
then partition your digits. Normally this does not matter as ``unsigned long'' will be the same size as your register size. Note that if your digit is smaller
than an ``unsigned long'' that is also acceptable as the ``bits\_ per\_ digit'' parameter will specify this.
\subsection { ECC Functions}
The ECC system in LibTomCrypt is based off of the NIST recommended curves over $ GF ( p ) $ and is used to implement EC-DSA and EC-DH. The ECC functions work with
the \textbf { ecc\_ point} structure and assume the points are stored in Jacobian projective format.
\begin { verbatim}
/** A point on a ECC curve, stored in Jacbobian format such
that (x,y,z) => (x/z^ 2, y/z^ 3, 1) when interpretted as affine */
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_ point;
\end { verbatim}
All ECC functions must use this mapping system. The only exception is when you remap all three ECC callbacks which will allow you to have more control
over how the ECC math will be implemented. Out of the box you only have three parameters per point to use $ ( x, y, z ) $ however, these are just void pointers. They
could point to anything you want. The only further exception is the ecc\_ export() function which expects the values to be in affine format.
\subsubsection { Point Multiply}
This will multiply the point $ G $ by the scalar $ k $ and store the result in the point $ R $ . The value should be mapped to affine only if $ map $ is set to one.
\subsubsection { Point Addition}
This will add the point $ P $ to the point $ Q $ and store it in the point $ R $ . The $ mp $ parameter is the ``b'' value from the montgomery\_ setup() call. The input points
may be in either affine (with $ z = 1 $ ) or projective format and the output point is always projective.
\subsubsection { Point Mapping}
This will map the point $ P $ back from projective to affine. The output point $ P $ must be of the form $ ( x, y, 1 ) $ .
\subsection { RSA Functions}
The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
\begin { verbatim}
/** RSA PKCS style key */
typedef struct Rsa_ key {
/** Type of key, PK_ PRIVATE or PK_ PUBLIC */
int type;
/** The public exponent */
void *e;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
} rsa_ key;
\end { verbatim}
The call reads the ``in'' buffer as an unsigned char array in big endian format. Then it performs the exponentiation and stores the output in big endian format
to the ``out'' buffer. The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes). For example,
for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \# 1 v2.1 specification.
2004-05-31 02:36:47 +00:00
\input { crypt.ind}
2003-03-03 00:59:24 +00:00
\end { document}
2005-06-09 00:08:13 +00:00
% $Source: /cvs/libtom/libtomcrypt/crypt.tex,v $
2006-01-26 18:11:56 +00:00
% $Revision: 1.62 $
% $Date: 2006/01/26 18:29:02 $