\documentclass{article}

\setlength{\textwidth}{6.75in} % 1 inch side margins
\setlength{\textheight}{9in} % ~1 inch top and bottom margins

\setlength{\headheight}{0in}
\setlength{\topmargin}{0in}
\setlength{\headsep}{0in}

\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}

\title{Botan API Documentation}
\author{Jack Lloyd (lloyd@randombit.net)}
\date{August 25, 2002}

\newcommand{\filename}[1]{\texttt{#1}}
\newcommand{\manpage}[2]{\texttt{#1}(#2)}

\newcommand{\macro}[1]{\texttt{#1}}

\newcommand{\function}[1]{\textbf{#1}}
\newcommand{\type}[1]{\texttt{#1}}
\renewcommand{\arg}[1]{\textsl{#1}}

\begin{document}

\maketitle

\tableofcontents

\parskip=5pt
\pagebreak

\section{Introduction}

Botan is a C++ library which attempts to provide the most common cryptographic
algorithms in an easy to use and portable package. Currently it runs on a wide
variety of systems, using numerous different compilers and on many different
CPU architectures.

The base library is written in ISO C++, so it can be ported with minimal fuss,
but Botan also supports a modules system, which allows system dependent code
to be compiled into the library for use by application code.

While you are reading this, you may want to refer to the files
\filename{base.h} and \filename{pipe.h}. These files contain the classes that
form the basic interface for the library.

\subsection{Basic Conventions}

With a few exceptions declarations in the library are contained within the
namespace \texttt{Botan}. Botan declares several typedef'ed types to help
buffer it against changes in machine architecture. These types are used
extensively in the interface, and thus it would be often be convenient to use
them without the \texttt{Botan::} prefix. You can, by \texttt{using} the
namespace \texttt{Botan\_types} (this way you can use the type names without
the namespace prefix, but the remainder of the library stays out of the global
namespace). The included types are \type{byte} and \type{u32bit}, which are
unsigned integer types.

The headers for Botan are usually available in the form
\filename{botan/headername.h}. For brevity in this documentation, headers are
always just called \filename{headername.h}, but they should be used as
\filename{botan/headername.h} in your actual code.

Prior to version 0.9.1, Botan was known as OpenCL. You can use the name OpenCL
wherever Botan is used (for header files, namespaces, macros, etc). This is
not recommended for new code.

\subsection{Targets}

Botan's primary targets (system-wise) are 32 and 64 bit systems with at least a
few hundred kilobytes of memory. Generally, given the choice between optimizing
for 32 bit systems and 64 bit systems, Botan chooses 64 bits, simply on the
theory that where performance really matters (like servers), people are using
64 bit machines. But performance on 32 bit systems is also quite good.

Nowadays, smaller systems such as handhelds, phones, and smart cards, are also
capable of using Botan. For very low-end machines, such as 8 bit smart cards
with only a few tens of kilobytes of RAM and RAM, Botan is too large, even in
stripped down form, to be useful. Botan has been used on a Compaq iPaq handheld
with no problems.

Botan's design makes it quite easy to remove unused algorithms in such a way
that applications do not need to be recompiled to work, even applications that
use the algorithms in question. They can simply ask Botan if the algorithm
exists, and if Botan says yes, ask the library to give them such an object for
that algorithm.

\pagebreak

\subsection{Why Botan?}

Botan may be the perfect choice for your application. Or it might be a
terribly bad idea. This section is basically to make it clear what Botan is
and is not.

First, let's cover the major strengths. Botan:

\begin{list}{*}
  \item Is written in a (fairly) clean object-oriented style, and the usual
        API works in terms of reasonably high-level abstractions.
  \item

  \item Supports a huge variety of algorithms, including most of the major
        public key algorithms and standards (such as IEEE 1363 and PKCS \#1)

  \item Supports a name-based lookup scheme, so you can get ahold of any
        algorithm on the fly.

  \item You can easily extend much of the system at run or (application)
        compile time.

  \item Works well with a wide variety of compilers, operating systems, and
        CPUs, and more all the time.

  \item Is the only open source crypto library (that I know of) that has
        support for memory allocation techniques that prevent an attacker from
        reading swap in an attempt to gain access to keys or other
        secrets. In fact two different such methods are supported.

  \item Has (optional) support for Zlib and Bzip2 compression/decompression
        integrated completely into the system -- it only takes a line or two of
        code to add compression to your application.
\end{list}

\noindent
And the major downsides and deficiencies are:

\begin{list}{*}
  \item It's written in C++. If your application isn't, Botan is probably
        going to be more pain than it's worth.
  \item

  \item While efficiency is a major goal, Botan is not (currently) as fast as
        say, OpenSSL. This is mostly due to the lack of assembly optimizations
        (crypto is one of the last few areas where assembly really does make
        sense), and partly from using non-optimal algorithms in some places.

        Both of these issues will be dealt with within the next 6-9 months,
        probably sooner.

  \item Doesn't support higher-level protocols and formats like SSL or OpenPGP.
        This will eventually be available as separate packages. Of course you
        can write it yourself (and I would be happy to help with that in any
        way I can). Some work is beginning on TLS support, but it's a ways out
        still.

  \item Doesn't (currently) support elliptic curves.

  \item Doesn't (currently) support any very high-level 'envelope' style
        processing.
\end{list}

\pagebreak

\section{Building The Library}

These are the basic steps for compiling Botan on a Unix or Unix-like system:

\begin{verbatim}
   $ ./configure.pl CC-OS-CPU
   $ make
   $ make check # optional, but recommended
   # make install
\end{verbatim}

The \filename{configure.pl} script is written in Perl; you'll need at least
version 5.005 to run the script. To get the list of values for \verb|CC|,
\verb|OS|, and \verb|CPU| that \filename{configure.pl} supports, run it with
the ``\verb|--help|'' option.

The \verb|make install| target has a default directory in which it will install
Botan (on Unix, it's \verb|/usr/local|). You can override this by changing the
value of the INSTALLROOT variable, like so:

\verb|make INSTALLROOT=/some/path install|

On Unix, the makefile has to decide who should own the files once they are
installed. By default, it uses \texttt{root:root}, but on some systems (for
example, MacOS X), there is no \texttt{root} group. Also, if you don't have
root access on the system you will want them to be installed owned by something
other than root (like yourself). You can override the defaults in a similar
manner to the \texttt{INSTALLROOT}. Here's an example:

\verb|make OWNER=lloyd GROUP=users INSTALLROOT=$HOME/binaries install|

The script tries to guess what kind of makefile to generate, but it might guess
wrong, so you can override it with \verb|--make-style=somestyle|. The styles
Botan currently knows about are 'unix' (normal Unix makefiles), and 'nmake',
the make variant commonly used by Windows compilers.

You can put basically anything reasonable for CPU: the script knows about a
large number of different architectures, their sub-models, and common aliases
for them. The script does not display all the possibilities in it's help
message because there are simply too many entries (if you're curious about what
exactly is available, you can look at the \verb|%ARCH|, \verb|%ARCH_ALIAS|, and
\verb|%SUBMODEL_ALIAS| hashes at the start of the script).

Note that you should only select the 64-bit version of a CPU (like ``sparc64''
or ``mips64'') if your operating system knows how to handle 64-bit object code
-- a 32-bit kernel on a 64-bit CPU will generally not like 64-bit code. For
example, gcc-solaris-sparc64 will not work unless you're running a 64-bit
Solaris kernel (for 32-bit Solaris running on an UltraSPARC system, you want
gcc-solaris-sparc32-v9). You may or may not have to install 64-bit versions of
libc and related system libraries as well.

The script also knows about the various extension modules available. You can
enable one or more with the option ``\verb|--modules=MOD|'', where \verb|MOD|
is some name that identifies the extension (or a comma separated list of them).
Modules provide additional capabilities such making a Zlib
compressor/decompressor system available, or replacing the implementation of
\function{system\_clock} with \function{gettimeofday} on some Unices. You
should enable any extensions which makes sense for your system. There is also
the concept of a ``module set'', essentially a set of modules which can be
referred to by a single name. At the time of this writing, the only available
module set is called 'unix', and includes about half a dozen modules which
should run on most, if not all, recent Unix systems. You can add a module set
with ``\verb|--module-set=MODSET|''.

Note that not all OSes or CPUs have specific support. If the CPU architecture
of your system isn't supported by \filename{configure.pl}, use
'generic'. This setting disables machine-specific optimization
flags. Similarly, setting OS to 'generic' disables things which depend greatly
on OS support (specifically, shared libraries).

However, it's impossible to guess which options to give to a system compiler.
Thus, if you want to compile Botan with a compiler which
\filename{configure.pl} does not support, the script will have to be updated.
Preferably, mail the man pages (or similar documentation) for the C and C++
compilers and the system linker to the author, or download the Botan-config
package from the Botan web site, and do it yourself.

\pagebreak

\subsection{Configuration Parameters}

There are some configuration parameters which you may want to tweak before
building the library. These can be found in \filename{config.h}. This file is
overwritten every time the configure script is run (and does not exist until
after you run the script for the first time).

Also included in \filename{config.h} are macros which are defined if one or
more extensions are available. All of them begin with \verb|BOTAN_EXT_|. For
example, if \verb|BOTAN_EXT_BZIP2| is defined, then an application using
Botan can include \filename{<botan/bzip2.h>} and use the Bzip2 filters.

\texttt{DEFAULT\_BUFFERSIZE}: This constant is used as the size of buffers
throughout Botan. A good rule of thumb would be to use the page size of your
machine. The default should be fine for most, if not all, purposes. If you're
particularly concerned about memory usage (for example, for a small embedded
system with little memory), drop it down to 256 or so.

\texttt{VECTOR\_OVER\_ALLOCATE}: The memory container \type{SecureVector} will
overallocate requests by this amount (in elements). In several areas of the
library, we grow a vector fairly often. By overallocating by a small amount, we
don't have to do allocations as often (which is good, because the allocators
can be quite slow). If you \emph{really} want to reduce memory usage, set it to
0. Otherwise, the default should be perfectly fine.

\texttt{MP\_WORD\_BITS}: This macro controls the size of the words used for
calculations with the MPI implementation (called \type{BigInt}). You can choose
8, 16, or 32 bits, with 32 being the default. In general, I can't imagine a
situation where this is truly useful to change, but it's helpful for testing
purposes. Keep in mind that changing this breaks binary compatibility. In
general, halving the size of the word also halves the speed of \type{BigInt}
operations.

\pagebreak

\section{Initializing the Library}

The library needs to have various things done to it in order for it to work
correctly. To make sure this is done properly, you should create a
\type{LibraryInitializer} object at the start of your main() function, before
you start using any part of Botan. The initializer does things like
initializing the memory allocation system, setting up the algorithm lookup
tables, finding out if there is a high resolution timer available to use, and
similar such matters.

The constructor of this object takes a string which specifies various options.
If more than one is used, they should be separated by a space. The options are
listed by order of danger (ie the caution you should have about using the
option), with safest first.

\noindent
\textbf{Option ``seed\_rng''}: If this argument is set, then a ``best effort''
attempt will be made to initialize the random number generator. Even if this
argument is \emph{not} passed, if \filename{/dev/random} is available, it will
be used to seed the RNG (via the \type{File\_EntropySource}).

\noindent
\textbf{Option ``egd\_path=PATH''}: Try to connect to an EGD socket at PATH and
use the output to seed the global RNG. If you do not pass this option, but you
do pass ``seed\_rng'', Botan will attempt to read from an EGD socket at
\filename{/var/run/egd-pool}, which is a pseudo-standard location for the
system's EGD socket.

Be aware that if the process listening on the other side of the socket is
actively hostile, it is possible for it to accept but ignore the connection,
blocking your process.

\noindent
\textbf{Option ``secure\_memory''}: Try to create a more secure allocator type
-- one that either locks allocated memory into RAM, or that memory maps a disk
file that it erases after use. If both are available, it will prefer the memory
mapping mechanism, because locking memory requires root privileges on many
systems.

On systems that don't (currently) have any specialized allocators, like
Windows, this option is ignored.

\noindent
\textbf{Option ``thread\_safe''}: The library should use mutexes for guarding
access to shared resources, such as the memory allocation system. If you pass
the ``thread\_safe'' option, and the initializer can't find a useful mutex
module, it will throw an exception. Thread safety in Botan is basically
untested and it is fairly likely there are problems. If you're going to try
this, be ready to have to send bug reports to the mailing list.

While most things in Botan are already thread-safe at the object level, a few
objects (notably the global RNG, the allocators, and the lookup tables) are
shared between threads for efficiency or security reasons. Access to these
objects are protected using mutexes, and I've tried to ensure things are
locked when they need to be, but I probably am missing some cases.

\noindent
\textbf{Option ``fast\_rng''}: If this option is set, the library will use an
\type{ANSI\_X917\_RNG} object, instead of a somewhat slower \type{Randpool}
object, as the global random number generator. See the section \textit{Random
Number Generators} for more details about what these objects are. Don't pass
this option unless you know what you're doing; there are many cases where the
X9.17 generator does not provide sufficient security (mostly because it has a
fairly small internal state).

\noindent
\textbf{Option ``no\_timers''}: The library should not try to find a high
resolution timer to use. Don't pass this option unless you \emph{really} know
what you're doing.

If you do not create a \type{LibraryInitializer} object, pretty much any Botan
operation will fail, because it will be unable to do basic things like get
memory. Note too, that you should be careful to only create one such object.

\pagebreak

\section{Gotchas}

There are a few things to watch out for to prevent problems when using Botan.

First and primary of these is to \emph{never} allocate any kind of Botan object
globally. The problem is that the constructor for such an object will be called
before the \type{LibraryInitializer} is created, and the constructor will
undoubtedly try to call an object which has not been initialized. If you're
lucky your program will die with an uncaught exception. If you're less lucky,
it will crash from a memory access error. And if you're really unlucky it
\emph{won't} crash, and your program will be in an unknown (but very bad)
state. Generally, global variables are bad news anyway, and I can't think of
many cases where this will cause problems for application code. The library
does have some global objects in it, and a great deal of hackery is involved
making sure everything is created and destroyed at the right time (and in the
right order).

The same rule applies for making sure the destructors of all your Botan objects
are called before the \type{LibraryInitializer} is destroyed. This implies you
can't have static variables that are Botan objects inside functions or
classes. This is kind of inelegant, but rarely a real problem in practice.

Never create a \type{SecureVector} or \type{SecureBuffer} with a type that is
not a basic integer (\type{byte}, \type{u16bit}, \type{u32bit}, \type{u64bit}).
More strongly, if you, as a user of the library, are creating any memory buffer
object that's not a \type{SecureVector<byte>}, you're probably doing something
wrong (I suppose there may be exceptions to this rule, but not many).

Don't include headers you don't have to. Past experience with Botan has shown
that headers get renamed fairly regularly as internal design changes are made,
but this need not affect you, if you follow the ``proper procedures''. Using
the lookup interface defined in \filename{lookup.h} and \filename{look\_pk.h}
will save you a great deal of pain in this regard, as it insulates you against
many such changes.

Enclose your \function{main} with a try block, and catch any
\type{std::exception} throws. This is not strictly required, but if you don't,
and Botan throws an exception, your application would die mysteriously and
without any error message.

Botan's multiple precision integer class (\type{BigInt}) has some of it's low
level functions linked as C. This is to make it easier to write implementations
of them in assembly (as then the name mangling technique used by the compiler
doesn't come into play). These functions are not visible in application space,
but at link time they could cause conflicts, so you should try to avoid naming
functions in your code any name starting with \texttt{bigint\_}.

\pagebreak

\section{The Basic Interface}

Botan has two different interfaces. The one documented in this section is
meant more for implementing higher-level types (see the section on filters,
later in this manual) than for use by applications.

\subsection{Basic Algorithm Abilities}

There are a small handful of functions implemented by most of Botan's
algorithm objects. Among these are:

\noindent
\type{std::string} \function{name}():

Returns a human-readable string of the name of this algorithm. Examples of
names returned are ``Blowfish'' and ``HMAC(MD5)''. You can turn names back into
algorithm objects using the functions in \filename{lookup.h}.

\noindent
\type{void} \function{clear}():

Clear out the algorithm's internal state. A block cipher object will ``forget''
it's key, a hash function will ``forget'' any data put into it, etc.

\noindent
\function{clone}():

This function is central to Botan's name-based interface. The \function{clone}
has many different return types, such as \type{BlockCipher*} and
\type{HashFunction*}, depending on what kind of object it is called on. Note
that unlike Java's clone, this returns a new object in a ``pristine'' state;
that is, operations done on the initial object before calling \function{clone}
do not affect the initial state of the new clone.

Cloned objects can (and should) be deallocated with the C++ \texttt{delete}
operator.

\subsection{Keys}

A \type{SymmetricKey} is an abstraction for a symmetric key, which is
represented as an arbitrary length byte string. The major functions of this
type are it's constructors:

\noindent
\function{SymmetricKey}(\type{u32bit} \arg{length}):

This constructor takes creates a new random key of size \arg{length}.

\noindent
\function{SymmetricKey}(\type{std::string} \arg{str}):

The argument \arg{str} is assumed to be a hex string; it is converted to binary
and stored as the key. Whitespace is ignored.

\noindent
\function{SymmetricKey}(\type{const byte} \arg{input}[], \type{u32bit}
\arg{length}):

This constructor simply copies it's input.

Synonyms for this type include \type{BlockCipher\_Key},
\type{StreamCipher\_Key}, \type{MAC\_Key}, and \type{BlockCipherModeIV}
(they're all exactly the same thing, the different names just makes it clear
what the bytes are being used for).

\subsection{Symmetrically Keyed Algorithms}

Block ciphers, stream ciphers, and MACs all handle keys in pretty much the same
way. To make this similarity explicit, all algorithms of those types are
derived from the \type{SymmetricAlgorithm} base class. This type has three
functions:

\noindent
\type{void} \function{set\_key}(\type{const byte} \arg{key}[], \type{u32bit}
\arg{length}):

Most algorithms only accept keys of certain lengths. If you attempt to call
\function{set\_key} with a key length that is not supported, the exception
\type{Invalid\_Key\_Length} will be thrown. There is also another version of
\function{set\_key} that takes a \type{SymmetricKey} as an argument.

\noindent
\type{bool} \function{valid\_keylength}(\type{u32bit} \arg{length}) const:

This function returns true if a key of the given length will be accepted by
the cipher.

There are also three constant data members of every \type{SymmetricAlgorithm}
object, which specify exactly what limits there are on keys which that object
can accept:

MAXIMUM\_KEYLENGTH: The maximum length of a key. This is at most 32 (256 bits),
even if the algorithm actually supports more.

MINIMUM\_KEYLENGTH: The minimum length of a key. This is at least 1.

KEYLENGTH\_MULTIPLE: The length of the key must be a multiple of this value.

In all cases, \function{set\_key} must be called on an object before any data
processing (encryption, decryption, etc) is done by that object. If this is not
done, the results are undefined -- that is to say, Botan reserves the right in
this situation to do anything from printing a nasty insulting message on the
screen to dumping core.

\subsection{Block Ciphers}

Block ciphers implement the interface \type{BlockCipher}, found in
\filename{base.h}.

\noindent
\type{void} \function{encrypt}(\type{const byte} \arg{in}[BLOCK\_SIZE],
                               \type{byte} \arg{out}[BLOCK\_SIZE]) const

\noindent
\type{void} \function{encrypt}(\type{byte} \arg{block}[BLOCK\_SIZE]) const

These functions apply the block cipher transformation to \arg{in} and place the
result in \arg{out}, or encrypts \arg{block} in place (\arg{in} may be the same
as \arg{out}). BLOCK\_SIZE is a constant member of each class, which specifies
how much data a block cipher can process at one time. Note that BLOCK\_SIZE is
not a static class member, like the old BLOCKSIZE was.

\type{BlockCipher}s have similar functions \function{decrypt}, which perform
the inverse operation.

Block ciphers implement the \type{SymmetricAlgorithm} interface.

\subsection{Stream Ciphers}

Stream ciphers are somewhat different from block ciphers, in that encrypting
data results in changing the internal state of the cipher. Also, you may
encrypt any length of data in one go (in byte amounts).

\noindent
\type{void} \function{encrypt}(\type{const byte} \arg{in}[], \type{byte}
\arg{out}[], \type{u32bit} \arg{length})

\noindent
\type{void} \function{encrypt}(\type{byte} \arg{data}[], \type{u32bit}
\arg{length}):

These functions encrypt the arbitrary length (well, less than 4 gigabyte long)
string \arg{in} and place it into \arg{out}, or encrypts it in place in
\arg{data}. The \function{decrypt} functions look just like
\function{encrypt}.

Stream ciphers implement the \type{SymmetricAlgorithm} interface.

Some stream ciphers support random access to any point in their cipher stream
(currently, the only like this in in Botan is SEAL). For such ciphers, calling
\type{void} \function{seek}(\type{u32bit} \arg{byte}) will change the cipher's
state so that it as if the cipher had been keyed as normal, then encrypted
\arg{byte} -- 1 bytes of data (so the next byte in the cipher stream is byte
number \arg{byte}).

\subsection{Hash Functions / Message Authentication Codes}

Hash functions take their input without producing any output, only producing
anything when all input has already taken place. MACs are very similar, but are
additionally keyed. Both of these are derived from the base class
\type{BufferedComputation}, which has the following functions.

\noindent
\type{void} \function{update}(\type{const byte} \arg{input}[], \type{u32bit}
\arg{length})

\noindent
\type{void} \function{update}(\type{byte} \arg{input})

\noindent
\type{void} \function{update}(\type{const std::string \&} \arg{input})

Updates the hash/mac calculation with \arg{input}.

\noindent
\type{void} \function{final}(\type{byte} \arg{out}[OUTPUT\_LENGTH])

\noindent
\type{SecureVector<byte>} \function{final}():

Complete the hash/MAC calculation and place the result into \arg{out}.
OUTPUT\_LENGTH is a public constant in each object that gives the length of the
hash in bytes. After you call \function{final}, the hash function is reset to
it's initial state, so it may be reused immediately.

The second method of using final is to call it with no arguments at all, as
shown in the second prototype. It will return the hash/mac value in a memory
buffer, which will have size OUTPUT\_LENGTH.

There are also a pair of functions called \function{process}. They are
essentially a combination of a single \function{update}, and \function{final}.
Both version return the final value, rather than placing it an array. Calling
\function{process} with a single byte value isn't available, mostly because it
would rarely be useful.

A MAC can be viewed (in most cases) as simply a keyed hash function, so classes
which are derived from \type{MessageAuthenticationCode} have \function{update}
and \function{final} classes just like a \type{HashFunction} (and like a
\type{HashFunction}, after \function{final} is called, it can be used to make a
new MAC right away; the key is kept around).

A MAC has the \type{SymmetricAlgorithm} interface in addition to the
\type{BufferedComputation} interface.

\pagebreak

\section{Public Key Cryptography}

Public key algorithms were added in Botan 0.8.0. The major base classes can be
found in \filename{pubkey.h}.

\subsection{Creating PK Algorithm Key Objects}

The library has interfaces for encryption, signatures, etc that do not require
knowing the exact algorithm in use (for example RSA and Rabin-Williams
signatures are handled by the exact same code path).

One place where we \emph{do} need to know exactly what kind of algorithm is in
use is when we are creating a key (support for ASN.1 will remove this later
on). There are (currently) two kinds of public key algorithms in Botan: ones
based on integer factorization (RSA and Rabin-Williams), and ones based on the
discrete logarithm problem (DSA, Diffie-Hellman, Nyberg-Rueppel, and
ElGamal). Since discrete logarithm parameters (primes and generators) can be
shared among many keys, there is the notion of these being a combined type
(called \type{DL\_Group}).

There are two was to create a DL private key (such as
\type{DSA\_PrivateKey}). One is to pass in just a \type{DL\_Group} object -- a
new key will automatically be generated. The other involves passing in a group
to use, along with both the public and private values (private value first).

Since in integer factorization algorithms, the modulus used isn't shared by
other keys, we don't use this notion. You can create a new key by passing in a
\type{u32bit} telling how long (in bits) the key should be, or you can copy an
pre-existing key by passing in the appropriate parameters (primes, exponents,
etc). For RSA and Rabin-Williams (the two IF schemes in Botan), the parameters
are all \type{BigInt}s: prime 1, prime 2, encryption exponent, decryption
exponent, modulus. The last two are optional, since they can easily be derived
from the first three.

\subsubsection{Creating a DL\_Group}

There are quite a few ways to get a \type{DL\_Group} object. The best is to use
the function \function{get\_dl\_group}, which takes a string naming a group; it
will either return that group, if it knows about it, or throw an
exception. Names it knows about include ``IETF-n'' where n is 768, 1024, 1536,
2048, 3072, or 4096, and ``DSA-n'', where n is 512, 768, or 1024. The IETF
groups are the ones specified for use with IPSec, and the DSA ones are the
default DSA parameters specified by Java's JCE. For DSA and Nyberg-Rueppel, use
the ``DSA-n'' groups, and for Diffie-Hellman and ElGamal, use the ``IETF-n''
groups.

You can also generate a new random group. This is not recommend, because it is
very slow, particularly for ``safe'' primes, which are needed for
Diffie-Hellman and ElGamal.

You can register a new DL group with \function{add\_dl\_group} with a string
naming the group and the \type{DL\_Group}. Future lookups on that name will
return the group. There is no need (or reason) to register the group if you
do decide to use a distinct DL group for each key.

If you pass the wrong group type (for example a DSA-style group to a
Diffie-Hellman key object), it will throw an exception.

\subsection{Parameter Checking}

Most public key algorithms have limitations or restrictions on their
parameters. For example RSA requires an odd exponent, and algorithms based on
the discrete logarithm problem need a generator $> 1$.

Each low-level public key type has a function named
\function{check\_params}. This function returns a boolean value that declares
whether or not the key is valid (from an algorithmic standpoint). For example,
it will check to make sure that the prime parameters of a DSA key are, in fact,
prime. It does not have anything to do with the validity of the key for any
particular use, nor does it have anything to do with certificates which link a
key (which, after all, is just some numbers) with a user or other entity.

Checks which can be done quickly tend to be done in the constructors (an
exception will be thrown if an argument is checked in a constructor and found
to be invalid). Checking for primality, and a few other expensive things, are
saved for \function{check\_params}.

If the keys you use are already authenticated in some way (for example stored
in a user's encrypted key file, or signed by a CA), doing this is a needless
waste of CPU time. So, essentially, make sure you call \function{check\_params}
if you have any suspicions that the key might not be a valid one (and check the
return value, naturally).

\pagebreak

\subsection{Getting a PK algorithm object}

The key types, like \type{RSA\_PrivateKey}, do not implement any kind of
padding or encoding (which is generally necessary for security). To get an
object like this, the easiest thing to do is call the functions found in
\filename{look\_pk.h}. Generally these take a key, followed by a string that
specified what hashing and encoding method(s) to use. Examples of such strings
are ``EME1(SHA-1)'' for OAEP encryption and ``EMSA4(SHA-1)'' for PSS signatures
(where the message is hashed using SHA-1).

Here are some basic examples (using an RSA key) to give you a feel for the
possibilities. These examples assume \type{rsakey} is an
\type{RSA\_PrivateKey}, since otherwise we would not be able to create an
decryption or signature object with it (you can create encryption or signature
verification objects with public keys, naturally). Remember to delete these
objects when you're done with them.

\begin{verbatim}
   // PKCS #1 v2.0 / IEEE 1363 compatible encryption
   PK_Encryptor* rsa_enc1 = get_pk_encryptor(rsakey, ``EME1(RIPEMD-160)'');
   // PKCS #1 v1.5 compatible encryption
   PK_Encryptor* rsa_enc2 = get_pk_encryptor(rsakey, ``PKCS1v15'');

   // Raw encryption: no padding, input is directly encrypted by the key
   // Don't use this unless you know what you're doing
   PK_Encryptor* rsa_enc3 = get_pk_encryptor(rsakey, ``Raw'');

   // This object can decrypt things encrypted by rsa_enc1
   PK_Decryptor* rsa_dec1 = get_pk_decryptor(rsakey, ``EME1(RIPEMD-160)'');

   // PKCS #1 v1.5 compatible signatures
   PK_Signer* rsa_sig = get_pk_signer(rsakey, ``EMSA3(MD5)'');
   PK_Verifier* rsa_verify = get_pk_verifier(rsakey, ``EMSA3(MD5)'');

   // PKCS #1 v2.1 compatible signatures
   PK_Signer* rsa_sig2 = get_pk_signer(rsakey, ``EMSA4(SHA-1)'');
   PK_Verifier* rsa_verify2 = get_pk_verifier(rsakey, ``EMSA4(SHA-1)'');

   // Hash input with SHA-1, but don't pad the input in any way
   PK_Signer* rsa_sig = get_pk_signer(rsakey, ``EMSA1(SHA-1)'');
\end{verbatim}

Alternately, you can create the objects directly, like so:
\begin{verbatim}
   PK_Signer rsa_pss_sig(rsakey, ``EMSA4(SHA-1)'');
\end{verbatim}

This works for everything except the signature verification algorithms. That's
because they come in two categories: those with message recovery (RSA,
Rabin-Williams, Nyberg-Rueppel), and those without (DSA). \type{PK\_Verifier}
is an abstract class, unlike the other PK interface adapters. It is subclassed
by \type{PK\_Verifier\_wo\_MR} and \type{PK\_Verifier\_with\_MR}. So if you
want to create a verifier object without going through the
\function{get\_pk\_X} functions, you need to know what kind of key you're
using:

\begin{verbatim}
   PK_Verifier_with_MR rsa_sig1(rsakey, ``EMSA1(SHA-1)'');
   // type mismatch, compile time error:
   PK_Verifier_with_MR dsa_sig1(dsakey, ``EMSA1(SHA-1)'');
   // this one will work
   PK_Verifier_wo_MR dsa_sig2(dsakey, ``EMSA1(SHA-1)'');

\end{verbatim}

\pagebreak

\subsection{Encryption}

The \type{PK\_Encryptor} and \type{PK\_Decryptor} classes are the interface for
encryption and decryption, respectively.

Calling \function{encrypt} with a \type{byte} array and a length parameter will
return the input encrypted with whatever scheme is being used. Calling the
similar \function{decrypt} will perform the inverse operation. You can also do
these operations with \type{SecureVector<byte>}s. In all cases, the output is
returned via a \type{SecureVector<byte>}.

If you attempt an operation with a larger size than the key can support (this
limit varies based on the algorithm, the key size, and the padding method used
(if any)), an exception will be throw. Alternately, you can call
\function{maximum\_input\_size}, which will return the maximum size you can
safely encrypt. In fact, you can often encrypt an object that is one byte
longer, but only if enough of the high bits of the leading byte are set to
zero.

Available public key encryption algorithms in Botan are RSA and ElGamal. The
encoding methods are EME1, denoted by ``EME1(HASHNAME)'', PKCS \#1 v1.5,
called ``PKCS1v15'' or ``EME-PKCS1-v1\_5'', and raw encoding (``Raw'').

For compatibility reasons, PKCS \#1 v1.5 is recommend for use with ElGamal
(most other implementations of ElGamal do not support any other encoding
format). RSA can also be used with PKCS encoding, but because of various
possible attacks, EME1 is the preferred encoding. EME1 requires the use of a
hash function: unless a competent applied cryptographer tells you otherwise,
you should use SHA-1.

Don't use ``Raw'' encoding unless you need it for backwards compatibility with
old protocols. There are many possible attacks against both ElGamal and RSA
when they are used this way.

\subsection{Signatures}

The signature algorithms look quite a bit like the hash functions. You can
repeatedly call \function{update}, giving more and more of a message you wish
to sign, and then call \function{signature}, which will return a signature for
that message. If you want to do it all in one shot, call
\function{sign\_message}, which will just call update with it's argument and
then return whatever \function{signature} returns.

You can validate a signature by updating the verifier class, and finally seeing
the if the value returned from \function{valid\_signature} is true (you pass
the supposed signature to the \function{valid\_signature} function as a byte
array and a length). There is another function, \function{verify\_message},
which takes a pair of byte array/length pairs, the first of which is the
message, the second being the (supposed) signature. It returns true if the
signature is valid and false otherwise.

Available public key signature algorithms in Botan are RSA, DSA,
Nyberg-Rueppel, and Rabin-Williams. Signature encoding methods include EMSA1,
EMSA2, EMSA3, EMSA4, and Raw. All of them, except Raw, take a parameter naming
a message digest function to hash the message with. Raw actually signs the
input directly; if the message is too big, the signing operation will fail. Raw
is not useful except in specialized applications.

There are various interactions which make certain encoding schemes and signing
algorithms more or less useful.

EMSA2 is the usual method for encoding Rabin-William signatures, so for
compatibility with other implementations you may have to use that. EMSA4 (also
called PSS), also works with Rabin-Williams. EMSA1 and EMSA3 do \emph{not} work
with Rabin-Williams.

RSA can be used with any of the available encoding methods. EMSA4 is by far the
most secure, but is not (as of now) widely implemented. EMSA3 (also called
``EMSA-PKCS1-v1\_5'') is commonly used with RSA (for example in SSL). EMSA1
signs the message digest directly, without any extra padding or encoding. This
may be useful, but is not as secure as either EMSA3 or EMSA4. EMSA2 may be used
but is not recommended.

For DSA and Nyberg-Rueppel, you should use EMSA1. None of the other encoding
methods are particularly useful for these algorithms.

\subsection{Key Agreement}

You can get ahold of a \type{PK\_Key\_Agreement\_Scheme} object by calling
\function{get\_pk\_kas} with a key that is of a type that supports key
agreement (such as a Diffie-Hellman key stored in a \type{DH\_PrivateKey}
object), and the name of a key derivation function. This can be ``Raw'',
meaning the output of the primitive itself is returned as the key, or
``KDF1(hash)'' or ``KDF2(hash)'' where ``hash'' is any string you happen to
like (hopefully you like strings like ``SHA-1'' or ``RIPEMD-160'').

How key agreement generally works is that you trade public values with some
other party, and then each of you runs a computation with the other's value and
your key (this should return the same result to both parties). This computation
can be called by using \function{derive\_key} with either a byte array/length
pair, or a \type{SecureVector<byte>} than holds the public value of the other
party. The last argument to either call is a number that specifies how long a
key you want.

Depending on the key derivation function you're using, you many not
\emph{actually} get back a key of that size. In particular, ``Raw'' will return
a number about the size of the Diffie-Hellman modulus, and KDF1 can only return
a key which is the same size as the output of the hash. KDF2, on the other
hand, will always give you a key exactly as long as you request, regardless of
the underlying hash used with it. The key returned is a \type{SymmetricKey},
ready to pass to a block cipher, MAC, or other symmetric algorithm.

The public value which should be used can be obtained by calling
\function{public\_data}, which exists for any key that is associated with a
key agreement algorithm. It returns a \type{SecureVector<byte>}.

KDF2 is by far the preferred algorithm for key derivation in new algorithms.

\pagebreak

\section{Filters}

\subsection{Basic Filter Usage}

Up until this point, using Botan would be very tedious; to do anything you
would have to bother with putting data into arrays, doing whatever you want
with it, and then sending it someplace. The filter metaphor (defining a series
of operations which take some amount of input, process it, then send it along
to the next filter) works very well in this situation. If you've ever used a
Unix system, the usage of filters in Botan should be very intuitive (and even
if you haven't, don't worry, it's pretty easy). For instance, here is how you
encrypt a file with Blowfish in CBC mode with PKCS\#7 padding, then encode it
with Base64 and send it to standard output (we assume that \verb|file| is an
open \type{istream}):

\begin{verbatim}
SymmetricKey key(16);
BlockCipherModeIV iv(8); // or use: block_size_of(``Blowfish'')
Pipe encryptor(new CBC_Encryption(``Blowfish'', ``PKCS7'', key, iv),
               new Base64_Encoder);
encryptor.start_msg();
file >> encryptor;
encryptor.end_msg(); // flush buffers, complete computations
cout << encryptor;
\end{verbatim}

\type{Pipe} works in conjunction with the \type{Filter} class (for example, the
\type{CBC\_Encryption} and \type{Base64\_Encoder} types used above are
\type{Filter}s), but you never have to deal with them directly; Pipe handles
all the required housekeeping.

A useful ability of Pipe is to split up the work up into what are called
``messages''. Messages are blocks of data that are processed in an identical
fashion (ie, with the same sequence of \type{Filter}s). Messages are delimited
by the \function{start\_msg} and \function{end\_msg} functions, as shown
above. There are two different ways to make use of messages. One is to send
several messages through a Pipe without changing the Pipe's configuration, so
you end up with a sequence of messages; one use of this would be to send a
sequence of identically encrypted UDP packets, for example (note that the
\emph{data} need not be identical; it is just that each is encrypted, encoded,
signed, etc in an identical fashion). Another is to change the filters that are
used in the Pipe between each message, by adding or removing Pipes; functions
that let you do this are documented a bit later in this section.

Besides the istream input operator \texttt{>>} used in the example above, there
are input operators for \type{FILE} objects and also Unix file descriptors (if
the \texttt{pipe\_unixfd} module was compiled into Botan). All of these pull
all available data out of the file and put it into the Pipe in one big
shot. Alternately, you can put data in a bit at a time with three functions,
all called \function{write}. One takes a \type{std::string}, another a single
\type{byte}, and the last an array of \type{byte}s and a length parameter.

There are a fairly large number of ways to pull processed data out of a Pipe.
One can use file output operators similar to the input operators described
above, as well as a wide variety of \function{read} calls (these functions may
not always return the full amount requested; they will always return a
\type{u32bit} telling how many bytes were written into the buffer). These are
split into two main flavors: ones that take a message number, and those that do
not. If a read call does not take a message number, it will read from whatever
message has been designated as the ``default read message'', using the
\function{set\_default\_msg} function (\function{default\_msg} returns this
value). This is also important to do for using the file output operators, since
these operators will always read from the default read message. The function
\function{read\_all\_as\_string} returns the entire message as a
\type{std::string}, and \function{read\_all} returns the same, as a
\type{SecureVector<byte>}.

Additionally, you can query the exact number of bytes in a message using
\function{remaining}. There are also a pair of functions called \function{peek}
which allow you to look at the contents of a message without removing it from
the Pipe.

You can reuse a \type{Pipe} by calling it's \function{reset} function, which
restores a pipe to it's initial state of no filters (writing into the
\type{Pipe} and then reading will give you back your data unchanged). This
usually isn't too useful, so you can use the functions \function{append} and
\function{prepend} to add filters to the Pipe again. The \function{pop}
function will pop the first \type{Filter} off of the pipe. You can call
\function{append} and \function{prepend} as many times as you like; each filter
added will be attached to the end or beginning (respectively) of the current
set of filters (note that you can use these functions even if you haven't
called \function{reset}). You can only use these stack-like functions while the
Pipe is ``unlocked'', that is, not in the middle of processing a message.

Pipe's full interface definition can be found in \filename{pipe.h}

\subsection{Fork}

It's fairly common that you might receive some data and want to perform more
than one operation on it (ie, encrypt it with DES and calculate the MD5 hash of
the plaintext at the same time). That's where \type{Fork} comes in. \type{Fork}
is a filter that takes it's input and passes it on to \emph{one or more}
\type{Filter}s which are attached to it. \type{Fork} changes the nature of the
pipe system completely. Instead of being a linked list, it becomes a tree.

Before messages were added to Botan, using Fork was significantly more
complicated, requiring you to keep pointers to Fork objects you allocated and
sending control information to them when you wanted to read your output. Now,
however, things are much simpler. Each Filter in the fork is given it's own
output buffer, and thus it's own message. For example, if you have previously
written two messages into a Pipe, then you start a new one with a Fork which
has three paths of Filter's inside it, you add three new messages to the Pipe.
The data you put into the Pipe is duplicated and sent into each set of Filters,
and the eventual output is placed into a dedicated message slot in the Pipe.

The \texttt{hasher} and \texttt{hasher2} examples show two different ways of
using Pipe and Fork.

There is a very useful (and previously undocumented) trick that you can do with
\type{Fork}. Let's say you had some data that had been encrypted with a block
cipher, and then hex encoded. In addition, a hex encoded MAC of the plaintext
had been calculated and included with the message. You not only want to decrypt
the data, you want to verify the MAC. So the first two filters in the pipe will
decode the hex, and decrypt the raw ciphertext. But now, how are you going to
both a) get the plaintext, and b) calculate the MAC of the plaintext? This is
actually very simple, if a bit obscure.

What you have to do is, after the filters that do the initial decoding, create
a \type{Fork}. For the first argument, pass a null pointer. The fork object
will understand that this means that you don't want to do any more processing
on that line of the fork; you just want the data that was placed in. And then
in the second argument you would pass in a \type{MAC\_Filter} so you could
compute a MAC of the plaintext.

For an example of this technique, look at the \texttt{rsa\_dec} example in
\filename{doc/examples/}.

Any \type{Filter}s which are attached to the \type{Pipe} after the \type{Fork}
are implicitly attached onto the first branch created by the fork. For example,
let's say you created this \type{Pipe}:

\begin{verbatim}
Pipe pipe(new Fork(new Hash_Filter(``MD5''), new Hash_Filter(``SHA-1'')),
          new Hex_Encoder);
\end{verbatim}

And then called \function{start\_msg}, inserted some data, then
\function{end\_msg}. Then \arg{pipe} would contain two messages. The first one
(message number 0) would contain the MD5 sum of the input in hex encoded form,
and the other would contain the SHA-1 sum of the input in raw binary.

\subsection{Chain}

\type{Chain} is about as simple as it gets. \type{Chain} creates a chain of
\type{Filter}s and encapsulates them inside a single filter (itself). This is
primarily useful for passing a sequence of filters into something which is
expecting only a single \type{Filter} (most notably, \type{Fork}). You can call
\type{Chain}'s constructor with up to 4 \type{Filter*}s (they will be added in
order), or with an array of \type{Filter*}s and a \type{u32bit} which tells
\type{Chain} how many \type{Filter*}s are in the array (again, they will be
attached in order).

See the next section for an example of using \type{Chain}.

\pagebreak

\subsection{A Filter Example}

Here is some code which takes one or more filenames as it's arguments and
calculates the result of several hash functions for each file. The complete
program can be found as \filename{hasher.cpp} in the Botan distribution. For
brevity, most error checking has been removed.

\begin{verbatim}
   string name[3] = { "MD5", "SHA-1", "RIPEMD-160" };
   Botan::Filter* hash[3] = {
      new Botan::Chain(new Botan::Hash_Filter(name[0]),
                        new Botan::Hex_Encoder),
      new Botan::Chain(new Botan::Hash_Filter(name[1]),
                        new Botan::Hex_Encoder),
      new Botan::Chain(new Botan::Hash_Filter(name[2]),
                        new Botan::Hex_Encoder) };

   Botan::Pipe pipe(new Botan::Fork(hash, COUNT));

   for(u32bit j = 1; argv[j] != 0; j++)
      {
      ifstream file(argv[j]);
      pipe.start_msg();
      file >> pipe;
      pipe.end_msg();
      file.close();
      for(u32bit k = 0; k != 3; k++)
         {
         pipe.set_default_msg(k);
         cout << name[k] << "(" << argv[j] << ") = " << pipe << endl;
         }
      }
\end{verbatim}

\pagebreak

\subsection{Rolling Your Own}

Well, now that you know how filters work in Botan, you might want to write
your own. Lucky for you, all of the hard work is done by the \type{Filter} base
class, leaving you to handle the details of what your filter is supposed to
do. Remember that if you get confused about any of this, you can always look at
the implementation of Botan's filters to see exactly how everything works.

There are basically only four functions that a filter need worry about:

\noindent
\type{void} \function{write}(\type{byte} \arg{input}[], \type{u32bit}
\arg{length}):

The \function{write} function is what is called when a filter receives input
for it to process. The filter is \emph{not} required to process it right away;
many filters buffer their input before producing any output. A filter will
usually have \function{write} called many times during it's lifetime.

\noindent
\type{void} \function{send}(\type{byte} \arg{output}[], \type{u32bit}
\arg{length}):

Eventually, a filter will want to produce some output to send along to the next
filter in the pipeline. It does so by calling \function{send} with whatever it
wants to send along to the next filter. There is also a version of
\function{send} taking a single byte argument, as a convenience.

\noindent
\type{void} \function{start\_msg()}:

This function is optional. Implement it if your Filter would like to do some
processing or setup at the start of each message (for an example, see the Zlib
compression module).

\noindent
\type{void} \function{end\_msg()}:

Implementing the \function{end\_msg} function is optional. It is called when it
has been requested that filters finish up their computations. Note that they
must \emph{not} deallocate their resources; this should be done by their
destructor. They should simply finish up with whatever computation they have
been working on (for example, a compressing filter would flush the compressor
and \function{send} the final block), and empty any buffers in preparation for
processing a fresh new set of input. It is essentially the inverse of
\function{start\_msg}.

Additionally, if necessary, filters can define a constructor that takes any
needed arguments, and a destructor to deal with deallocating memory, closing
files, etc.

There is also a \type{BufferingFilter} class (in \filename{buf\_filt.h}) which
will take a message and split it up into an initial block which can be of any
size (including zero), a sequence of fixed sized blocks of any non-zero size,
and last (possibly zero-sized) final block. This might make a useful base class
for your filters, depending on what you have in mind.

\pagebreak

\subsection{Filter Catalog}

This section contains descriptions of every \type{Filter} included in Botan.
Note that modules which provide \type{Filter}s are documented elsewhere --
these \type{Filter}s are available on any installation of Botan.

\subsubsection{Keyed Filters}

A few sections ago, it was mentioned that Pipe can process multiple messages,
treating each of them exactly the same. Well, that was a bit of a lie. There
are some algorithms (in particular, block ciphers not in ECB mode, and all
stream ciphers) that change their state as data is put through them.

Naturally, you might well want to reset the keys or (in the case of block
cipher modes) IVs used by such filters, so multiple messages can be processed
using completely different keys, or new IVs, or new keys and IVs, or whatever.
And in fact, even for a MAC or an ECB block cipher, you might well want to
change the key used from message to message.

Enter \type{Keyed\_Filter}. It's a base class of any filter that is keyed:
block cipher modes, stream ciphers, MACs, whatever. It has two functions,
\function{reset\_key} and \function{reset\_iv}. Calling \function{reset\_key}
will, naturally, reset the key used by the algorithm. Reseting the IV only
makes sense in certain algorithms -- calling \function{reset\_iv} will cause an
exception if the filter in question doesn't support it.

Here's a slightly edited fragment of code from the \filename{rsa\_dec} example
application. For the complete source, look in \filename{doc/examples} in the
distribution.

\begin{verbatim}
   Keyed_Filter *cast, *hmac;
   Pipe pipe(new Base64_Decoder,
             // Note the assignments to the cast and hmac variables
             cast = new CBC_Decryption("CAST-128", "PKCS7", cast_key, iv),
             new Fork(
                0, // Read the section 'Fork' to understand this
                new Chain(
                   hmac = new MAC_Filter("HMAC(SHA-1)", mac_key, 12),
                   new Base64_Encoder
                   )
                )
      );
   pipe.start_msg();
   [use pipe for a while, decrypt some stuff, derive new keys and IVs]
   pipe.end_msg();

   cast->reset_key(cast_key2);
   cast->reset_iv(iv2);
   hmac->reset_key(mac_key2);

   pipe.start_msg();
   [use pipe for some other things]
   pipe.end_msg();
\end{verbatim}

There is a requirement to using \type{Keyed\_Filter} which you must follow. If
you call \function{reset\_key} or \function{reset\_iv}, you must do so while
the Pipe is ``unlocked''. This refers to the times when no messages are being
processed by Pipe -- either before Pipe's \function{start\_msg} is called, or
after \function{end\_msg} is called (and no new call to \function{start\_msg}
has happened yet). Doing otherwise will result in undefined behavior, probably
silently getting invalid output.

\pagebreak

\subsubsection{Basic Wrappers}

Stream ciphers, hash functions, and MACs don't need anything special when it
comes to filters. Stream ciphers take their input, encrypt it, and send it
along to the next \type{Filter}. Hash functions and MACs both take their input
and produce no output until \function{end\_msg()} is called, at which time they
complete the hash or MAC and send that as output.

These \type{Filter}s take a string naming the type to be used. If for some
reason you name something that doesn't exist, an exception will be thrown.
Generally speaking you can use any obvious name here, like ``SHA-1'', ``ARC4'',
``HMAC(SHA-1)'', or even really odd recursive things like
``EMAC(Lion(SHA-1,SEAL(8),1024))'', just as long as it's well formed and in the
end everything resolves to the correct type.

\noindent
\function{StreamCipher\_Filter}(\type{std::string} \arg{cipher},
                                \type{const StreamCipher\_Key\&} \arg{key})

Pretty basic; key \arg{cipher} with \arg{key}, anything passed through the
filter is encrypted with the stream cipher.

\noindent
\function{Hash\_Filter}(\type{std::string} \arg{hash},
                        \type{u32bit} \arg{outlength}):

This type hashes it's input with \arg{hash}. When \function{end\_msg} is called
on the owning \type{Pipe}, the hash is completed and the digest is sent on to
the next thing in the pipe. The argument \arg{outlength} specifies how much of
the output of the hash will be passed along to the next filter when
\function{end\_msg} is called. By default, it will pass the entire hash.

\noindent
\function{MAC\_Filter}(\type{std::string} \arg{mac},
                       \type{const MAC\_Key\&} \arg{key},
                       \type{u32bit} \arg{outlength}):

The constructor for a \type{MAC\_Filter} takes a key, used in calculating the
MAC, and a length parameter, which has semantics exactly the same as the one
passed to \type{Hash\_Filter}s constructor.

These filters can be found in \filename{filters.h}.

\pagebreak

\subsubsection{Cipher Modes}

For block ciphers, the situation is more complicated. Because ECB mode is
dangerous (a message may be easily altered without detection and similar
plaintext encrypts to similar ciphertext), block ciphers must usually be used
in a different mode. The modes provided with Botan are CBC, CTS, CFB, OFB, and
CTR. They are presented in \filename{cbc.h}, \filename{cts.h},
\filename{cfb.h}, \filename{ofb.h}, and \filename{ctr.h}.

Only their constructors are interesting; other than that they are just like any
other filter, and are used like any other discussed in this documentation. Each
one takes a \type{std::string} as the first argument. This names the cipher to
be used to encryption/decryption. The constructors to the decryption filters
are identical to that of the encryption modes (the types are named
\type{MODENAME\_Decryption}).

\noindent

\parskip 0pt
\noindent
\function{CBC\_Encryption}(\type{std::string} \arg{cipher},
                           \type{std::string} \arg{padding},

\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 
                           \type{const BlockCipher\_Key\&} \arg{key},
                           \type{const BlockCipherModeIV\&} \arg{iv}):
\parskip 5pt

This is quite simple: a key, of a length suitable for the cipher, and an IV,
which is the size of the cipher block (if it is not an exception will be
thrown).

The second string, \arg{padding}, specifies what kind of padding to use at the
end of the block. The three currently defined padding methods are ``PKCS7'',
``OneAndZeros'', and ``NoPadding''. If ``NoPadding'' is used, then the object
will throw an exception if it's input is not an exact multiple of the cipher's
block size -- don't use it unless you have to.

Some padding methods can only work with block ciphers that have certain block
sizes (for example, ``PKCS7''), while others (such as ``OneAndZeros'') will
work for any size block cipher. If the chosen block cipher/padding method pair
cannot work together, a \type{Invalid\_Block\_Size} exception will be thrown by
the constructor.

Additionally, a \type{DecodingError} exception can be thrown when
\function{end\_msg()} is called on the decrypting CBC filter, if the input data
was not formatted correctly.

\noindent
\function{CTS\_Encryption}(\type{std::string} \arg{cipher},
                           \type{const BlockCipher\_Key\&} \arg{key},
                           \type{const BlockCipherModeIV\&} \arg{iv}):

CTS (Cipher Text Stealing) mode is the same as CBC except for the last 2
blocks. It uses a neat little trick to make it so that the ciphertext is always
the same size as the plaintext. It does not use any external padding method, so
that argument isn't needed.

\noindent
\parskip=0pt
\function{CFB\_Encryption}(\type{std::string} \arg{cipher},
                           \type{const BlockCipher\_Key\&} \arg{key},
                           \type{const BlockCipherModeIV\&} \arg{iv},

\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 
                           \type{u32bit} \arg{feedback}):
\parskip=5pt

This is similar to CBC, but it takes an (optional) additional argument, the
size of the feedback (it will default to the full blocksize of the cipher being
used). This value is given in bytes, and can range from 1 to BLOCK\_SIZE. If
the \arg{feedback} is not a valid amount, \type{Invalid\_Argument} will be
thrown. The ciphertext will always be the same size of the plaintext.

\noindent
\function{OFB}(\type{std::string} \arg{cipher},
               \type{const BlockCipher\_Key\&} \arg{key},
               \type{const BlockCipherModeIV\&} \arg{iv}):

This is the usual OFB mode. Variable feedback sizes are not supported, as it
has been shown that they are insecure. The \type{CTR} mode is a variant of
\type{OFB}, whose constructor takes the same arguments. Remember that a block
cipher operating in either OFB or counter modes is like a stream cipher, and
thus you must never encrypt two messages with the same key without changing the
IV. Since OFB and CTR are their own inverses, there is no need for separate
encryption and decryption classes.

\noindent
\function{ECB\_Encryption}(\type{std::string} \arg{cipher},
                           \type{const BlockCipher\_Key\&} \arg{key})

Don't use this mode unless you know what you are doing. For the vast majority
of applications, it is \emph{insecure}. You can find the \type{ECB\_Encryption}
and \type{ECB\_Decryption} filters in \filename{ecb.h}.

\pagebreak

\subsubsection{PK Filters}

There are four classes in this category, \type{PK\_Encryptor\_Filter},
\type{PK\_Decryptor\_Filter}, \type{PK\_Signer\_Filter}, and
\type{PK\_Verifier\_Filter}. Each takes a pointer to an object of the
appropriate type (\type{PK\_Encryptor}, \type{PK\_Decryptor}, etc) which is
deleted by the destructor. These classes are found in \filename{pk\_filts.h}.

Three of these, for encryption, decryption, and signing are pretty much
identical conceptually. Each of them buffers it's input until the end of the
message is marked with a call to the \function{end\_msg} function. Then they
encrypt, decrypt, or sign their input and send the output (the ciphertext, the
plaintext, or the signature) into the next filter.

Signature verification works a little differently, because it needs to know
what the signature is in order to check it. You can either pass this in along
with the constructor, or call the function \function{set\_signature} -- with
this second method, you need to keep a pointer to the filter around so you can
send it this command. In either case, after \function{end\_msg} is called, it
will try to verify the signature (if the signature has not been set by either
method, an exception will be thrown here). It will then send a single byte onto
the next filter -- a 1 or a 0, which specifies whether the signature verified
or not (respectively).

For more information about PK algorithms (including creating the appropriate
objects to pass to the constructors), read the section ``Public Key
Cryptography'' in this manual.

\subsubsection{Encoders}

Often you want your data to be in some form of text (for sending over channels
which aren't 8-bit clean, printing it, etc). The filters \type{Hex\_Encoder}
and \type{Base64\_Encoder} will convert arbitrary binary data into hex or
base64 formats. Not surprisingly, you can use \type{Hex\_Decoder} and
\type{Base64\_Decoder} to convert it back into it's original form.

Both of the encoders can take a few options about how the data should be
formatted (all of which have defaults). The first is a \type{bool} which simply
says if the encoder should insert line breaks. This defaults to
false. Line breaks don't matter either way to the decoder, but it makes the
output a bit more appealing to the human eye, and a few transport mechanisms
(notably some email systems) limit the maximum line length.

The second encoder option is an integer specifying how long such lines will be
(obviously this will be ignored if line-breaking isn't being used). The default
tends to be in the range of 60-80 characters, but is not specified exactly. If
you want a specific value, set it. Otherwise the default should be fine.

Lastly, \type{Hex\_Encoder} takes an argument of type \type{Case}, which can be
\type{Uppercase} or \type{Lowercase} (default is \type{Uppercase}). This
specifies what case the characters A-F should be output as. The base64 encoder
has no such option, because it uses both upper and lower case letters for it's
output.

You can find the declarations for these types in \filename{hex.h} and
\filename{base64.h}.

\pagebreak

\section{Random Number Generators}

The random number generators provided in Botan are meant for creating keys,
IVs, padding, nonces, and anything else which requires 'random' data. It is
important to remember that the output of these classes will vary, even if they
are supplied with exactly the same seed (ie, two Randpool objects with similar
initial states will not produce the same output).

To ensure good quality output, you need to seed the RNG with truly 'random'
data, such as timing data from hardware. Preferably, you should use an
\type{EntropySource} (see below).

To add entropy to a RNG, you can use \type{void}
\function{add\_entropy}(\type{const byte} \arg{data}[], \type{u32bit}
\arg{length}) or (better), use the \type{EntropySource} interface.

One a RNG has been initialized, you can get a single byte of random data by
calling \type{byte} \function{random()}, or get a large block by calling
\type{void} \function{randomize}(\type{byte} \arg{data}[], \type{u32bit}
\arg{length}), which will put random bytes into each member of the array from
indexes 0 $\ldots$ \arg{length} -- 1.

\subsection{The Global RNG}

Botan maintains a global RNG that is used internally for things like
generating secret keys and salts. In addition, it is automatically seeded by
the \type{LibraryInitializer}. Most of the time, you won't need to access it
directly because the library handles the common cases where randomness is
needed for you, but you might want to for a complicated application.

To use it, include \filename{rng.h}. You can't get a pointer to the actual
global RNG object, because it is guarded with a mutex for thread safety, so the
interface basically defines a set of entry points into the object. All of them
are in the namespace \texttt{Global\_RNG}, which is inside the \texttt{Botan}
namespace. So you might call them as \texttt{Botan::Global\_RNG::function}, or
if you have a \texttt{using} declaration to include Botan objects into the
global namespace, just \texttt{Global\_RNG::function}.

There are four functions, two for adding entropy and two for getting randomness
out.

\vskip 5pt
\noindent
\type{void} \function{Global\_RNG::randomize}(\type{byte} \arg{buf[]},
                                              \type{u32bit} \arg{size}):

Get \arg{size} bytes of random bytes from the global RNG and put it into
\arg{buf}.

\vskip 5pt
\noindent
\type{byte} \function{Global\_RNG::random}():

Return a single random byte.

\vskip 5pt
\noindent
\type{void} \function{Global\_RNG::add\_entropy}(\type{const byte} \arg{buf[]},
                                                 \type{u32bit} \arg{size}):

Add the contents of \arg{buf}, which is of size \arg{size}, into the global
RNG's internal state.

\vskip 5pt
\noindent
\type{void} \function{Global\_RNG::add\_entropy}(\type{EntropySource\&}
                        \arg{es}, \type{bool} \arg{slow\_poll}):

Poll \arg{es} for entropy. If \arg{slow\_poll} is true, then do a slow poll,
otherwise do a fast poll. Fast polling is useful if you have a long-running
process (like a server), and you don't want to take a long time to do a poll,
but you want to make sure that you don't run out of entropy. The RNGs included
in Botan \emph{should} be resistant to analysis even if large amounts of
output are available to an attacker, as long as the initial seeding added
enough entropy to prevent brute-force attacks on the seed. But caution is
always wise when dealing with RNGs.

\pagebreak

\subsection{Randpool}

\type{Randpool} is based around a large pool of data and a hash function (which
used to be MD5, but is now HAVAL). It is slower than \type{ANSI\_X917\_RNG} but
can easily satisfy any reasonable demand (100 kilobytes per second on a 4 year old
machine). Because the internal state of \type{Randpool} is much larger than
\type{ANSI\_X917\_RNG}, it is more likely to be secure, and it is recommended
that \type{Randpool} be used over \type{ANSI\_X917\_RNG} in most cases.

\subsection{ANSI X9.17}

\type{ANSI\_X917\_RNG} is based on the algorithm given in Annex C of the ANSI
X9.17 standard, which makes use of a block cipher. \type{ANSI\_X917\_RNG} can
produce bits about four times as fast as \type{Randpool}.

The version used is a variant of the normal X9.17; most importantly, only a
portion of the output of the block cipher is actually given to the caller (then
a new block is computed), the timestamp is encrypted in CBC mode instead of ECB
mode, and that after a \type{ANSI\_X917\_RNG} object has generated a certain
number of bytes (384 at the time of this writing), it will automatically rekey
itself using it's internal state. These alterations make any attack much harder
(at the cost of reducing speed).

The block cipher used for internal operation is AES. Formerly the block cipher
could be chosen by the user, but it was felt that AES provides a sufficient
security/speed balance for most applications.

\pagebreak

\subsection{Entropy Sources}

An \type{EntropySource} is an abstract representation of some method of gather
``real'' entropy. This tends to be very system dependent. The \emph{only} way
you should use an \type{EntropySource} is to pass it to a RNG that will extract
entropy from it -- never use the output directly for any kind of key or nonce
generation!

\type{EntropySource} has a pair of functions for getting entropy from some
external source, called \function{fast\_poll} and \function{slow\_poll}. You
can use an \type{EntropySource} to seed a RNG by calling \type{void}
\function{add\_entropy}(\type{EntropySource\&} \arg{source}, \type{bool}
\arg{slow}). This tells the RNG to ask the \type{EntropySource} for some amount
of random data.

If \arg{slow} is \type{true}, the RNG will ask \function{slow\_poll} to gather
a fairly large amount of data; otherwise \function{fast\_poll} will be called
in order to get some basic information quickly. Seeding the RNG with a slow
poll at least once (when your application starts up, for example) is a
\emph{highly} recommended idea, because it ensures that your RNG is in a good
(ie, highly random and unpredictable) state.

The \type{EntropySource} must not write more data into the array than was
requested (otherwise memory not owned by the process will probably be written
to), however, it can write less (for instance, if it cannot collect enough
data, or collecting that much would take too long). For this reason, the
\function{get\_entropy} function returns how much data it actually wrote (which
will never be more than the \arg{length} field passed to the function).

Note for writers of \type{EntropySource}s: it isn't necessary to use any kind
of cryptographic hash on your output. The data produced by an EntropySource is
only used by an application after it has been hashed by the
\type{RandomNumberGenerator} which asked for the entropy, and thus any hashing
you do will be wasteful of both CPU cycles and possibly entropy.

\pagebreak

\section{Miscellaneous}

This section has documentation for anything that just didn't fit into any of
the major categories. Many of them (Timers, Allocators) will rarely be used
in actual application code, but others, like the S2K algorithms, have a wide
degree of applicability.

\subsection{S2K Algorithms}

There are various procedures (usually fairly ad-hoc) for turning a passphrase
into a (mostly) arbitrary length key for a symmetric cipher. A general
interface for such algorithms is presented in \filename{s2k.h}. The main
function is \function{derive}, which takes a passphrase, and the desired length
of the output key, and returns a key of that length, deterministically produced
from the passphrase.

Most such algorithms allow the use of a ``salt'', which provides some extra
randomness and helps against dictionary attacks on the passphrase. Simply call
\function{change\_salt} (there are variations of it for most of the ways you
might wish to specify a salt, check the header for details) with a block of
random data.

Additionally some algorithms allow you to set some sort of iteration count,
which will make the algorithm take longer to compute the final key (reducing
the speed of brute-force attacks of various kinds). A note of warning: the only
currently implemented S2K algorithm, the one specified for OpenPGP (in
\filename{pgp\_s2k.h}), uses the iteration count in a strange manner; instead
of specifying how many times to iterate the hash, it tells how many
\emph{bytes} should be hashed in total (including the salt). So the exact
iteration count will depend on the size of the salt (which is fixed at 8 bytes
for OpenPGP, though the implementation will allow any salt size) and the size
of the passphrase.

To get what OpenPGP calls ``Simple S2K'', set iterations to 0 (the default for
OpenPGP S2K), and do not specify a salt. To get ``Salted S2K'', again leave the
iteration count at 0, but give an 8-byte salt. ``Salted and Iterated S2K''
requires an 8-byte salt and some iteration count (this should be significantly
larger than the size of the longest passphrase that might reasonably be used;
somewhere from 1024 to 65536 would probably be about right).

While OpenPGP's S2K algorithm supports both salting and iterating, not all S2K
algorithms will. However, if they do not support such things, they will simply
ignore the number of iterations and/or the salt (ie, you can call
\function{change\_salt} on any S2K object without fear of an exception because
that particular S2K doesn't support salting).

\subsection{Checksums}

Checksums are very similar to hash functions, and in fact share the same
interface. But there are some significant differences, the major ones being
that the output size is very small (usually in the range of 2 to 4 bytes), and
is not cryptographically secure. But for their intended purpose (error
checking), they perform very well. Some examples of checksums included in Botan
are the Adler32 and CRC32 checksums.

\subsection{Exceptions}

Sooner or later, something is going to go wrong. Botan's behavior when
something unusual occurs, like most C++ software, is to throw an exception.
Exceptions in Botan are derived from it's \type{Exception} class. You can see
most of the major varieties of exceptions used in Botan by looking at
\filename{exceptn.h}. The only function you really need to concern yourself
with is \type{const char*} \function{what()}. This will return an error message
relevant to the error that occurred. For example:

\begin{verbatim}
try {
   // various Botan operations
   }
catch(Botan::Exception& e)
   {
   cout << "Botan exception caught: " << e.what() << endl;
   // error handling, or just abort
   }
\end{verbatim}

Botan's exceptions are derived from \type{std::exception}, so you don't need
to explicitly check for Botan exceptions if you're already catching the ISO
standard ones.

\subsection{Threads and Mutexes}

Botan includes a mutex system, which is used internally to lock some shared
data structures which must be kept shared for efficiency reasons (mostly, these
are in the allocation systems - handing out 1000 separate allocators hurts
performance and makes caching memory blocks useless). This system is supported
by the mutex\_pthread module, implementing the \type{Mutex} interface for
systems that have POSIX threads.

You can ensure the entire system uses real mutexes (the default mutex type is
just a stub), by calling the function \function{set\_mutex\_type} with a
pointer to a new mutex type. For example, calling
\function{set\_mutex\_type}(new \type{Pthread\_Mutex}) will make all calls to
\function{get\_mutex} return a pointer to a Pthread\_Mutex, so real locking
will occur. In single-threaded code, this will just make things slower, but it
is necessary if you wish to use Botan in multi-threaded code. Make sure you
call this before calling anything else in Botan; in particular, set the mutex
type before creating any allocators.

In the future, this will be done by the \type{LibraryInitializer} class, so you
won't have to worry about it yourself, but for the moment you still have to do
it explicitly.

\subsection{Secure Memory}

A major concern with mixing modern multiuser OSes and cryptographic code is
that at any time the code (including secret keys) could be swapped to disk,
where it can later be read by an attacker. Botan stores almost everything (and
especially anything sensitive) in memory buffers which a) clear out their
contents when their destructors are called, and b) have easy plugins for
various memory locking functions, such as the \function{mlock}(2) call on many
Unix systems.

These classes should also be used within your own code for storing sensitive
data. They are only meant for primitive data types (int, long, etc): if you
want a container of higher level Botan objects, you can just use a
\verb|std::vector|, since these objects know how to clear themselves when they
are destroyed. You cannot, however, have a \verb|std::vector| (or any other
container) of \type{Pipe}s or \type{Filter}s, because these types have pointers
to other \type{Filter}s, and implementing copy constructors for these types
would be both hard and quite expensive (vectors of pointers to such objects is
fine, though).

These types are not described in any great detail: for more information,
consult the definitive sources -- the header files \filename{secmem.h} and
\filename{allocate.h}.

\type{SecureBuffer} is a simple array type, whose size is specified at compile
time. It will automatically convert to a pointer of the appropriate type, and
has various useful functions, including \function{clear()}, and \type{u32bit}
\function{size()}, which returns the length of the array. It is a template that
takes as parameters a type, and a constant integer which is how long the array
is (for example: \verb|SecureBuffer<byte, 8> key;|).

\type{SecureVector} is a variable length array. It's size can be increased or
decreased as need be, and it has a wide variety of functions useful for copying
data into it's buffer. Like \type{SecureBuffer}, it implements \function{clear}
and \function{size}.

\subsection{Allocators}

The containers described above get their memory from allocators. As a user of
the library, you can add new allocator methods at run time for containers,
including the ones used internally by the library, to use. The interface to
this is in \filename{allocate.h}. Basically how it works is that code needing
an allocator uses \function{get\_allocator} and \function{release\_allocator}
to get and release an allocator. It is possible to call
\function{get\_allocator} with a specific name to request a particular type of
allocator, otherwise, a default allocator type is returned.

At start time, the only allocator known is a \type{Default\_Allocator}, which
just allocates memory using malloc, and memsets it to 0 when the memory is
released. It is known by the name ``default''.

You can add in a new allocator type using \function{add\_allocator\_type}. This
function takes a string and a pointer to an allocator. The string gives this
allocator type a name to which it can be referred when one is requesting it
with \function{get\_allocator}. If an error occurs (such as the name being
already registered), this function returns false. It will return true if the
allocator was successfully registered. If you ask it to,
\type{LibraryInitializer} will do this for you.

Finally, you can set the default allocator type that will be returned by
calling \function{set\_default\_allocator}. If you call this with the name of
any previously registered allocator, that allocator type will be returned by
\function{get\_allocator}. Actually, \function{get\_allocator} will walk down a
list of possibilities, starting with it's argument, then the default that was
set with \function{set\_default\_allocator}, then a hardcoded ``default'' to
help ensure that an allocator is always available.

\subsection{Timers}

Botan includes a pair of functions, \function{system\_time} and
\function{system\_clock}, which are used extensively in some areas of the code
(especially in the random number generators). These functions by default use
\function{std::time} and \function{std::clock}, but often you can do better
with system-dependent functions, especially for the system clock (for example,
returning the microseconds value from \function{gettimeofday}, or the
nanoseconds value from the POSIX.1b \function{clock\_gettime}, is far
superior). Modules for this exist for several systems.

You can register a new timer method with \function{set\_timer\_type}. For
example, if the \texttt{timer\_unix} module is available, one could call
\function{set\_timer\_type}(new \type{Unix\_Timer}), in which case
\function{system\_clock} will return a more ``interesting'' value based on the
return of the \function{gettimeofday} function call.

Unless you ask it not to, \type{LibraryInitializer} will handle finding a timer
and installing it for you.

\pagebreak

\section{Botan's Modules}

Botan comes with a variety of modules which can be compiled into the system.
These will not be available on all installations of the library, but you can
check for their availability based on whether or not certain macros are
defined.

\subsection{Pipe I/O for Unix}

This is a fairly minor feature, but it comes in handy sometimes. Botan's
\type{Pipe} object overloads the \texttt{<<} and \texttt{>>} operators for
both C++ iostream objects and C-style FILE objects.

Since we're supporting every other form of ``file object'' in the known C/C++
universe, we might as well directly support I/O with Unix file descriptors.
Really, this is more valuable than supporting FILE objects, since it's a rare
thing that can be represented as a FILE and not an iostream. This is most
useful when using you want to read from or write to something like a TCP or
Unix-domain socket, since for simple file access it's usually easier to just
use C++'s file streams.

If \macro{BOTAN\_EXT\_PIPE\_UNIXFD\_IO} is defined, then you can use the
overloaded I/O operators with Unix file descriptors. For an example of this,
check out the \texttt{hash\_fd} example, included in the Botan distribution.

\subsection{Entropy Sources}

\noindent
\type{EGD\_EntropySource}: Query an EGD socket. If the macro
\texttt{BOTAN\_EXT\_ENTROPY\_SRC\_EGD} is defined, it can be found in
\filename{es\_egd.h}. The constructor takes a \type{std::string} that specifies
the path to look for an EGD socket. Of the three entropy sources available as
modules, this is the best one to use (if EGD is running on the system).

\noindent
\type{Unix\_EntropySource}: This entropy source executes various programs
common on Unix systems (such as \texttt{uptime}, \texttt{vmstat}, and
\texttt{df}) and adds it to a buffer. It's quite slow due to process overhead,
and (roughly) 1 bit of real entropy is contained in each byte that is
output. It is declared in \filename{es\_unix.h}, if
\texttt{BOTAN\_EXT\_ENTROPY\_SRC\_UNIX} is defined. If you don't have
\filename{/dev/random} \emph{or} EGD, this is probably the thing to use. For a
long-running process, keep on object of this type around and run fast polls
ever few minutes.

\noindent
\type{FTW\_EntropySource}: Walk through a filesystem (the root to start
searching is passed as a string to the constructor), reading files. This tends
to only be useful on things like \filename{/proc} which have a great deal of
variability over time, and even then there is only a small amount of entropy
gathered: about 1 bit of entropy for every 16 bits of output (and many hundreds
of bits are read in order to get that 16 bits). It is declared in
\filename{es\_ftw.h}, if \texttt{BOTAN\_EXT\_ENTROPY\_SRC\_FTW} is
defined. Only use this as a last resort. I don't really trust it, and neither
should you.

\subsection{Compressors}

There are two compression algorithms supported by Botan, Zlib and Bzip2 (Gzip
and Zip encoding will be supported in future releases). Only lossless
compression algorithms are currently supported by Botan, because they tend to
be the most useful for cryptography. However, it is very reasonable to consider
supporting something like GSM speed encoding (which is lossy), for use in
encrypted voice applications.

You should always compress \emph{before} you encrypt, because encryption seeks
to hide the redundancy that compression is supposed to try to find and remove.

\subsubsection{Bzip2}

To test for Bzip2, check to see if \macro{BOTAN\_EXT\_COMPRESSOR\_BZIP2} is
defined. If so, you can include \filename{bzip2.h}, which will declare a pair
of \type{Filter} objects: \type{Bzip2\_Compression} and
\type{Bzip2\_Decompression}.

You should be prepared to take an exception when using the decompressing
filter, for if the input is not valid Bzip2 data, that is what you will
receive. You can specify the desired level of compression to
\type{Bzip2\_Compression}'s constructor as an integer between 1 and 9, 1
meaning worst compression, and 9 meaning the best. The default is to use 9,
since small values take the same amount of time, just use a little less memory.

The Bzip2 module was contributed by Peter J. Jones.

\subsubsection{Zlib}

Zlib compression works pretty much like Bzip2 compression. The only differences
in this case are that the macro is \macro{BOTAN\_EXT\_COMPRESSOR\_ZLIB}, the
header you need to include is called \filename{botan/zlib.h} (remember that you
shouldn't just \verb|#include <zlib.h>|, or you'll get the regular zlib API,
which is not what you want). The types are called \type{Zlib\_Compression} and
\type{Zlib\_Decompression}.

Like Bzip2, a \type{Zlib\_Decompression} object will throw an exception if
invalid (in the sense of not being in the Zlib format) data is passed into it.

In the case of zlib's algorithm, a worse compression level will be faster than
a very high compression ratio. For this reason, the Zlib compressor will
default to using a compression level of 6. This tends to give a good trade off
in terms of time spent to compression achieved. There are several factors you
need to consider in order to decide if you should use a higher compression
level:

\begin{list}{*}
  \item Better security: the less redundancy in the source text, the harder it
        is to attack your ciphertext. This is not too much of a concern,
        because with decent algorithms using sufficiently long keys, it doesn't
        really matter \emph{that} much (but it certainly can't hurt).
  \item

  \item Decreasing returns. Some simple experiments by the author showed
        minimal decreases in the size between level 6 and level 9 compression
        with large (1 to 3 megabyte) files. There was some difference, but it
        wasn't that much.

  \item CPU time. Level 9 zlib compression is often two to four times as slow
        as level 6 compression. This can make a substantial difference in the
        overall runtime of a program.

\end{list}

While the zlib compression library uses the same compression algorithm as the
gzip and zip programs, the format is different. The zlib format is defined in
RFC 1950.

\pagebreak

\section{Recommended Algorithms}

This section is by no means the last word on selecting which algorithms to use.
However, Botan includes a sometimes bewildering array of possible algorithms,
and unless you're familiar with the latest developments in the field, it can be
hard to know what is secure and what is not. The following attributes of the
algorithms were evaluated when making this list: security, standardization,
patent status, efficiency, and support by other implementations (in roughly
that order).

It is intended as a set of useful guidelines for developers and nothing more.

\begin{list}{*}
  \item Block ciphers: TripleDES, AES, or CAST-128 in CBC mode with ``PKCS7''
        padding.
  \item

  \item Stream Ciphers: Use any of the recommended block ciphers in CTR mode.

  \item Hash functions: SHA-1, SHA2-256, SHA2-512

  \item MACs: HMAC with any recommended hash function

  \item Public Key Encryption: RSA with EME1 and SHA-1

  \item Public Key Signatures: RSA with EMSA4, or DSA with EMSA1, using
        any recommended hash function

  \item Key Agreement: Diffie-Hellman, with KDF2 and SHA-1

\end{list}

\pagebreak

\section{BigInt}

\type{BigInt} is Botan's implementation of a multiple-precision
integer. Thanks to C++'s operator overloading features, using \type{BigInt} is
often quite similar to using a native integer type. The number of functions
related to \type{BigInt} is quite large. You can find most of them in
\filename{bigint.h} and \filename{numthry.h}.

Due to the sheer number of functions involved, only a few, which a regular user
of the library might have to deal with, are mentioned here.

Probably the most important are the encoding/decoding functions, which
transform the normal representation of a \type{BigInt} into some other form,
such as a decimal string. The most useful of these functions are
\type{SecureVector<byte>} \function{encode}(\type{BigInt}, \type{Encoding}) and
\type{BigInt} \function{decode}(\type{SecureVector<byte>},
\type{Encoding}). \type{Encoding} is an enum which has values \type{Binary},
\type{Decimal}, and \type{Hexadecimal}. The parameter will default to
\type{Binary}.

There are also C++-style I/O operators defined for use with
\type{BigInt}. Unlike \type{Pipe}, there are no operators for working with
C-style \type{FILE} objects or Unix file descriptors. The input operator
understands negative numbers, hexadecimal numbers (marked with a leading
``0x''), and octal numbers (marked with a leading '0'). The '-' must come
before the ``0x'' or '0' marker. The output operator will never adorn the
output; for example, when printing a hexadecimal number, there will not be a
leading ``0x'' (though a leading '-' will be printed if the number is
negative). If you want such things, you'll have to do them yourself.

\type{BigInt} has constructors that can create a \type{BigInt} from an unsigned
integer or a string. You can also decode a \type{byte}[] / length pair into a
BigInt. There are several other \type{BigInt} constructors, which I would
seriously recommend you avoid, as they are only intended for use internally by
the library, and may arbitrarily change, or be removed, in a future release.

An essentially random sampling of \type{BigInt} related functions:

\type{u32bit} \function{BigInt::bytes}(): Return the size of this \type{BigInt}
in bytes.

\type{BigInt} \function{random\_prime(\type{u32bit} \arg{b})}: Return a prime
number \arg{b} bits long.

\type{BigInt} \function{gcd}(\type{BigInt} \arg{x}, \type{BigInt} \arg{y}):
Returns the greatest common divisor of \arg{x} and \arg{y}. Uses the binary
GCD algorithm.

\type{bool} \function{is\_prime}(\type{BigInt} \arg{x}): Returns true if
\arg{x} is a (possible) prime number. Uses the Miller-Rabin probabilistic
primality test with fixed bases. For higher assurance, use
\function{verify\_prime}, which uses more rounds and randomized 48-bit bases.

\type{BigInt} \function{inverse\_mod}(\type{BigInt} \arg{x}, \type{BigInt}
\arg{m}): Returns $y$ such that $x \cdot y \equiv 1 \bmod m$, or 0 if no such
$y$ exists.

\subsection{Efficiency Hints}

If you can, always use expressions of the form \verb|a += b| over
\verb|a = a + b|. The difference can be \emph{very} substantial, because the
first form prevents at least one needless memory allocation, and possibly as
many as three.

If you're doing repeated modular exponentiations with the same modulus, create
a \type{BarrettReducer} ahead of time. If the exponent or base is a constant,
use the classes in \filename{mod\_exp.h}. This stuff is all handled for you by
the normal high-level interfaces, of course.

\subsection{Warning}

Don't ever even consider using the low-level MPI functions (those that begin
with \texttt{bigint\_}). These are completely internal to the library, and make
arbitrarily strange and undocumented assumptions about their inputs, and not
check to see if they are actually true, on the assumption that only the library
itself calls them, and that the library knows what the assumptions are. The
interfaces for these functions can change completely without notice. These
functions aren't visible without effort on your part specifically to that end,
so you will get no sympathy if you decide to use any of them.

\pagebreak

\section{Removing Algorithms}

You may well want to remove some of Botan's algorithms in order to fit it into
a memory-constrained system, where you're counting the kilobytes. For the most
part, this is trivial to do, and Botan's interface makes it easy for
applications to test for the presence of an algorithm at runtime, so a
well-behaved application can work without any need for porting on such an
version of Botan.

Removing things like the PK signature encoding schemes (EMSA2, EMSA3...) is
somewhat more complicated and not documented here. This tutorial (of sorts)
will go through the steps required to compile a version of Botan without the
Blowfish block cipher.

The first step is to remove the files \filename{include/blowfish.h}, 
\filename{src/blowfish.cpp}, and \filename{src/blfs\_tab.cpp}, which actually
implement the algorithm. Then minor editing of \filename{src/algolist.cpp} is
required. First, remove the line that includes the Blowfish header. Then look
in \function{load\_algorithms\_list} for the code that adds a Blowfish block
cipher object to the internal lookup table, and remove it. Run the configure
script and then make the library. Tada! Done.

So how does an application test for such a situation? The first is to simply
try to pass the name ``Blowfish'' to constructor of \type{CBC\_Encryption} or
other Botan Filter, and catch the resulting exception. This is not particularly
flexible, though. If an application wants to check on the status of Botan's
support for a particular algorithm, it can call some status functions found in
\filename{lookup.h}, called \function{have\_block\_cipher},
\function{have\_stream\_cipher}, \function{have\_hash}, and
\function{have\_mac}, passing in the name of the desired algorithm. If Botan
knows about it, the function will return true.

There are a handful of algorithms which are considered ``sacred'', in that an
application can always expect that they exist, and a distributor or other
end-user should not remove them without considering the possibly serious
consequences. At this time, these are: AES (Rijndael), DES, TripleDES, SHA-1,
and HMAC(SHA-1). This allows a workable fallback strategy for
applications. Note that no stream ciphers are currently safe from removal.

One other useful application of this is to remove patented algorithms, for
example if Botan were to be included as part of a commercial Linux
distribution.

For the most part, applications don't have to really worry about this, simply
because the cases this will be required are fairly rare. Checking for the
availability of patented algorithms like RC5, RC6, and SEAL before using them
might be a good idea, though.

Another advantage of this is that an application can be written to take
advantage of an algorithm which is not yet part of Botan, like the MARS block
cipher or the Panama stream cipher. If it's not available, one can simply fall
back on another algorithm, and when/if it is added to Botan, the application
will start using it automagically.

\pagebreak

\section{Writing Modules}

It's a lot simpler to write modules for Botan that it is to write code in the
core library, for several reasons. First, a module can rely on external
libraries and services beyond the base ISO C++ libraries, and also machine
dependent features (assembler, anyone?). Also, the code can be added at
configuration time on the user's end with very little effort (ie the code can
be distributed separately and without depending on patching anything).

Creating a module is quite simple. First, there must be a subdirectory in the
\filename{modules} directory for it. The name of the module is the same as the
name of this directory. Inside this directory, there needs to be a file, with
exactly the same name as the directory (that's so the configuration script
knows where to look). This file contains various directives it uses to specify
what this module does, what systems it runs on, and so on. Comments start with
a \verb|#| character and continue to end of line.

Recognized directives include:

\newcommand{\directive}[2]{
   \vskip 4pt
   \noindent
   \texttt{#1}: #2
}

\directive{realname <name>}{Specify that the 'real world' name of this module
   is \texttt{<name>}}

\directive{note <note>}{Add a note that will be seen by the end-user at
configure time}

\directive{define <macro>}{Define \texttt{BOTAN\_EXT\_<macro>} in
   \filename{config.h}. This may only be used if the module creates
   user-visible changes. There is a set of conventions that should be followed
   in deciding what to call this macro (where xxx denotes some descriptive and
   distinguishing characteristic of the thing implemented, such as
   \texttt{ALLOC\_MLOCK} or \texttt{MUTEX\_PTHREAD}):

\begin{itemize}
\item Allocator: \texttt{ALLOC\_xxx}
\item Compressors: \texttt{COMPRESSOR\_xxx}
\item EntropySource: \texttt{ENTROPY\_SRC\_xxx}
\item Mutex: \texttt{MUTEX\_xxx}
\item Timer: \texttt{TIMER\_xxx}
\end{itemize}
}

\directive{link\_to <lib>}{The module needs to link against this library (can
   be used multiple times). The C, C++, and math libraries are linked by
   default, so you don't need to specify those}

\directive{needs\_std <std>}{Specify that the module requires the abilities of
   \texttt{<std>}. Values currently known are ``posix1'', ``posix1b'', and
   ``pthreads''}

\directive{add\_file <file>}{Tell the configuration script to add the file
   given into the source tree. This file must exist in the module directory}

\directive{ignore\_file <file>}{Tell the configuration script to ignore the
   file given in the main source tree}

\directive{replace\_file <file>}{Tell the configuration script to ignore the
   file given in the main source tree, and instead use the one in the module's
   directory}

\directive{patch\_file <file> <patch>}{Tell the configuration script to patch
   the file named (in the main source tree) with the patch given. The patch
   filename must end with ``.dif''. The patch file is recommended to be (but is
   not required to be) a context diff. The system's patch program is used, so
   it should be a widely used format if at all possible}

\vskip 10pt
\noindent
Additionally, the module file can contain blocks, delimited by
the following pairs:

\texttt{<os> / </os>}, \texttt{<arch> / </arch>}, \texttt{<cc> / </cc>}

\noindent
For example, putting ``alpha'' and ``ia64'' in a \texttt{<arch>} block will
make the configuration script only allow the module to be compiled on those
architectures. Not having a block means any value is acceptable.

\pagebreak

\section{More Information}

\subsection{Support}

Questions or problems you have with Botan can be directed to the development
mailing list (currently called \texttt{opencl-devel}). Joining this list is
highly recommended if you're going to be using Botan, since often advance
notice of upcoming changes is sent there. ``Philosophical'' bug reports,
announcements of programs using Botan, and basically anything else having to do
with Botan are also welcome.

If you would like to pay for extensions, consulting, or other support, they can
be obtained direct from the source at very reasonable rates; email
\texttt{lloyd@randombit.net} for information.

\subsection{Compatibility}

Generally, cryptographic algorithms are well standardized, and thus
compatibility between implementations is relatively simple (of course, not all
algorithms are supported by all implementations). But there are a few
algorithms which are poorly specified, and these should be avoided if you wish
your data to be processed in the same way by another implementation (including
future versions of Botan).

The block cipher GOST has a particularly poor specification: there are no
standard Sboxes, and the specification does not give test vectors even for
sample boxes, which leads to issues of endian conventions, etc. Other
algorithms including in Botan suffering from these problems (though to a less
serious degree) include HAVAL, ISAAC, and EMAC.

If you wish maximum portability between different implementations of an
algorithm, it's best to stick to strongly defined and well standardized
algorithms: TripleDES, CAST-128, Rijndael, HMAC, RIPEMD-160, and SHA-1 all
being good examples.

\subsection{Patents}

Some of the algorithms implemented by Botan are covered by patents. Algorithms
known to be patented in the United States or other countries (where the patent
holder has not granted royalty-free use for any purpose) include: IDEA, MISTY1,
RC5, RC6, SEAL, and Nyberg-Rueppel. Note that just because an algorithm is not
listed here, you must not assume that it is not encumbered by patents.

\subsection{Further Reading and Information}

It's a very good idea if you have some knowledge of cryptography prior to
trying to use this stuff. You really should read one or more of these books
before seriously using the library (note that the Handbook of Applied
Cryptography is available online in it's entirety):

\setlength{\parskip}{5pt}

\noindent
\textit{Handbook of Applied Cryptography}, by Alfred J. Menezes,
Paul C. Van Oorschot, and Scott A. Vanstone; CRC Press

\noindent
\textit{Cryptography: Theory and Practice}, by Douglas R. Stinson; CRC Press

\noindent
\textit{Applied Cryptography, 2nd Ed.}, by Bruce Schneier; John Wiley \& Sons

\noindent
Once you've got the basics down, these are good things to at least take a look
at: IEEE 1363 and 1363a, PKCS \#1 v2.1, SCAN, NESSIE, the relevant RFCs.

\pagebreak

\subsection{Contact Information}

A PGP DSA key with a fingerprint of
\verb|33E3 9768 1D13 E7B4 1A01 BBCE A63F 2CBD FA02 FBCC| is used to sign all
Botan releases. This key can be found in the file \filename{doc/pgpkeys.asc};
PGP keys for the developers are also stored there.

\vskip 5pt \noindent
Main email contact: \verb|lloyd@randombit.net|

\vskip 5pt \noindent
Botan Web Site: \verb|http://botan.randombit.net|

\vskip 5pt \noindent
Botan Download Page (HTTP): \verb|http://botan.randombit.net/download.php|

\end{document}
