For \textit{3DES} exists a two-key mode, that can be initialized by calling the setup function with a \textit{keylen} of 16. This results in the re-usage of key \textit{K1} as key \textit{K3}. This mode has been specified as \textit{Keying Option 2} in FIPS 46-3.
Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time. These options are found in
the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8\times32$ s-boxes. This means that a scheduled
key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
chunk sensitive. That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size. In the CBC case, you must manually pad the end of your message (either with
zeroes or with whatever your protocol requires).
To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
\subsection{IV Manipulation}
To change or read the IV of a previously initialized chaining mode use the following two functions.
LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media. It is meant to have efficient seeking and overcome the
security problems of ECB mode while not increasing the storage requirements. It is used much like any other chaining mode except with two key differences.
The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long). The second key
$K_2$ is the \textit{tweak} key and is always 16 octets long. The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.
This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$\textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$\textit{tweak}.
These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa). The length is specified by \textit{len} in octets but must be a multiple
These will get or set the 16--octet IV. Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation. It requires
updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
As of v1.17, LibTomCrypt supports XTS mode with code donated by Elliptic Semiconductor Inc.\footnote{www.ellipticsemi.com}.
XTS is a chaining mode for 128--bit block ciphers, recommended by IEEE (P1619)
for disk encryption. It is meant to be an encryption mode with random access to the message data without compromising privacy. It requires two private keys (of equal
length) to perform the encryption process. Each encryption invocation includes a sector number or unique identifier specified as a 128--bit string.
To initialize XTS mode use the following function call:
\index{xts\_start()}
\begin{verbatim}
int xts_start( int cipher,
const unsigned char *key1,
const unsigned char *key2,
unsigned long keylen,
int num_rounds,
symmetric_xts *xts)
\end{verbatim}
This will start the XTS mode with the two keys pointed to by \textit{key1} and \textit{key2} of length \textit{keylen} octets each.
To encrypt or decrypt a sector use the following calls:
\index{xts\_encrypt()}\index{xts\_decrypt()}
\begin{verbatim}
int xts_encrypt(
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
const unsigned char *tweak,
symmetric_xts *xts);
int xts_decrypt(
const unsigned char *ct, unsigned long ptlen,
unsigned char *pt,
const unsigned char *tweak,
symmetric_xts *xts);
\end{verbatim}
The first will encrypt the plaintext pointed to by \textit{pt} of length \textit{ptlen} octets, and store the ciphertext in the array pointed to by
\textit{ct}. It uses the 128--bit tweak pointed to by \textit{tweak} to encrypt the block. The decrypt function performs the opposite operation. Both
functions support ciphertext stealing (blocks that are not multiples of 16 bytes).
The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.
To terminate the XTS state call the following function:
The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers. It behaves much like CTR mode in that it XORs a keystream
against the plaintext to encrypt. F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}. We
initialize F8 mode with the following function call:
This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter. It uses the \textit{salt\_key} as IV encryption key
(\textit{m} in the RFC 3711). The salt\_key can be shorter than the secret key but it should not be longer.
These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified. The length is specified in bytes and does not have to be a multiple
These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start(). The purpose of these two functions is to be
able to seek within a current session only. If you want to change the session IV you will have to call f8\_done() and then start a new state with
f8\_start().
To terminate an F8 state call the following function:
It is initialized with a random \textit{nonce} that can be shared publicly, a \textit{header} which can be fixed and public, and a random secret symmetric key.
The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages). It can
be added at anytime during an EAX stream, and is part of the authentication tag. That is, changes in the meta-data can be detected by changes in the output tag.
The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
called a \textit{tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
of operation.
The mode is initialized with the following function.
This initializes the CCM state \textit{ccm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
chosen must have a 16--byte block size (e.g., AES).
Unlike EAX and OCB mode, CCM is only meant for \textit{packet} mode where the length of the input is known in advance. This is why the length of the stream
to authenticate is given as \textit{ptlen}.
With CCM, a header is meta--data you want to send with the message but not have encrypted. The header len is given in the init
After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector. It should be unique per packet encrypted.
This adds the nonce (a.k.a. salt) \textit{nonce} of length \textit{noncelen} octets to the CCM state \textit{ccm}. Note that this function must be called
once and only once.
\subsection{Additional Authentication Data}
The header is meta--data you want to send with the message but not have encrypted, it must be stored in \textit{adata} of length \textit{adatalen} octets.
This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{CCM\_ENCRYPT} the plaintext is read,
encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{CCM\_DECRYPT} the opposite occurs.
Galois counter mode is an IEEE proposal for authenticated encryption (also it is a planned NIST standard). Like EAX and OCB mode, it can be used in a streaming capacity
however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed. This mode also only works with
A GCM stream is meant to be processed in three modes, one after another. First, the initialization vector (per session) data is processed. This should be
unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
\subsection{Initialization}
To initialize the GCM context with a secret key call the following function.
\index{gcm\_init()}
\begin{verbatim}
int gcm_init( gcm_state *gcm,
int cipher,
const unsigned char *key,
int keylen);
\end{verbatim}
This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
chosen must have a 16--byte block size (e.g., AES).
\subsection{Initialization Vector}
After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector. It should be unique per packet encrypted.
\index{gcm\_add\_iv()}
\begin{verbatim}
int gcm_add_iv( gcm_state *gcm,
const unsigned char *IV,
unsigned long IVlen);
\end{verbatim}
This adds the initialization vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}. You can call this function as many times as required
to process the entire IV.
Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done. If you want to minimize per packet latency it is ideal
to only use 12--byte IVs. You can just increment it like a counter for each packet.
\subsection{Additional Authentication Data}
After the entire IV has been processed, the additional authentication data can be processed. Unlike the IV, a packet/session does not require additional
authentication data (AAD) for security. The AAD is meant to be used as side--channel data you want to be authenticated with the packet. Note: once
you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
\index{gcm\_add\_aad()}
\begin{verbatim}
int gcm_add_aad( gcm_state *gcm,
const unsigned char *adata,
unsigned long adatalen);
\end{verbatim}
This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
\subsection{Plaintext Processing}
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
\index{gcm\_process()}
\begin{verbatim}
int gcm_process( gcm_state *gcm,
unsigned char *pt,
unsigned long ptlen,
unsigned char *ct,
int direction);
\end{verbatim}
This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext. The length of both are equal and stored in \textit{ptlen}. Depending on
the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa). When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read,
encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
\subsection{State Termination}
To terminate a GCM state and retrieve the message authentication tag call the following function.
\index{gcm\_done()}
\begin{verbatim}
int gcm_done( gcm_state *gcm,
unsigned char *tag,
unsigned long *taglen);
\end{verbatim}
This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
\subsection{State Reset}
The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
\index{gcm\_reset()}
\begin{verbatim}
int gcm_reset(gcm_state *gcm);
\end{verbatim}
This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it. The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.
\subsection{One--Shot Packet}
To process a single packet under any given key the following helper function can be used.
\index{gcm\_memory()}
\begin{verbatim}
int gcm_memory(
int cipher,
const unsigned char *key,
unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
\end{verbatim}
This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
message tag. The definition of the variables is the same as it is for all the manual functions.
If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.
\subsection{Example Usage}
The following is an example usage of how to use GCM over multiple packets with a shared secret key.
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int send_packet(const unsigned char *pt, unsigned long ptlen,
const unsigned char *iv, unsigned long ivlen,
const unsigned char *aad, unsigned long aadlen,
gcm_state *gcm)
{
int err;
unsigned long taglen;
unsigned char tag[16];
/* reset the state */
if ((err = gcm_reset(gcm)) != CRYPT_OK) {
return err;
}
/* Add the IV */
if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
return err;
}
/* Add the AAD (note: aad can be NULL if aadlen == 0) */
if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm))
!= CRYPT_OK) {
whine_and_pout(err);
}
}
return EXIT_SUCCESS;
}
\end{verbatim}
\end{small}
\mysection{ChaCha20--Poly1305}
This authenticated encryption is based on ChaCha20 stream cipher and Poly1305 authenticator.
It is defined by \url{https://tools.ietf.org/html/rfc7539}.
\subsection{Initialization}
To initialize the ChaCha20--Poly1305 context with a secret key call the following function.
\index{chacha20poly1305\_init()}
\begin{verbatim}
int chacha20poly1305_init(chacha20poly1305_state *st,
const unsigned char *key,
unsigned long keylen);
\end{verbatim}
This initializes the ChaCha20--Poly1305 state \textit{st} with a secret key \textit{key} of length \textit{keylen}
octets (valid lengths: 32 or 16).
\subsection{Initialization Vector}
After the state has been initialized the next step is to add the initialization vector.
\index{chacha20poly1305\_setiv()}
\begin{verbatim}
int chacha20poly1305_setiv(chacha20poly1305_state *st,
const unsigned char *iv,
unsigned long ivlen);
\end{verbatim}
This adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
the ChaCha20--Poly1305 state \textit{st}.
\index{chacha20poly1305\_setiv\_rfc7905()}
\begin{verbatim}
int chacha20poly1305_setiv_rfc7905(chacha20poly1305_state *st,
const unsigned char *iv,
unsigned long ivlen,
ulong64 sequence_number);
\end{verbatim}
This also adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
the state \textit{st} but it also incorporates 64bit \textit{sequence\_number} into IV as described in RFC7905.
You can call only one of \textit{chacha20poly1305\_setiv} or \textit{chacha20poly1305\_setiv\_rfc7905}.
\subsection{Additional Authentication Data}
After the IV has been set, the additional authentication data can be processed.
\index{chacha20poly1305\_add\_aad()}
\begin{verbatim}
int chacha20poly1305_add_aad(chacha20poly1305_state *st,
const unsigned char *adata,
unsigned long adatalen);
\end{verbatim}
This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the ChaCha20--Poly1305 state \textit{st}.
\subsection{Encryption / Decryption}
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
\index{chacha20poly1305\_encrypt()}
\begin{verbatim}
int chacha20poly1305_encrypt(chacha20poly1305_state *st,
const unsigned char *in,
unsigned long inlen,
unsigned char *out);
\end{verbatim}
This encrypts the data where \textit{in} is the plaintext and \textit{out} is the ciphertext. The length of both are equal and stored in \textit{inlen}.
\index{chacha20poly1305\_decrypt()}
\begin{verbatim}
int chacha20poly1305_decrypt(chacha20poly1305_state *st,
const unsigned char *in,
unsigned long inlen,
unsigned char *out);
\end{verbatim}
This decrypts the data where \textit{in} is the ciphertext and \textit{out} is the plaintext. The length of both are equal and stored in \textit{inlen}.
\subsection{State Termination}
To terminate a ChaCha20--Poly1305 state and retrieve the message authentication tag call the following function.
\index{chacha20poly1305\_done()}
\begin{verbatim}
int chacha20poly1305_done(chacha20poly1305_state *st,
unsigned char *tag,
unsigned long *taglen);
\end{verbatim}
This terminates the ChaCha20--Poly1305 state \textit{st} and stores the tag in \textit{tag} of length \textit{taglen} octets (always 16).
\subsection{One--Shot Packet}
To process a single packet under any given key the following helper function can be used.
\index{chacha20poly1305\_memory()}
\begin{verbatim}
int chacha20poly1305_memory(const unsigned char *key,
unsigned long keylen,
const unsigned char *iv,
unsigned long ivlen,
const unsigned char *aad,
unsigned long aadlen,
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned char *tag,
unsigned long *taglen,
int direction);
\end{verbatim}
This will initialize the ChaCha20--Poly1305 state with the given key, IV and AAD value then proceed to
encrypt (\textit{direction} equals \textbf{CHACHA20POLY1305\_ENCRYPT}) or decrypt (\textit{direction} equals
\textbf{CHACHA20POLY1305\_DECRYPT}) the message text and store the final message tag. The definition of the
variables is the same as it is for all the manual functions.
\chapter{One-Way Cryptographic Hash Functions}
\mysection{Core Functions}
Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}. To initialize hash
XXX (where XXX is the name) call:
\index{Hash Functions}
\begin{verbatim}
void XXX_init(hash_state *md);
\end{verbatim}
This simply sets up the hash to the default state governed by the specifications of the hash. To add data to the message being hashed call:
\begin{verbatim}
int XXX_process( hash_state *md,
const unsigned char *in,
unsigned long inlen);
\end{verbatim}
Essentially all hash messages are virtually infinitely\footnote{Most hashes are limited to $2^{64}$ bits or 2,305,843,009,213,693,952 bytes.} long message which
are buffered. In the case where this limit is reached the \textit{XXX\_process()} function returns \textit{CRYPT\_HASH\_OVERFLOW}.
\index{CRYPT\_HASH\_OVERFLOW}
The data can be passed in any sized chunks as long as the order of the bytes are the same, the message digest (hash output) will be the same. For example, this means that:
user owning the process performing the request. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}. This will begin hashing from the current file pointer position, and
will not rewind the file pointer when finished. This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
The other hashes such as the SHA-2 (that includes SHA-512, SHA-512/384, SHA-384, SHA-512/256, SHA-256 and SHA-224) and TIGER-192 are still considered secure
The \textit{hmac} parameter is the state for the HMAC code. The \textit{hash} parameter is the index into the descriptor table of the hash you want
to use to authenticate the message. The \textit{key} parameter is the pointer to the array of chars that make up the key. The \textit{keylen} parameter is the
length (in octets) of the key you want to use to authenticate the message. To send octets of a message through the HMAC system you must use the following function:
The \textit{hmac} parameter is the HMAC state you are working with. The \textit{out} parameter is the array of octets where the HMAC code should be stored.
It is possible to use XCBC in a three key mode by OR'ing the value \textbf{LTC\_XCBC\_PURE} against the \textit{keylen} parameter. In this mode, the key is
interpretted as three keys. If the cipher has a block size of $n$ octets, the first key is then $keylen -2n$ octets and is the encryption key. The next
$2n$ octets are the $K_1$ and $K_2$ padding keys (used on the last block). For example, to use AES--192 \textit{keylen} should be $24+2\cdot16=56$ octets.
The three keys are interpretted as if they were concatenated in the \textit{key} buffer.
This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}. Like the other MAC functions,
the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
To compute the MAC tag value use the following function:
This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return \textbf{CRYPT\_OK} on success.
Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard. Originally specified to be used with the KASUMI block cipher, it can also be used
F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding. The padding quite simply is a direction
bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size. If the message is byte aligned, the padding takes on the form of
a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.
If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
with F9--MAC.
\subsection{F9--MAC Functions}
A F9--MAC state is initialized with the following function:
This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
To process data through F9--MAC use the following function:
\index{f9\_process()}
\begin{verbatim}
int f9_process( f9_state *state,
const unsigned char *in,
unsigned long inlen);
\end{verbatim}
This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}. Like the other MAC functions,
the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
To compute the MAC tag value use the following function:
\index{f9\_done()}
\begin{verbatim}
int f9_done( f9_state *state,
unsigned char *out,
unsigned long *outlen);
\end{verbatim}
This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}. The \textit{outlen} parameter
specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns. This will return
\textbf{CRYPT\_OK} on success.
Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
\index{f9\_memory()}
\begin{verbatim}
int f9_memory(
int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
To F9--MAC a file use
\index{f9\_file()}
\begin{verbatim}
int f9_file(
int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
\end{verbatim}
Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same rules as f9\_done().
To test f9--MAC for RFC 3566 compliance use the following function:
\index{f9\_test()}
\begin{verbatim}
int f9_test(void);
\end{verbatim}
This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
\textbf{CRYPT\_NOP}.
\mysection{Poly1305--MAC}
The Poly1305--MAC is a cryptographic message authentication code created by Daniel J. Bernstein.
More info at \url{https://en.wikipedia.org/wiki/Poly1305}.
A Poly1305--MAC state is initialized with the following function:
\index{poly1305\_init()}
\begin{verbatim}
int poly1305_init( poly1305_state *st,
const unsigned char *key,
unsigned long keylen);
\end{verbatim}
This will initialize the Poly1305--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (always 32).
To process data through Poly1305--MAC use the following function:
\index{poly1305\_process()}
\begin{verbatim}
int poly1305_process( poly1305_state *st,
const unsigned char *in,
unsigned long inlen);
\end{verbatim}
This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the Poly1305--MAC state pointed to by \textit{st}.
To compute the MAC tag value use the following function:
\index{poly1305\_done()}
\begin{verbatim}
int poly1305_done(poly1305_state *st,
unsigned char *mac,
unsigned long *maclen);
\end{verbatim}
This will retrieve the Poly1305--MAC tag from the state pointed to by \textit{st}, and store it in the array pointed to by \textit{mac}.
The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
the function returns.
Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
\index{poly1305\_memory()}
\begin{verbatim}
int poly1305_memory(const unsigned char *key,
unsigned long keylen,
const unsigned char *in,
unsigned long inlen,
unsigned char *mac,
unsigned long *maclen);
\end{verbatim}
This will compute the Poly1305--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
To Poly1305--MAC a file use
\index{poly1305\_file()}
\begin{verbatim}
int poly1305_file( const char *fname,
const unsigned char *key,
unsigned long keylen,
unsigned char *mac,
unsigned long *maclen);
\end{verbatim}
Which will Poly1305--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
\mysection{BLAKE2s + BLAKE2b MAC}
The BLAKE2s and BLAKE2b are cryptographic message authentication code designed by Jean--Philippe Aumasson,
Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. More info at \url{https://tools.ietf.org/html/rfc7693}.
A BLAKE2s/b--MAC state is initialized with the following function:
PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}. The
Just like the ciphers and hashes, you must register your prng before you can use it. The two functions provided work exactly as those for the cipher registry functions.
int register_prng(const struct _prng_descriptor *prng);
int unregister_prng(const struct _prng_descriptor *prng);
\end{verbatim}
The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error). It will avoid registering the same
descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once. The unregister function
will return \textbf{CRYPT\_OK} if the PRNG was found and removed. Otherwise, it returns \textbf{CRYPT\_ERROR}.
Which will try one of three methods of getting random data. The first is to open the popular \textit{/dev/random} device which
on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite. It emulates \textit{/dev/random} via the Microsoft CSP.}.
The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG. The third method is an ANSI C
clock drift method that is also somewhat popular but gives bits of lower entropy. The \textit{callback} parameter is a pointer to a function that returns void. It is
used when the slower ANSI C RNG must be used so the calling application can still work. This is useful since the ANSI C RNG has a throughput of roughly three
bytes a second. The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to. The function returns the number of bytes actually read from
\textbf{LTC\_PKCS\_1\_EME} to perform encryption padding. It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding. The \textit{modulus\_bitlen}
parameter indicates the length of the modulus in bits. The padded data is stored in \textit{out} with a length of \textit{outlen} octets. The output will not be
longer than the modulus which helps allocate the correct output buffer size.
Only encryption padding requires a PRNG. When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.
\subsection{PKCS \#1 v1.5 Decoding}
The following function performs PKCS \#1 v1.5 de--padding:
This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}. The decoded data is stored in \textit{out} of length
\textit{outlen}. If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored. The \textit{block\_type} parameter must be set to either
\textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.
\mysection{PKCS \#1 v2.1 Encryption}
PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
the library is concerned we are only dealing with th OAEP padding of the message.
\subsection{OAEP Encoding}
The following function performs PKCS \#1 v2.1 encryption padding:
The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537. Stick with 65537 since it is big enough to prevent
trivial math attacks, and not super slow. The \textit{key} parameter is where the constructed key is placed. All keys must be at
There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the
PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant). The second type, is a public RSA key which only includes the modulus and public exponent.
This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
(i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
Note: the output of this function is zero--padded as per PKCS \#1 specification. This allows this routine to work with PKCS \#1 padding functions properly.
import the key, strip off the additional data and fill in the \textit{rsa\_key} structure.
\index{rsa\_import\_pkcs8()}
\begin{verbatim}
int rsa_import_pkcs8(const unsigned char *in,
unsigned long inlen,
const void *passwd,
unsigned long passwdlen,
rsa_key *key);
\end{verbatim}
This function can import RSA private keys serialized in PKCS\#8 format.
It provides a \textit{password} parameter for the encrypted PKCS\#8 format, but this functionality is currently NOT implemented.
\index{rsa\_import\_x509()}
\begin{verbatim}
int rsa_import_x509(const unsigned char *in,
unsigned long inlen,
rsa_key *key);
\end{verbatim}
This function can import the RSA public key from a X.509 certificate.
\subsubsection{Import from plain big numbers}
\index{rsa\_set\_key()}
\begin{verbatim}
int rsa_set_key(const unsigned char *N,
unsigned long Nlen,
const unsigned char *e,
unsigned long elen,
const unsigned char *d,
unsigned long dlen,
rsa_key *key);
\end{verbatim}
This function can import the plain RSA key parameters \textit{N}, \textit{e} and \textit{d}.
The parameter \textit{d} is optional and only required when importing a private key.
\index{rsa\_set\_factors()}
\begin{verbatim}
int rsa_set_factors(const unsigned char *p,
unsigned long plen,
const unsigned char *q,
unsigned long qlen,
rsa_key *key);
\end{verbatim}
This function can import the plain RSA key factors \textit{p} and \textit{q}.
\index{rsa\_set\_crt\_params()}
\begin{verbatim}
int rsa_set_crt_params(const unsigned char *dP,
unsigned long dPlen,
const unsigned char *dQ,
unsigned long dQlen,
const unsigned char *qP,
unsigned long qPlen,
rsa_key *key);
\end{verbatim}
This function can import the plain RSA CRT (chinese remainder theorem) parameters \textit{dP}, \textit{dQ} and \textit{qP}.
After importing \textit{p}, \textit{q}, \textit{dP}, \textit{dQ} and \textit{qP}
the library can perfrom the optimized CRT calculations on private key operations.
\chapter{Diffie-Hellman Key Exchange}
\mysection{Background}
Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{}(\mbox{mod }p)$
generates a large sub-group of prime order (for unique values of $x$).
A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{}(\mbox{mod }p)$. The term
``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange
a shared key $K \equiv B_y^{A_x}\equiv A_y^{B_x}\equiv g^{A_xB_x}\mbox{}(\mbox{mod }p)$.
From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
$y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
$k' \equiv g^k\mbox{}(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{}(\mbox{mod }p)$ as a key to encrypt
the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
symmetric cipher.
It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
$r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
the sub-group generated is a large prime namely ${p -1}\over2$. Such primes are known as ``strong primes'' and the
smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
\mysection{Core Functions}
This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first set of routines
are to make a Diffie-Hellman private key pair:
\index{dh\_make\_key()}
\begin{verbatim}
int dh_set_pg_groupsize(int groupsize, dh_key *key);
int dh_generate_key(prng_state *prng, int wprng, dh_key *key);
\end{verbatim}
The ``groupsize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 1024 bytes which correspond
to key sizes of 768 to 8192 bits. The smaller the key the faster it is to use however it will be less secure. When
specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
above 512 it will return an error. So if you pass ``groupsize == 32'' it will use a 768 bit key but if you pass
``groupsize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
$p-1$ is equal to $2r$ where $r$ is a large prime. The bases are chosen to generate a group of order $r$ to prevent
leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
hard.
The next two routines are for exporting/importing Diffie-Hellman keys in/from DER encoded ASN.1. This is useful for transport
over communication mediums.
\index{dh\_export()}\index{dh\_import()}
\begin{verbatim}
int dh_export(unsigned char *out, unsigned long *outlen,
int type, dh_key *key);
int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
\end{verbatim}
The ASN.1 sequence used to represent a DH key is as following:
\begin{verbatim}
DiffieHellmanKey ::= SEQUENCE {
version Version,
flags Flags,
p INTEGER, -- prime
g INTEGER, -- base/group
n INTEGER -- either x when private key or y when public key }
Version ::= INTEGER { v1(0) }
Flags ::= BIT STRING {
privateKey (0) -- this BIT is '1' if it's a private key
-- or '0' if it's a public key
}
\end{verbatim}
These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails.
You can free a ``dh\_key'' using:
\begin{verbatim}
void dh_free(dh_key *key);
\end{verbatim}
After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
with the other user using:
\index{dh\_shared\_secret()}
\begin{verbatim}
int dh_shared_secret(dh_key *private_key,
dh_key *public_key,
unsigned char *out, unsigned long *outlen);
\end{verbatim}
Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you. The result goes
into ``out'' and the length into ``outlen''. If all went correctly the data in ``out'' should be identical for both parties. It is important to
note that the two keys have to be the same size in order for this to work. There is a function to get the size of a
key:
\index{dh\_get\_groupsize()}
\begin{verbatim}
int dh_get_groupsize(dh_key *key);
\end{verbatim}
This returns the size in bytes of the modulus chosen for that key.
\mysection{Other Diffie-Hellman Functions}
To be able to import Diffie-Hellman keys LibTomCrypt provides several API functions.
\\
To import the prime and group from binary format:
\index{dh\_set\_pg()}
\begin{verbatim}
int dh_set_pg(const unsigned char *p, unsigned long plen,
const unsigned char *g, unsigned long glen,
dh_key *key);
\end{verbatim}
This sets the prime \textit{p} of length \textit{plen} and the generator/base \textit{g} of length \textit{glen} in the DH key \textit{key}.
\\
To import the prime and group from an ASN.1 encoded DHparam Sequence:
\index{dh\_set\_pg\_dhparam()}
\begin{verbatim}
int dh_set_pg_dhparam(const unsigned char *dhparam, unsigned long dhparamlen, dh_key *key);
\end{verbatim}
This sets the parameters in \textit{dhparam} of \textit{dhparamlen} in the DH key \textit{key}.
\\
To import a private or public key from binary data:
\index{dh\_set\_key()}
\begin{verbatim}
int dh_set_key(const unsigned char *in, unsigned long inlen, int type, dh_key *key);
\end{verbatim}
This will import, depending on \textit{type} which can be either \textit{PK\_PRIVATE} or \textit{PK\_PUBLIC},
the according part of the DH key \textit{key} from \textit{in} of length \textit{inlen}.
After import the key will be verified and in case of an error it will be free'd.
\mysection{Remarks on Usage}
Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example. It is suggested that proper packaging be used. For example, if the public key sent is truncated these routines will not detect that.}:
\newpage
\begin{small}
\begin{verbatim}
int establish_secure_socket(int sock, int mode, unsigned char *key,
prng_state *prng, int wprng)
{
unsigned char buf[4096], buf2[4096];
unsigned long x, len;
int res, err, inlen;
dh_key mykey, theirkey;
/* make up our private key */
if ((err = dh_set_pg_groupsize(128, &mykey)) != CRYPT_OK) {
return err;
}
if ((err = dh_generate_key(prng, wprng, &mykey)) != CRYPT_OK) {
return err;
}
/* export our key as public */
x = sizeof(buf);
if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
res = err;
goto done2;
}
if (mode == 0) {
/* mode 0 so we send first */
if (send(sock, buf, x, 0) != x) {
res = CRYPT_ERROR;
goto done2;
}
/* get their key */
if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
res = CRYPT_ERROR;
goto done2;
}
} else {
/* mode >0 so we send second */
if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
res = CRYPT_ERROR;
goto done2;
}
if (send(sock, buf, x, 0) != x) {
res = CRYPT_ERROR;
goto done2;
}
}
if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
res = err;
goto done2;
}
/* make shared secret */
x = sizeof(buf);
if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
res = err;
goto done;
}
/* hash it */
len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves. These curves were added to
The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the
value the faster the algorithm will be but the more memory it will take. The memory usage is $3\cdot2^{FP\_LUT}$ integers which by default
with TFM amounts to about 400kB of memory. Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount. Memory is only used by a cache entry
if it is active. Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,
\begin{verbatim}
CFLAGS="-DTFM_DESC -DMECC_FP -DFP_ENTRIES=8 -DFP_LUT=6" make
would define a window of 6 bits and limit the cache to 8 entries. Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h). It defaults
to 4096 bits (512 bytes) which is way more than what is required by ECC. At most, you need 1152 bits to accommodate ECC--521. If you're only using (say)
ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
\end{flushleft}
\mysection{Key Format}
LibTomCrypt uses a unique format for ECC public and private keys. While ANSI X9.63 partially specifies key formats, it does it in a less than ideally simple manner. \
In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves. The format of the keys is as follows:
The \textit{keysize} is the size of the modulus in bytes desired. Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
correspond to key sizes of 112, 128, 160, 192, 224, 256, 384, and 521 bits respectively. If you pass a key size that is between any key size it will round
This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The imported key is stored in the ECC key pointed to by
This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.
ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext. It is not strictly ANSI X9.63 compliant
but it is very similar. It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage. The following function
encrypts a short string (no longer than the message digest) using this technique:
With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems. The math will still work, and in effect the signature will still
work. With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller. For example, if you sign with
SHA256 and an ECC-192 key, you in effect have 96--bits of security.
The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
reduce the bandwidth of the signatures. For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.
With DSA, you need a group of order at least 160--bits. By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature
Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
now so that others can interoperate with this library.
This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
The DSA \textit{key} must be a private key.
\mysection{DSA Key Import and Export}
\subsection{DSA Key Export}
To export a DSA key so that it can be transported use the following function:
\index{dsa\_export()}
\begin{verbatim}
int dsa_export(unsigned char *out,
unsigned long *outlen,
int type,
dsa_key *key);
\end{verbatim}
This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
initialized to the maximum buffer size). The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
depending on whether you want to export a private or public copy of the DSA key.
\subsection{DSA Key Import}
To import an exported DSA key use the following function
:
\index{dsa\_import()}
\begin{verbatim}
int dsa_import(const unsigned char *in,
unsigned long inlen,
dsa_key *key);
\end{verbatim}
This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}. If the process fails the function
will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
\mysection{Other DSA Functions}
The following functions allow to create a DSA key in 2 steps:
\begin{enumerate}
\item Load or generate \textit{p}, \textit{q}, \textit{g} part of the key via \textit{dsa\_set\_pqg()}, \textit{dsa\_set\_pqg\_dsaparam()} or \textit{dsa\_generate\_pqg()}.
\item Load or generate the actual DSA key -- private (\textit{x} and \textit{y} values) or public (\textit{y} value).
\end{enumerate}
\index{dsa\_set\_pqg()}
\begin{verbatim}
int dsa_set_pqg(const unsigned char *p, unsigned long plen,
const unsigned char *q, unsigned long qlen,
const unsigned char *g, unsigned long glen,
dsa_key *key);
\end{verbatim}
This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary
representation of \textit{p} (with length of \textit{plen}), \textit{q} (with length of \textit{qlen}) and \textit{g} (with length of \textit{glen}).
A simple DSA key validity check (without primality testing) is performed at the end of this function.
LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
are all provided with three basic functions with \textit{similar} prototypes. One function has been dedicated to calculate the length in octets of a given
in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure. It is defined as the following:
The \textit{type} field is one of the following ASN.1 field definitions. The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the
\textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type). The \textit{used} field is primarily for the CHOICE decoder
and reflects if the particular member of a list was the decoded data type. To help build the lists in an orderly fashion the macro
\textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.
It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size). An example usage would be:
The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
\subsubsection{SEQUENCE Encoding}
To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it. The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}. The
function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.
The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
verbatim to the dependent encoder. The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions. In these cases
the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
Decoding a SEQUENCE is similar to encoding. You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size
(in certain cases). For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets. The function will stop (gracefully) when it runs out of items to decode.
It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occurred.
For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
\begin{enumerate}
\item BIT STRING
\item OCTET STRING
\item OBJECT IDENTIFIER
\item IA5 STRING
\item PRINTABLE STRING
\end{enumerate}
\subsubsection{SEQUENCE Length}
The length of a SEQUENCE can be determined with the following function.
These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
The list of items are specified as a triple of the form \textit{(type, size, data)} where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
and \textit{data} is \textbf{void} pointer. The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function. Constants such as \textit{1} without
a cast or prototype are of type \textbf{int} by default. Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.
This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively. Note the usage of the \textbf{UL} modifier
on the size parameters. This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
\subsection{SET and SET OF}
\index{SET}\index{SET OF}
SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code. However, they are different, and they should
be carefully noted. The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of
This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.
The function will make a copy of the list provided, and sort it by the TAG. Objects with identical TAGs are additionally sorted on their original placement in the
This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.
used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
use. They are encoded with the following function.
This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.
The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer. This
These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER. To encode smaller values without allocating
a bignum to store the value, the \textit{short} INTEGER functions were made available.
These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf{char} per bit. A non--zero value will be interpreted
These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
that the build platform honours the run--time platforms character conventions.
These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
to numerical conversions based on the conventions of the compiler being used. For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
that the build platform honours the run-time platforms character conventions.
These will encode or decode an UTF8 STRING. The characters are read or stored in individual \textbf{wchar\_t} elements. These function performs no internal
These functions use the \textbf{wchar\_t} type which is not universally available. In those cases, the library will typedef it to \textbf{unsigned long}. If you
The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
will be subtracted. For instance, the array $\lbrace5, 6, 20, 22, 4, 00, 0, 5, 0\rbrace$ represents the current time of
\textit{2005, June 20th, 22:04:00} with a time offset of +05h00.
The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the
input. The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.
It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm). When \textit{off\_dir} is zero, the time will be added otherwise it
will be subtracted. For instance, the array $\lbrace2005, 6, 20, 22, 4, 0, 122, 0, 5, 0\rbrace$ represents the current time of
\textit{2005, June 20th, 22:04:00.122} with a time offset of +05h00.
The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}. There is no encoder for the CHOICE type, only a
decoder. The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet. The list can contain any ASN.1 data
This will decode the input in the \textit{in} field of length \textit{inlen}. It uses the provided ASN.1 list specified in the \textit{list} field which has
\textit{outlen} elements. The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field
will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
\subsection{ASN.1 Flexi Decoder}
The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
the structure of the data. Where der\_decode\_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent}
and \textit{child}. The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
encoded in a SEQUENCE are stored as a child element.
When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the child
This will decode items in the \textit{in} buffer of max input length \textit{inlen} and store the newly created pointer to the list in \textit{out}. This function allocates
all required memory for the decoding. It stores the number of octets read back into \textit{inlen}.
The function will terminate when either it hits an invalid ASN.1 tag, or it reads \textit{inlen} octets. An early termination is a soft error, and returns
normally. The decoded list \textit{out} will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf{NULL}).
An invalid decoding will terminate the process, and free the allocated memory automatically.
The flexi decoder calls itself when decoding a constructed type. This leads to
a 'child process' that will terminate when it decodes an unkown/invalid
identifier and leaves an allocated but uninitialized child element.
However the parent processing will continue with a "soft-error".
This can be detected by checking for \textit{child} elements with
type \textbf{LTC\_ASN1\_EOL} after decoding.
As of v1.18.0 the flexi decoder will also decode arbitrary constructed types
other than SEQUENCE and SET. The \textit{type} field will be set to
\textbf{LTC\_ASN1\_CONSTRUCTED} and the plain identifier that was indicated in the ASN.1
encoding is stored in the \textit{used} field. Further decoding is done in the
same way as if it were a SEQUENCE or SET.
Also as of v1.18.0 the flexi decoder is capable to handle
\textit{context-specific} encodings. The \textit{type} field will be set to
\textbf{LTC\_ASN1\_CONTEXT\_SPECIFIC} and the plain identifier that was indicated
in the ASN.1 encoding is stored in the \textit{used} field. Encapsulated data
in the \textit{context-specific} encoding is copied to newly allocated memory
and is accessible through the \textit{data} field.
\textbf{Note:} the list decoded by this function is \textbf{NOT} in the correct form for der\_encode\_sequence() to use directly. You will first
have to convert the list by first storing all of the siblings in an array then storing all the children as sub-lists of a sequence using the \textit{.data}
At this point \textit{list} would point to the SEQUENCE identified by \textit{User}. It would have no sibblings (prev or next), and only a child node. Walking to the child
node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
\begin{small}
\begin{verbatim}
list = list->child;
\end{verbatim}
\end{small}
Now \textit{list} points to the \textit{Name} member (with the tag IA5 STRING). The \textit{data}, \textit{size}, and \textit{type} members of \textit{list} should reflect
that of an IA5 STRING. The sibbling will now be the \textit{LoginToken} SEQUENCE. The sibbling has a child node which points to the \textit{passwdHash} OCTET STRING.
We can walk to this node with the following code:
\begin{small}
\begin{verbatim}
/* list already pointing to 'Name' */
list = list->next->child;
\end{verbatim}
\end{small}
At this point, \textit{list} will point to the \textit{passwdHash} member of the innermost SEQUENCE. This node has a sibbling, the \textit{pubkey} member of the SEQUENCE.
The \textit{LastOn} member of the SEQUENCE is a sibbling of the LoginToken node, if we wanted to walk there we would have to go up and over via:
At this point, we are pointing to the last node of the list. Lists are terminated in all directions by a \textbf{NULL} pointer. All nodes are doubly linked so that you
The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.
Where \textit{password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
The output of length up to \textit{outlen} is stored in \textit{out}. If \textit{outlen} is initially larger than the size of the hash functions output
it is set to the number of bytes stored. If it is smaller than not all of the hash output is stored in \textit{out}.
int pkcs_5_alg1_openssl(const unsigned char *password,
unsigned long password_len,
const unsigned char *salt,
int iteration_count,
int hash_idx,
unsigned char *out,
unsigned long *outlen)
\end{alltt}
As above, but we generate as many bytes as requested in outlen per the OpenSSL extension to Algorithm One. If you are trying to be compatible with OpenSSL's EVP\_BytesToKey() or the "openssl enc" command line (or variants such as perl's Crypt::CBC), then use this function with MD5 as your hash (ick!) and iteration\_count=1 (double-ick!!).
The \textit{salt} is an array of size \textit{salt\_len}. It should be random for each user and session. The \textit{iteration\_count} is the delay desired
A key derivation function (KDF) is a basic and essential component of cryptographic systems. Its goal is to take some source of initial
keying material and derive from it one or more cryptographically strong secret keys.
HKDF follows the "extract-then-expand" paradigm, where the KDF logically consists of two modules. The first stage takes the input
keying material and "extracts" from it a fixed-length pseudorandom key K. The second stage "expands" the key K into several additional
pseudorandom keys (the output of the KDF).
In many applications, the input keying material is not necessarily distributed uniformly, and the attacker may have some partial
knowledge about it (for example, a Diffie-Hellman value computed by a key exchange protocol) or even partial control of it (as in some
entropy-gathering applications). Thus, the goal of the "extract" stage is to "concentrate" the possibly dispersed entropy of the input
keying material into a short, but cryptographically strong, pseudorandom key. In some applications, the input may already be a
good pseudorandom key; in these cases, the "extract" stage is not necessary, and the "expand" part can be used alone.
The second stage "expands" the pseudorandom key to the desired length; the number and lengths of the output keys depend on the
specific cryptographic algorithms for which the keys are needed.
\subsection{HKDF Extract}
To perform the extraction phase, use the following function:
\index{hkdf\_extract()}
\begin{alltt}
int hkdf_extract( int hash_idx,
const unsigned char *salt,
unsigned long saltlen,
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen);
\end{alltt}
The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
The \textit{salt} parameter is a pointer to the array of octets of length \textit{saltlen} containing the salt or a NULL pointer if a salt is not being used (in that case set saltlen to 0).
\textit{in} is a pointer to an array of octets of length \textit{inlen} containing the source entropy. The extracted output is stored in the location pointed to by \textit{out}.
You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated to the length of the extracted output. If \textit{outlen} is too small the extracted output will be truncated.
While the salt is optional, using one improves HKDF's security. If used, the salt should be randomly chosen, but does not need to be secret and may be re-used. Please see RFC5869 section 3.1 for more details.
\subsection{HKDF Expand}
To perform the expansion phase, use the following function:
\index{hkdf\_expand()}
\begin{alltt}
int hkdf_expand( int hash_idx,
const unsigned char *info,
unsigned long infolen,
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long outlen);
\end{alltt}
The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
The \textit{info} parameter, an array of octets of length \textit{infolen}, is an optional parameter (set \textit{info} to NULL and \textit{infolen} to 0 if not using it) which
may be used to bind the derived keys to some application and context specific information. This prevents the same keying material from being generated in different contexts. Please see RFC5869 section 3.2 for more information.
The extracted keying material is passed as octet array \textit{in} of length \textit{inlen}. Expanded output of length \textit{outlen} is generated and stored in octet arrat \textit{out}.
\subsection{HKDF Extract-and-Expand}
To perform both phases together, use the following function:
\index{hkdf()}
\begin{alltt}
int hkdf( int hash_idx,
const unsigned char *salt,
unsigned long saltlen,
const unsigned char *info,
unsigned long infolen,
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long outlen);
\end{alltt}
Parameters are as in \textit{hkdf\_extract()} and \textit{hkdf\_expand()}.
two phases. First it will perform trial division by the first few primes. Second it will perform \textit{LTC\_MILLER\_RABIN\_REPS} (pre-defined to $35$) rounds of the
$\left({1\over4}\right)^{8}=2^{-16}$. In practice the probability of error is in fact much lower than that.
When making random primes the trial division step is in fact an optimized implementation of \textit{Implementation of Fast RSA Key Generation on Smart Cards}\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candidate
is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
math operations. As a result the routine can scan ahead to the next number required for testing with very little work
as $\phi(pq)$ or $(p -1)(q -1)$. The decryption exponent $d$ is found as $de \equiv1\mbox{}(\mbox{mod }\phi(pq))$. If either $p$ or $q$ is composite the value of $d$ will be incorrect and the user
\textbf{LIBNAME} is the name of the output library (archive) to create. It defaults to \textit{libtomcrypt.a} for static builds and \textit{libtomcrypt.la} for
shared.
On installation of the shared library the appropriately versioned \textit{libtomcrypt.so}, \textit{libtomcrypt.so.0} etc. will be created by \textit{libtool}.
In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
we define \textbf{TFM\_DESC} for compilation. This is so that the TFM descriptor symbol will be defined for the client application to make use of without
This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
shared build process requires libtool to be installed.
\mysection{Header Configuration}
The file \textit{tomcrypt\_cfg.h} is what lets you control various high level macros which control the behaviour of the library. Build options are also
stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.
\subsubsection{ARGTYPE}
This lets you control how the LTC\_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
Assumes that you have no memory paging with the stack.
\subsection{LTC\_TEST}
When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build. This is the default configuration.
If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.
\subsection{LTC\_NO\_FAST}
When this has been defined the library will not use faster word oriented operations. By default, they are only enabled for platforms
which can be auto-detected. This macro ensures that they are never enabled.
If you do plan on using the \textit{LTC\_FAST} mode, a \textit{LTC\_FAST\_TYPE} type which resolves to an optimal sized
data type you can perform integer operations with is required. For the auto-detected platforms this type will be defined automatically. Ideally it should be four or eight bytes since it must properly divide the size
of your block cipher (e.g. 16 bytes for AES). This means sadly if you're on a platform with 57--bit words (or something) you can't
When this has been defined the library will not use any inline assembler. Only a few platforms support assembler inlines but various versions of ICC and GCC
The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
libraries. When \textbf{GMP\_DESC}, \textbf{LTM\_DESC}, or \textbf{TFM\_DESC} are defined
descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.
In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
to tell the program which library to use. Only one of the USE flags can be defined at once.
The entire API was designed with plug and play in mind at the low level. That is you can swap out any cipher, hash, PRNG or bignum library and the dependent API will not
require updating. This has the nice benefit that one can add ciphers (etc.) not have to re--write portions of the API. For the most part, LibTomCrypt has also been written
to be highly portable and easy to build out of the box on pretty much any platform. As such there are no assembler inlines throughout the code, I make no assumptions
about the platform, etc...
That works well for most cases but there are times where performance is of the essence. This API allows optimized routines to be dropped in--place of the existing
portable routines. For instance, hand optimized assembler versions of AES could be provided. Any existing function that uses the cipher could automatically use
the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
At the heart of this flexibility is the \textit{descriptor} system. A descriptor is essentially just a C \textit{struct} which describes the algorithm and provides pointers
to functions that do the required work. For a given class of operation (e.g. cipher, hash, prng, bignum) the functions of a descriptor have identical prototypes which makes
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
@remark Requires manual padding
*/
int (*f9_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
};
\end{verbatim}
\end{small}
\subsection{Name}
\index{find\_cipher()}
The \textit{name} parameter specifies the name of the cipher. This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
tables.
\subsection{Internal ID}
This is a single byte Internal ID you can use to distinguish ciphers from each other.
\subsection{Key Lengths}
The minimum key length is \textit{min\_key\_length} and is measured in octets. Similarly the maximum key length is \textit{max\_key\_length}. They can be equal
and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
\subsection{Block Length}
The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.
\subsection{Rounds}
Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit{default\_rounds}.
\subsection{Setup}
To initialize a cipher (for ECB mode) the function setup() was provided. It accepts an array of key octets \textit{key} of length \textit{keylen} octets. The user
can specify the number of rounds they want through \textit{num\_rounds} where $num\_rounds =0$ means use the default. The destination of a scheduled key is stored
in \textit{skey}.
Inside the \textit{symmetric\_key} union there is a \textit{void *data} which you can use to allocate data if you need a data structure that does not fit with the existing
ones provided. Just make sure in your \textit{done()} function that you free the allocated memory.
To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided. The plaintext and ciphertext buffers are allowed to overlap so you
must make sure you do not overwrite the output before you are finished with the input.
\subsection{Testing}
The test() function is used to self--test the \textit{device}. It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly. You may return
\textbf{CRYPT\_NOP} to indicate that no testing was performed.
Occasionally, a function will want to find a suitable key size to use since the input is oddly sized. The keysize() function is for this case. It accepts a
pointer to an integer which represents the desired size. The function then has to match it to the exact or a lower key size that is valid for the cipher. For
example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer. It must not round up and must return an error if the keysize
cannot be mapped to a valid key size for the cipher.
\subsection{Acceleration}
The next set of functions cover the accelerated functionality of the cipher descriptor. Any combination of these functions may be set to \textbf{NULL} to indicate
it is not supported. In those cases the software defaults are used (using the single ECB block routines).
\subsubsection{Accelerated ECB}
These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks. These functions are accessed
through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The \textit{blocks} count is the number of complete blocks to process.
These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CBC initialization vector. It is an input upon calling this function and must be
This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
The \textit{blocks} value is the number of complete blocks to process. The \textit{IV} is the CTR counter vector. It is an input upon calling this function and must be
The \textit{CTR pad} is empty when a multiple (including zero) blocks of text have been processed. That is, if you pass in seven bytes to AES--CTR mode you would have to
pass in a minimum of nine extra bytes before the accelerator could be called. The CTR accelerator must increment the counter (and store it back into the
buffer provided) before encrypting it to create the pad.
The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
\subsubsection{Accelerated LRW}
These functions are meant for accelerated LRW. They process blocks of input in lengths of multiples of 16 octets. They must accept the \textit{IV} and \textit{tweak}
state variables and updated them prior to returning. Note that you may want to disable \textbf{LRW\_TABLES} in \textit{tomcrypt\_custom.h} if you intend
to use accelerators for LRW.
While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_setiv() more efficient.
Note that calling lrw\_done() will only invoke the cipher\_descriptor[].done() function on the \textit{symmetric\_key} parameter of the LRW state. That means
if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
the plugin solely to do LRW with the cipher. That way cipher\_descriptor[].setup() means to init LRW resources and cipher\_descriptor[].done() means to
free them.
\subsubsection{Accelerated CCM}
This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance). This
\hline\textbf{key}&\textbf{uskey}&\textbf{Source of key}\\
\hline NULL & NULL & Error, not supported \\
\hline non-NULL & NULL & Use key, do a key schedule \\
\hline NULL & non-NULL & Use uskey, key schedule not required \\
\hline non-NULL & non-NULL & Use uskey, key schedule not required \\
\hline
\end{tabular}
\end{small}
\end{center}
\index{ccm\_memory()} This function is called when the user calls ccm\_memory().
\subsubsection{Accelerated GCM}
\index{gcm\_memory()}
This function is meant for accelerated GCM encryption or decryption. It processes the entire packet in one call. Note that the setup() function will not
be called prior to this. This function must handle scheduling the key provided on its own. It is called when the user calls gcm\_memory().
This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory(). Like f9\_memory(), it requires
the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.
\mysection{One--Way Hashes}
The hash functions are accessed through the ltc\_hash\_descriptor structure.
This is the name the hash is known by and what find\_hash() will look for.
\subsection{Internal ID}
This is the internal ID byte used to distinguish the hash from other hashes.
\subsection{Digest Size}
The \textit{hashsize} variable indicates the length of the output in octets.
\subsection{Block Size}
The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
invocation.
\subsection{OID Identifier}
This is the universal ASN.1 Object Identifier for the hash.
\subsection{Initialization}
The init function initializes the hash and prepares it to process message bytes.
\subsection{Process}
This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
guaranteed to be a multiple of the block size in length.
\subsection{Done}
The done function terminates the hash and returns the message digest.
\subsection{Acceleration}
A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
\subsection{HMAC Acceleration}
The hmac\_block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_memory() if present. If you need
to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_memory() as provided in LibTomCrypt.
\mysection{Pseudo--Random Number Generators}
The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
Most of the functions are fairly straightforward and do not need documentation. We'll cover the basic conventions of the API and then explain the accelerated functions.
\subsection{Conventions}
All \textit{bignums} are accessed through an opaque \textit{void *} data type. You must internally cast the pointer if you need to access members of your bignum structure. During
the init calls a \textit{void **} will be passed where you allocate your structure and set the pointer then initialize the number to zero. During the deinit calls you must
All functions (except where noted otherwise) return \textbf{CRYPT\_OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
The digit routines (including functions with the \textit{i} suffix) use a \textit{ltc\_mp\_digit} to represent the digit. If your internal digit is larger than this you must
then partition your digits. Note that if your digit is smaller than an \textit{ltc\_mp\_digit} that is also acceptable as the \textit{bits\_per\_digit} parameter will specify this.
\subsubsection{ltc\_mp\_digit}
\index{ltc\_mp\_digit}
Depending on the archtitecture \textit{ltc\_mp\_digit} is either a $32$- or $64$-bit long \textit{unsigned} data type.
The ECC system in LibTomCrypt is based off of the NIST recommended curves over $GF(p)$ and is used to implement EC-DSA and EC-DH. The ECC functions work with
that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_point;
\end{verbatim}
All ECC functions must use this mapping system. The only exception is when you remap all ECC callbacks which will allow you to have more control
over how the ECC math will be implemented. Out of the box you only have three parameters per point to use $(x, y, z)$ however, these are just void pointers. They
could point to anything you want. The only further exception is the export functions which expects the values to be in affine format.
This will multiply the point $G$ by the scalar $k$ and store the result in the point $R$. The value should be mapped to affine only if $map$ is set to one.
This will add the point $P$ to the point $Q$ and store it in the point $R$. The $mp$ parameter is the \textit{b} value from the montgomery\_setup() call. The input points
To accelerate EC--DSA verification the library provides a built--in function called ltc\_ecc\_mul2add(). This performs two point multiplications and an addition in
roughly the time of one point multiplication. It is called from ecc\_verify\_hash() if an accelerator is not present. The acclerator function must allow the points to
The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
The call reads the \textit{in} buffer as an unsigned char array in big endian format. Then it performs the exponentiation and stores the output in big endian format
to the \textit{out} buffer. The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes). For example,
for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \#1 v2.1 specification.