2006-11-17 14:21:24 +00:00
\documentclass [synpaper] { book}
2017-08-01 08:18:34 +00:00
\usepackage { geometry}
2003-06-11 21:10:22 +00:00
\usepackage { hyperref}
2003-03-03 00:59:24 +00:00
\usepackage { makeidx}
\usepackage { amssymb}
2003-03-13 02:12:16 +00:00
\usepackage { color}
\usepackage { alltt}
\usepackage { graphicx}
\usepackage { layout}
2006-11-17 14:21:24 +00:00
\usepackage { fancyhdr}
2017-09-20 12:33:04 +00:00
\usepackage { float}
2003-03-03 00:59:24 +00:00
\def \union { \cup }
\def \intersect { \cap }
\def \getsrandom { \stackrel { \rm R} { \gets } }
\def \cross { \times }
\def \cat { \hspace { 0.5em} \| \hspace { 0.5em} }
\def \catn { $ \| $ }
\def \divides { \hspace { 0.3em} | \hspace { 0.3em} }
\def \nequiv { \not \equiv }
\def \approx { \raisebox { 0.2ex} { \mbox { \small $ \sim $ } } }
\def \lcm { { \rm lcm} }
\def \gcd { { \rm gcd} }
\def \log { { \rm log} }
\def \ord { { \rm ord} }
\def \abs { { \mathit abs} }
\def \rep { { \mathit rep} }
\def \mod { { \mathit \ mod\ } }
\renewcommand { \pmod } [1]{ \ ({ \rm mod\ } { #1} )}
\newcommand { \floor } [1]{ \left \lfloor { #1} \right \rfloor }
\newcommand { \ceil } [1]{ \left \lceil { #1} \right \rceil }
\def \Or { { \rm \ or\ } }
\def \And { { \rm \ and\ } }
\def \iff { \hspace { 1em} \Longleftrightarrow \hspace { 1em} }
\def \implies { \Rightarrow }
\def \Proof { \vspace { 1ex} \noindent { \bf Proof:} \hspace { 1em} }
\let \oldphi \phi
\def \phi { \varphi }
\def \Pr { { \rm Pr} }
\newcommand { \str } [1]{ { \mathbf { #1} } }
\def \F { { \mathbb F} }
\def \N { { \mathbb N} }
\def \Z { { \mathbb Z} }
\def \R { { \mathbb R} }
\def \C { { \mathbb C} }
\def \Q { { \mathbb Q} }
2006-11-17 14:21:24 +00:00
\definecolor { DGray} { gray} { 0.5}
\newcommand { \emailaddr } [1]{ \mbox { $ < $ { #1} $ > $ } }
2003-03-03 00:59:24 +00:00
\def \twiddle { \raisebox { 0.3ex} { \mbox { \tiny $ \sim $ } } }
\def \gap { \vspace { 0.5ex} }
\makeindex
2006-11-17 14:21:24 +00:00
\newcommand { \mysection } [1] % Re-define the chaptering command to use
{ % THESE headers.
\section { #1}
2017-06-19 21:38:33 +00:00
\markboth { \textsf { www.libtom.net} } { \thesection ~ { #1} }
2006-11-17 14:21:24 +00:00
}
\newcommand { \mystarsection } [1] % Re-define the chaptering command to use
{ % THESE headers.
\section * { #1}
2017-06-19 21:38:33 +00:00
\markboth { \textsf { www.libtom.net} } { { #1} }
2006-11-17 14:21:24 +00:00
}
\pagestyle { empty}
2003-03-03 00:59:24 +00:00
\begin { document}
2006-11-17 14:21:24 +00:00
\frontmatter
\pagestyle { empty}
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
~
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
\vspace { 2in}
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
~
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
\begin { center}
\begin { Huge} LibTomCrypt\end { Huge}
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
~
2004-06-20 02:41:49 +00:00
2006-11-17 14:21:24 +00:00
\begin { large} Developer Manual\end { large}
2004-06-20 02:41:49 +00:00
2006-11-17 14:21:24 +00:00
~
2004-06-20 02:41:49 +00:00
2006-11-17 14:21:24 +00:00
\vspace { 15mm}
2004-06-20 02:41:49 +00:00
2006-11-17 14:21:24 +00:00
\begin { tabular} { c}
LibTom Projects
\end { tabular}
\end { center}
\vfil
2006-12-16 18:10:04 +00:00
\newpage
This document is part of the LibTomCrypt package and is hereby released into the public domain.
~
Open Source. Open Academia. Open Minds.
~
\begin { flushright}
2017-06-20 10:03:11 +00:00
LibTom Projects
~
\& originally
~
2006-12-16 18:10:04 +00:00
Tom St Denis
~
Ottawa, Ontario
~
Canada
~
\vfil
\end { flushright}
\newpage
2006-11-17 14:21:24 +00:00
2003-03-03 00:59:24 +00:00
\tableofcontents
2006-11-17 14:21:24 +00:00
\listoffigures
\pagestyle { myheadings}
\mainmatter
2003-03-03 00:59:24 +00:00
\chapter { Introduction}
2006-11-17 14:21:24 +00:00
\mysection { What is the LibTomCrypt?}
2014-08-28 12:42:19 +00:00
LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
designing cryptosystems. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
2018-07-03 16:58:11 +00:00
public key cryptography (via PKCS \# 1 RSA, DH or ECDH), and a plethora of support routines.
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
(and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
2006-11-17 14:21:24 +00:00
also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Why did I write it?}
You may be wondering, \textit { Tom, why did you write a crypto library. I already have one.} Well the reason falls into
2003-03-03 00:59:24 +00:00
two categories:
\begin { enumerate}
\item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
\item It was (still is) good coding practice.
\end { enumerate}
2014-08-28 12:42:19 +00:00
The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
2003-03-03 00:59:24 +00:00
{ \bf own} crypto library and hopefully along the way others will appreciate the work.
2006-11-17 14:21:24 +00:00
With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
2003-03-03 00:59:24 +00:00
and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
2014-08-28 12:42:19 +00:00
on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time. That means your
2006-11-17 14:21:24 +00:00
application can support all ciphers/hashes/prngs/bignum without changing the source code.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
2004-12-30 23:55:53 +00:00
configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
without having to use configure scripts. This means that the library will work with platforms where development
tools may be limited (e.g. no autoconf).
2006-11-17 14:21:24 +00:00
On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
2004-12-30 23:55:53 +00:00
robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
2006-11-17 14:21:24 +00:00
with \textit { cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
2004-12-30 23:55:53 +00:00
Crypto++.
2003-03-13 02:12:16 +00:00
\subsection { Modular}
2006-11-17 14:21:24 +00:00
The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
2014-08-28 12:42:19 +00:00
pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit { descriptor} tables which
2003-03-13 02:12:16 +00:00
are essentially structures with pointers to functions. While you can still call particular functions
directly (\textit { e.g. sha256\_ process()} ) this descriptor interface allows the developer to customize their
usage of the library.
For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
2004-12-30 23:55:53 +00:00
that for the PRNG needs within the library (\textit { e.g. making a RSA key} ). All the developer has to do
2014-08-28 12:42:19 +00:00
is write a descriptor and the few support routines required for the device. After that the rest of the
API can make use of it without change. Similarly imagine a few years down the road when AES2
(\textit { or whatever they call it} ) has been invented. It can be added to the library and used within applications
2004-12-30 23:55:53 +00:00
with zero modifications to the end applications provided they are written properly.
2003-03-13 02:12:16 +00:00
2014-08-28 12:42:19 +00:00
This flexibility within the library means it can be used with any combination of primitive algorithms and
2003-03-13 02:12:16 +00:00
unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
mode routines for every single cipher. That means every time you add or remove a cipher from the library
you have to update the associated support code as well. In LibTomCrypt the associated code (\textit { chaining modes in this case} )
2014-08-28 12:42:19 +00:00
are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
2003-03-13 02:12:16 +00:00
the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
can make use of the cipher right away.
2006-11-17 14:21:24 +00:00
\mysection { License}
2003-03-03 00:59:24 +00:00
2003-09-08 01:06:11 +00:00
The project is hereby released as public domain.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Patent Disclosure}
2003-03-03 00:59:24 +00:00
The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
2014-08-28 12:42:19 +00:00
of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
2006-11-17 14:21:24 +00:00
They can be removed from a build by simply commenting out the two appropriate lines in \textit { tomcrypt\_ custom.h} . The rest
2003-03-03 00:59:24 +00:00
of the ciphers and hashes are patent free or under patents that have since expired.
2014-08-28 12:42:19 +00:00
The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
the ciphers you just can't advertise that you are doing so.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Thanks}
2004-06-20 02:41:49 +00:00
I would like to give thanks to the following people (in no particular order) for helping me develop this project from
early on:
2003-03-03 00:59:24 +00:00
\begin { enumerate}
\item Richard van de Laarschot
\item Richard Heathfield
\item Ajay K. Agrawal
\item Brian Gladman
\item Svante Seleborg
\item Clay Culver
\item Jason Klapste
\item Dobes Vandermeer
\item Daniel Richards
\item Wayne Scott
\item Andrew Tyler
\item Sky Schulz
2003-03-03 01:02:10 +00:00
\item Christopher Imes
2003-03-03 00:59:24 +00:00
\end { enumerate}
2004-06-20 02:41:49 +00:00
There have been quite a few other people as well. Please check the change log to see who else has contributed from
time to time.
2003-03-03 00:59:24 +00:00
\chapter { The Application Programming Interface (API)}
2006-11-17 14:21:24 +00:00
\mysection { Introduction}
2003-03-03 00:59:24 +00:00
\index { CRYPT\_ ERROR} \index { CRYPT\_ OK}
In general the API is very simple to memorize and use. Most of the functions return either { \bf void} or { \bf int} . Functions
2014-08-28 12:42:19 +00:00
that return { \bf int} will return { \bf CRYPT\_ OK} if the function was successful, or one of the many error codes
2003-03-03 00:59:24 +00:00
if it failed. Certain functions that return int will return $ - 1 $ to indicate an error. These functions will be explicitly
commented upon. When a function does return a CRYPT error code it can be translated into a string with
2004-05-31 02:36:47 +00:00
\index { error\_ to\_ string()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-05-31 02:36:47 +00:00
const char *error_ to_ string(int err);
2003-03-03 00:59:24 +00:00
\end { verbatim}
An example of handling an error is:
2006-11-17 14:21:24 +00:00
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
void somefunc(void)
{
2004-05-31 02:36:47 +00:00
int err;
2014-08-28 12:42:19 +00:00
2003-03-03 00:59:24 +00:00
/* call a cryptographic function */
2004-05-31 02:36:47 +00:00
if ((err = some_ crypto_ function(...)) != CRYPT_ OK) {
2006-11-17 14:21:24 +00:00
printf("A crypto error occurred, %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
/* perform error handling */
}
2006-11-17 14:21:24 +00:00
/* continue on if no error occurred */
2003-03-03 00:59:24 +00:00
}
\end { verbatim}
2006-11-17 14:21:24 +00:00
\end { small}
2003-03-03 00:59:24 +00:00
There is no initialization routine for the library and for the most part the code is thread safe. The only thread
related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
that is not an issue.
2006-11-17 14:21:24 +00:00
To include the prototypes for \textit { LibTomCrypt.a} into your own program simply include \textit { tomcrypt.h} like so:
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void) {
return 0;
}
\end { verbatim}
2006-11-17 14:21:24 +00:00
\end { small}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
The header file \textit { tomcrypt.h} also includes \textit { stdio.h} , \textit { string.h} , \textit { stdlib.h} , \textit { time.h} and \textit { ctype.h} .
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Macros}
2003-03-03 00:59:24 +00:00
There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
32/64-bit words in little/big endian format. The macros are:
2005-04-17 11:37:13 +00:00
\index { STORE32L} \index { STORE64L} \index { LOAD32L} \index { LOAD64L} \index { STORE32H} \index { STORE64H} \index { LOAD32H} \index { LOAD64H} \index { BSWAP}
2006-11-17 14:21:24 +00:00
\newpage
\begin { figure} [hpbt]
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |c|c|c|}
2014-08-31 15:57:59 +00:00
\hline STORE32L(x, y) & { \bf ulong32} x, { \bf unsigned char} *y & $ x \to y [ 0 \ldots 3 ] $ \\
\hline STORE64L(x, y) & { \bf ulong64} x, { \bf unsigned char} *y & $ x \to y [ 0 \ldots 7 ] $ \\
\hline LOAD32L(x, y) & { \bf ulong32} x, { \bf unsigned char} *y & $ y [ 0 \ldots 3 ] \to x $ \\
\hline LOAD64L(x, y) & { \bf ulong64} x, { \bf unsigned char} *y & $ y [ 0 \ldots 7 ] \to x $ \\
\hline STORE32H(x, y) & { \bf ulong32} x, { \bf unsigned char} *y & $ x \to y [ 3 \ldots 0 ] $ \\
\hline STORE64H(x, y) & { \bf ulong64} x, { \bf unsigned char} *y & $ x \to y [ 7 \ldots 0 ] $ \\
\hline LOAD32H(x, y) & { \bf ulong32} x, { \bf unsigned char} *y & $ y [ 3 \ldots 0 ] \to x $ \\
\hline LOAD64H(x, y) & { \bf ulong64} x, { \bf unsigned char} *y & $ y [ 7 \ldots 0 ] \to x $ \\
\hline BSWAP(x) & { \bf ulong32} x & Swap bytes \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
2006-11-17 14:21:24 +00:00
\caption { Load And Store Macros}
2003-03-03 00:59:24 +00:00
\end { center}
\end { small}
2006-11-17 14:21:24 +00:00
\end { figure}
2003-03-03 00:59:24 +00:00
2004-12-30 23:55:53 +00:00
There are 32 and 64-bit cyclic rotations as well:
2014-08-28 12:42:19 +00:00
\index { ROL} \index { ROR} \index { ROL64} \index { ROR64} \index { ROLc} \index { RORc} \index { ROL64c} \index { ROR64c}
2006-11-17 14:21:24 +00:00
\begin { figure} [hpbt]
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|c|}
2014-08-31 15:57:59 +00:00
\hline ROL(x, y) & { \bf ulong32} x, { \bf ulong32} y & $ x << y, 0 \le y \le 31 $ \\
\hline ROLc(x, y) & { \bf ulong32} x, { \bf const ulong32} y & $ x << y, 0 \le y \le 31 $ \\
\hline ROR(x, y) & { \bf ulong32} x, { \bf ulong32} y & $ x >> y, 0 \le y \le 31 $ \\
\hline RORc(x, y) & { \bf ulong32} x, { \bf const ulong32} y & $ x >> y, 0 \le y \le 31 $ \\
2004-12-30 23:55:53 +00:00
\hline & & \\
2014-08-31 15:57:59 +00:00
\hline ROL64(x, y) & { \bf ulong64} x, { \bf ulong64} y & $ x << y, 0 \le y \le 63 $ \\
\hline ROL64c(x, y) & { \bf ulong64} x, { \bf const ulong64} y & $ x << y, 0 \le y \le 63 $ \\
\hline ROR64(x, y) & { \bf ulong64} x, { \bf ulong64} y & $ x >> y, 0 \le y \le 63 $ \\
\hline ROR64c(x, y) & { \bf ulong64} x, { \bf const ulong64} y & $ x >> y, 0 \le y \le 63 $ \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
2006-11-17 14:21:24 +00:00
\caption { Rotate Macros}
2003-03-03 00:59:24 +00:00
\end { center}
2006-11-17 14:21:24 +00:00
\end { small}
\end { figure}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Functions with Variable Length Output}
Certain functions such as (for example) \textit { rsa\_ export()} give an output that is variable length. To prevent buffer overflows you
2006-06-18 01:37:50 +00:00
must pass it the length of the buffer where the output will be stored. For example:
2006-12-16 18:10:04 +00:00
\index { rsa\_ export()} \index { error\_ to\_ string()} \index { variable length output}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void) {
rsa_ key key;
unsigned char buffer[1024];
unsigned long x;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
/* ... Make up the RSA key somehow ... */
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
/* lets export the key, set x to the size of the
2006-11-17 14:21:24 +00:00
* output buffer */
2003-03-03 00:59:24 +00:00
x = sizeof(buffer);
2004-05-31 02:36:47 +00:00
if ((err = rsa_ export(buffer, & x, PK_ PUBLIC, & key)) != CRYPT_ OK) {
printf("Export error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
2014-08-28 12:42:19 +00:00
/* if rsa_ export() was successful then x will have
2006-11-17 14:21:24 +00:00
* the size of the output */
2003-03-03 00:59:24 +00:00
printf("RSA exported key takes %d bytes\n", x);
/* ... do something with the buffer */
return 0;
}
\end { verbatim}
\end { small}
2004-12-30 23:55:53 +00:00
In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
2014-08-28 12:42:19 +00:00
indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
2006-11-17 14:21:24 +00:00
\textit { x} so that the calling application will know how many bytes were used.
2003-03-03 00:59:24 +00:00
2006-06-18 01:37:50 +00:00
As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
support this so please check the source before you rely on it doing that.
2006-11-17 14:21:24 +00:00
\mysection { Functions that need a PRNG}
2004-12-30 23:55:53 +00:00
\index { Pseudo Random Number Generator} \index { PRNG}
2014-08-28 12:42:19 +00:00
Certain functions such as \textit { rsa\_ make\_ key()} require a Pseudo Random Number Generator (PRNG). These functions do not setup
2004-12-30 23:55:53 +00:00
the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
2006-11-17 14:21:24 +00:00
Certain PRNG algorithms do not require a \textit { prng\_ state} argument (sprng for example). The \textit { prng\_ state} argument
2004-12-30 23:55:53 +00:00
may be passed as \textbf { NULL} in such situations.
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
\index { register\_ prng()} \index { rsa\_ make\_ key()}
2006-11-17 14:21:24 +00:00
\begin { small}
\begin { verbatim}
#include <tomcrypt.h>
int main(void) {
rsa_ key key;
int err;
/* register the system RNG */
2014-08-28 12:42:19 +00:00
register_ prng(& sprng_ desc)
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
/* make a 1024-bit RSA key with the system RNG */
2014-08-28 12:42:19 +00:00
if ((err = rsa_ make_ key(NULL, find_ prng("sprng"), 1024/8, 65537, & key))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
printf("make_ key error: %s\n", error_to_string(err));
return -1;
}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
/* use the key ... */
return 0;
}
\end { verbatim}
\end { small}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Functions that use Arrays of Octets}
Most functions require inputs that are arrays of the data type \textit { unsigned char} . Whether it is a symmetric key, IV
for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit { unsigned char} only the
2014-08-28 12:42:19 +00:00
lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
must pass in (a pointer to) an array of 32 \textit { unsigned char} variables. Certain routines (such as SAFER+) take
2006-11-17 14:21:24 +00:00
special care to work properly on platforms where an \textit { unsigned char} is not eight bits.
For the purposes of this library, the term \textit { byte} will refer to an octet or eight bit word. Typically an array of
type \textit { byte} will be synonymous with an array of type \textit { unsigned char.}
\chapter { Symmetric Block Ciphers}
\mysection { Core Functions}
2014-08-28 12:42:19 +00:00
LibTomCrypt provides several block ciphers with an ECB block mode interface. It is important to first note that you
2006-11-17 14:21:24 +00:00
should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
2003-03-03 00:59:24 +00:00
or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
the API to grow in a modular fashion.
2005-04-17 11:37:13 +00:00
\subsection { Key Scheduling}
2014-08-28 12:42:19 +00:00
All ciphers store their scheduled keys in a single data type called \textit { symmetric\_ key} . This allows all ciphers to
2004-12-30 23:55:53 +00:00
have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
2014-08-28 12:42:19 +00:00
allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers must provide six visible
2006-11-17 14:21:24 +00:00
functions which are (given that XXX is the name of the cipher) the following:
2003-03-03 00:59:24 +00:00
\index { Cipher Setup}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ setup(const unsigned char *key,
int keylen,
2006-12-16 18:10:04 +00:00
int rounds,
symmetric_ key *skey);
2003-03-03 00:59:24 +00:00
\end { verbatim}
The XXX\_ setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
The number of rounds can be set to zero to use the default, which is generally a good idea.
2006-11-17 14:21:24 +00:00
If the function returns successfully the variable \textit { skey} will have a scheduled key stored in it. It's important to note
2014-08-28 12:42:19 +00:00
that you should only used this scheduled key with the intended cipher. For example, if you call \textit { blowfish\_ setup()} do not
pass the scheduled key onto \textit { rc5\_ ecb\_ encrypt()} . All built--in setup functions do not allocate memory off the heap so
2006-11-17 14:21:24 +00:00
when you are done with a key you can simply discard it (e.g. they can be on the stack). However, to maintain proper coding
practices you should always call the respective XXX\_ done() function. This allows for quicker porting to applications with
externally supplied plugins.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { ECB Encryption and Decryption}
2006-11-17 14:21:24 +00:00
To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
2003-03-03 00:59:24 +00:00
\index { Cipher Encrypt} \index { Cipher Decrypt}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ ecb_ encrypt(const unsigned char *pt,
2006-12-16 18:10:04 +00:00
unsigned char *ct,
symmetric_ key *skey);
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
int XXX_ ecb_ decrypt(const unsigned char *ct,
2006-12-16 18:10:04 +00:00
unsigned char *pt,
symmetric_ key *skey);
2003-03-03 00:59:24 +00:00
\end { verbatim}
These two functions will encrypt or decrypt (respectively) a single block of text\footnote { The size of which depends on
2014-08-28 12:42:19 +00:00
which cipher you are using.} , storing the result in the \textit { ct} buffer (\textit { pt} resp.). It is possible that the input and output buffer are
the same buffer. For the encrypt function \textit { pt} \footnote { pt stands for plaintext.} is the input and
2006-11-17 14:21:24 +00:00
\textit { ct} \footnote { ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
2014-08-28 12:42:19 +00:00
return \textbf { CRYPT\_ OK} on success. To test a particular cipher against test vectors\footnote { As published in their design papers.}
2006-11-17 14:21:24 +00:00
call the following self-test function.
2014-08-28 12:42:19 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Self--Testing}
2004-12-30 23:55:53 +00:00
\index { Cipher Testing}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
2014-08-28 12:42:19 +00:00
This function will return { \bf CRYPT\_ OK} if the cipher matches the test vectors from the design publication it is
based upon.
2005-04-17 11:37:13 +00:00
\subsection { Key Sizing}
2006-11-17 14:21:24 +00:00
For each cipher there is a function which will help find a desired key size. It is specified as follows:
2006-12-16 18:10:04 +00:00
\index { Key Sizing}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ keysize(int *keysize);
\end { verbatim}
2006-11-17 14:21:24 +00:00
Essentially, it will round the input keysize in \textit { keysize} down to the next appropriate key size. This function
will return { \bf CRYPT\_ OK} if the key size specified is acceptable. For example:
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int keysize, err;
2003-03-03 00:59:24 +00:00
/* now given a 20 byte key what keysize does Twofish want to use? */
keysize = 20;
2004-05-31 02:36:47 +00:00
if ((err = twofish_ keysize(& keysize)) != CRYPT_ OK) {
printf("Error getting key size: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
printf("Twofish suggested a key size of %d\n", keysize);
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit { keysize.}
2004-12-30 23:55:53 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Cipher Termination}
When you are finished with a cipher you can de--initialize it with the done function.
\begin { verbatim}
void XXX_ done(symmetric_ key *skey);
\end { verbatim}
2006-11-17 14:21:24 +00:00
For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
cipher descriptors may require to be called for resource management purposes. To be compliant, all functions which call a cipher
2005-04-17 11:37:13 +00:00
setup function must also call the respective cipher done function when finished.
2004-12-30 23:55:53 +00:00
\subsection { Simple Encryption Demonstration}
2006-11-17 14:21:24 +00:00
An example snippet that encodes a block with Blowfish in ECB mode.
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
\index { blowfish\_ setup()} \index { blowfish\_ ecb\_ encrypt()} \index { blowfish\_ ecb\_ decrypt()} \index { blowfish\_ done()}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
2014-08-28 12:42:19 +00:00
{
2003-03-03 00:59:24 +00:00
unsigned char pt[8], ct[8], key[8];
symmetric_ key skey;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
/* ... key is loaded appropriately in key ... */
/* ... load a block of plaintext in pt ... */
2003-03-03 00:59:24 +00:00
/* schedule the key */
2006-11-17 14:21:24 +00:00
if ((err = blowfish_ setup(key, /* the key we will use */
8, /* key is 8 bytes (64-bits) long */
0, /* 0 == use default # of rounds */
& skey) /* where to put the scheduled key */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("Setup error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* encrypt the block */
2006-11-17 14:21:24 +00:00
blowfish_ ecb_ encrypt(pt, /* encrypt this 8-byte array */
2014-08-28 12:42:19 +00:00
ct, /* store encrypted data here */
2006-11-17 14:21:24 +00:00
& skey); /* our previously scheduled key */
2014-08-28 12:42:19 +00:00
/* now ct holds the encrypted version of pt */
2003-03-03 00:59:24 +00:00
/* decrypt the block */
2006-11-17 14:21:24 +00:00
blowfish_ ecb_ decrypt(ct, /* decrypt this 8-byte array */
pt, /* store decrypted data here */
& skey); /* our previously scheduled key */
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
/* now we have decrypted ct to the original plaintext in pt */
2005-04-17 11:37:13 +00:00
/* Terminate the cipher context */
blowfish_ done(& skey);
2003-03-03 00:59:24 +00:00
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
\mysection { Key Sizes and Number of Rounds}
2003-03-03 00:59:24 +00:00
\index { Symmetric Keys}
2006-11-17 14:21:24 +00:00
As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it. Only a few of the ciphers support smaller
keys (mainly for test vectors anyways). Ideally, your application should be making at least 256 bit keys. This is not
because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
2003-03-03 00:59:24 +00:00
example, if you have $ \mbox { Pr } \left [ X = 1 \right ] = { 1 \over 2 } \pm \gamma $ where $ \vert \gamma \vert > 0 $ then the
total amount of entropy in N bits is $ N \cdot - log _ 2 \left ( { 1 \over 2 } + \vert \gamma \vert \right ) $ . So if $ \gamma $
were $ 0 . 25 $ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
only 53 bits of entropy.
The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
2014-08-28 12:42:19 +00:00
ciphers are configured such that the default number of rounds provide adequate security for the given block and key
2004-12-30 23:55:53 +00:00
size.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { The Cipher Descriptors}
2003-03-03 00:59:24 +00:00
\index { Cipher Descriptor}
2006-11-17 14:21:24 +00:00
To facilitate automatic routines an array of cipher descriptors is provided in the array \textit { cipher\_ descriptor} . An element
2006-12-16 18:10:04 +00:00
of this array has the following (partial) format (See Section \ref { sec:cipherdesc} ):
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
struct _ cipher_ descriptor {
2006-11-17 14:21:24 +00:00
/** name of cipher */
2003-03-03 00:59:24 +00:00
char *name;
2006-11-17 14:21:24 +00:00
/** internal ID */
2004-12-30 23:55:53 +00:00
unsigned char ID;
2006-11-17 14:21:24 +00:00
/** min keysize (octets) */
2014-08-28 12:42:19 +00:00
int min_ key_ length,
2006-11-17 14:21:24 +00:00
/** max keysize (octets) */
2014-08-28 12:42:19 +00:00
max_ key_ length,
2006-11-17 14:21:24 +00:00
/** block size (octets) */
2014-08-28 12:42:19 +00:00
block_ length,
2006-11-17 14:21:24 +00:00
/** default number of rounds */
2004-12-30 23:55:53 +00:00
default_ rounds;
2006-12-16 18:10:04 +00:00
...<snip>...
2003-03-03 00:59:24 +00:00
} ;
\end { verbatim}
2005-04-17 11:37:13 +00:00
\end { small}
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
Where \textit { name} is the lower case ASCII version of the name. The fields \textit { min\_ key\_ length} and \textit { max\_ key\_ length}
2006-11-17 14:21:24 +00:00
are the minimum and maximum key sizes in bytes. The \textit { block\_ length} member is the block size of the cipher
2004-12-30 23:55:53 +00:00
in bytes. As a good rule of thumb it is assumed that the cipher supports
2006-11-17 14:21:24 +00:00
the min and max key lengths but not always everything in between. The \textit { default\_ rounds} field is the default number
2003-03-03 00:59:24 +00:00
of rounds that will be used.
2006-11-17 14:21:24 +00:00
For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
and if missing will be emulated in software.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_ descriptor array is
marked when \textit { name} equals { \bf NULL} .
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
As of this release the current cipher\_ descriptors elements are the following:
\vfil
2004-05-31 02:36:47 +00:00
\index { Cipher descriptor table}
2006-12-16 18:10:04 +00:00
\index { blowfish\_ desc} \index { xtea\_ desc} \index { rc2\_ desc} \index { rc5\_ desc} \index { rc6\_ desc} \index { saferp\_ desc} \index { aes\_ desc} \index { twofish\_ desc}
2014-07-17 09:30:44 +00:00
\index { des\_ desc} \index { des3\_ desc} \index { noekeon\_ desc} \index { skipjack\_ desc} \index { anubis\_ desc} \index { khazad\_ desc} \index { kseed\_ desc} \index { kasumi\_ desc} \index { camellia\_ desc} \index { aes\_ enc\_ desc}
2017-10-18 05:12:45 +00:00
\index { idea\_ desc} \index { serpent\_ desc}
2006-11-17 14:21:24 +00:00
\begin { figure} [hpbt]
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |c|c|c|c|c|c|}
2006-11-17 14:21:24 +00:00
\hline \textbf { Name} & \textbf { Descriptor Name} & \textbf { Block Size} & \textbf { Key Range} & \textbf { Rounds} \\
2004-05-12 20:42:16 +00:00
\hline Blowfish & blowfish\_ desc & 8 & 8 $ \ldots $ 56 & 16 \\
2003-03-03 00:59:24 +00:00
\hline X-Tea & xtea\_ desc & 8 & 16 & 32 \\
2017-02-21 19:23:10 +00:00
\hline RC2 & rc2\_ desc & 8 & 5 $ \ldots $ 128 & 16 \\
2004-05-12 20:42:16 +00:00
\hline RC5-32/12/b & rc5\_ desc & 8 & 8 $ \ldots $ 128 & 12 $ \ldots $ 24 \\
\hline RC6-32/20/b & rc6\_ desc & 16 & 8 $ \ldots $ 128 & 20 \\
2003-03-03 00:59:24 +00:00
\hline SAFER+ & saferp\_ desc & 16 & 16, 24, 32 & 8, 12, 16 \\
2003-03-03 01:01:40 +00:00
\hline AES & aes\_ desc & 16 & 16, 24, 32 & 10, 12, 14 \\
2004-05-31 02:36:47 +00:00
& aes\_ enc\_ desc & 16 & 16, 24, 32 & 10, 12, 14 \\
2003-03-03 00:59:24 +00:00
\hline Twofish & twofish\_ desc & 16 & 16, 24, 32 & 16 \\
2007-07-20 17:48:02 +00:00
\hline DES & des\_ desc & 8 & 8 & 16 \\
2014-04-28 19:08:56 +00:00
\hline 3DES (EDE mode) & des3\_ desc & 8 & 16, 24 & 16 \\
2004-05-12 20:42:16 +00:00
\hline CAST5 (CAST-128) & cast5\_ desc & 8 & 5 $ \ldots $ 16 & 12, 16 \\
2003-03-03 01:01:40 +00:00
\hline Noekeon & noekeon\_ desc & 16 & 16 & 16 \\
2003-12-24 18:59:57 +00:00
\hline Skipjack & skipjack\_ desc & 8 & 10 & 32 \\
2004-12-30 23:55:53 +00:00
\hline Anubis & anubis\_ desc & 16 & 16 $ \ldots $ 40 & 12 $ \ldots $ 18 \\
\hline Khazad & khazad\_ desc & 8 & 16 & 8 \\
2006-11-17 14:21:24 +00:00
\hline SEED & kseed\_ desc & 16 & 16 & 16 \\
\hline KASUMI & kasumi\_ desc & 8 & 16 & 8 \\
2014-07-17 09:30:44 +00:00
\hline Camellia & camellia\_ desc & 16 & 16, 24, 32 & 18, 24 \\
2017-10-16 19:20:33 +00:00
\hline IDEA & idea\_ desc & 8 & 16 & 8 \\
2017-10-18 05:12:45 +00:00
\hline Serpent & serpent\_ desc & 16 & 16, 24, 32 & 32 \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\end { small}
2006-11-17 14:21:24 +00:00
\caption { Built--In Software Ciphers}
\end { figure}
2003-03-03 00:59:24 +00:00
\subsection { Notes}
2004-05-31 02:36:47 +00:00
\begin { small}
\begin { enumerate}
\item
2014-08-28 12:42:19 +00:00
For AES, (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
rijndael\_ desc and rijndael\_ enc\_ desc provide the cipher named \textit { rijndael} . The descriptors aes\_ desc and
2006-11-17 14:21:24 +00:00
aes\_ enc\_ desc provide the cipher name \textit { aes} . Functionally both \textit { rijndael} and \textit { aes} are the same cipher. The
2014-08-28 12:42:19 +00:00
only difference is when you call find\_ cipher() you have to pass the correct name. The cipher descriptors with \textit { enc}
2004-05-31 02:36:47 +00:00
in the middle (e.g. rijndael\_ enc\_ desc) are related to an implementation of Rijndael with only the encryption routine
2014-08-28 12:42:19 +00:00
and tables. The decryption and self--test function pointers of both \textit { encrypt only} descriptors are set to \textbf { NULL} and
2004-05-31 02:36:47 +00:00
should not be called.
2006-11-17 14:21:24 +00:00
The \textit { encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
as EAX, PMAC and OMAC only require the encryption function. So far this \textit { encrypt only} functionality has only been implemented for
2004-05-31 02:36:47 +00:00
Rijndael as it makes the most sense for this cipher.
\item
2006-11-17 14:21:24 +00:00
Note that for \textit { DES} and \textit { 3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
2003-03-03 00:59:24 +00:00
fact used for the purposes of encryption. My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
byte string from the real 7/21 byte key.
2014-07-17 09:30:44 +00:00
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.
2004-05-31 02:36:47 +00:00
\item
2006-11-17 14:21:24 +00:00
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 \times 32 $ s-boxes. This means that a scheduled
key will require less ram but the resulting cipher will be slower. The second option is \textit { TWOFISH\_ TABLES} which when
2003-03-03 00:59:24 +00:00
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
2006-11-17 14:21:24 +00:00
speed increase is useful when \textit { TWOFISH\_ SMALL} is defined since the s-boxes and MDS multiply form the heart of the
2003-03-03 00:59:24 +00:00
Twofish round function.
2006-11-17 14:21:24 +00:00
\begin { figure} [hpbt]
2006-12-16 18:10:04 +00:00
\index { Twofish build options} \index { TWOFISH\_ SMALL} \index { TWOFISH\_ TABLES}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { center}
\begin { tabular} { |l|l|l|}
2006-11-17 14:21:24 +00:00
\hline \textbf { TWOFISH\_ SMALL} & \textbf { TWOFISH\_ TABLES} & \textbf { Speed and Memory (per key)} \\
2003-03-03 00:59:24 +00:00
\hline undefined & undefined & Very fast, 4.2KB of ram. \\
2006-11-17 14:21:24 +00:00
\hline undefined & defined & Faster key setup, larger code. \\
2003-03-03 00:59:24 +00:00
\hline defined & undefined & Very slow, 0.2KB of ram. \\
2004-06-20 02:41:49 +00:00
\hline defined & defined & Faster, 0.2KB of ram, larger code. \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
\end { small}
2006-11-17 14:21:24 +00:00
\caption { Twofish Build Options}
\label { fig:twofishopts}
\end { figure}
2017-08-07 10:06:58 +00:00
\item
As of v1.18.0 of the library RC2 got an extended setup function (which didn't fit in the regular API):
\index { rc2\_ setup\_ ex()}
\begin { verbatim}
int rc2_ setup_ ex(const unsigned char *key,
int keylen,
int bits,
int num_ rounds,
symmetric_ key *skey);
\end { verbatim}
This setup function also allows to configure the effective key length in bits of the RC2 cipher as in its original specification.
2004-05-31 02:36:47 +00:00
\end { enumerate}
\end { small}
2017-08-07 10:06:58 +00:00
2003-03-03 00:59:24 +00:00
To work with the cipher\_ descriptor array there is a function:
2004-05-31 02:36:47 +00:00
\index { find\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int find_ cipher(char *name)
\end { verbatim}
2006-11-17 14:21:24 +00:00
Which will search for a given name in the array. It returns $ - 1 $ if the cipher is not found, otherwise it returns
2003-03-03 00:59:24 +00:00
the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
\begin { small}
2006-12-16 18:10:04 +00:00
\index { register\_ cipher()} \index { find\_ cipher()} \index { error\_ to\_ string()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char key[8];
symmetric_ key skey;
2004-05-31 02:36:47 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* you must register a cipher before you use it */
if (register_ cipher(& blowfish_ desc)) == -1) {
printf("Unable to register Blowfish cipher.");
return -1;
}
2014-08-28 12:42:19 +00:00
/* generic call to function (assuming the key
2006-11-17 14:21:24 +00:00
* in key[] was already setup) */
2014-08-28 12:42:19 +00:00
if ((err =
2006-11-17 14:21:24 +00:00
cipher_ descriptor[find_ cipher("blowfish")].
setup(key, 8, 0, & skey)) != CRYPT_ OK) {
2004-05-31 02:36:47 +00:00
printf("Error setting up Blowfish: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* ... use cipher ... */
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
A good safety would be to check the return value of \textit { find\_ cipher()} before accessing the desired function. In order
2003-03-03 00:59:24 +00:00
to use a cipher with the descriptor table you must register it first using:
2004-05-31 02:36:47 +00:00
\index { register\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int register_ cipher(const struct _ cipher_ descriptor *cipher);
\end { verbatim}
Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
as there is no more room (it can have 32 ciphers at most) it will return { \bf { -1} } . If you try to add the same cipher more
than once it will just return the index of the first copy. To remove a cipher call:
2004-05-31 02:36:47 +00:00
\index { unregister\_ cipher()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int unregister_ cipher(const struct _ cipher_ descriptor *cipher);
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which returns { \bf CRYPT\_ OK} if it removes the cipher, otherwise it returns { \bf CRYPT\_ ERROR} .
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int err;
2014-08-28 12:42:19 +00:00
2003-03-03 00:59:24 +00:00
/* register the cipher */
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael\n ");
return -1;
}
/* use Rijndael */
/* remove it */
2004-05-31 02:36:47 +00:00
if ((err = unregister_ cipher(& rijndael_ desc)) != CRYPT_ OK) {
printf("Error removing Rijndael: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
2014-08-28 12:42:19 +00:00
This snippet is a small program that registers Rijndael.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Symmetric Modes of Operations}
2003-03-03 00:59:24 +00:00
\subsection { Background}
A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
size of the cipher. Given a key $ k $ , a plaintext $ P $ and a cipher $ E $ we shall denote the encryption of the block
2017-09-20 11:54:42 +00:00
$ P $ under the key $ k $ as $ E _ k ( P ) $ . In some modes there exists an initialization vector denoted as $ C _ { - 1 } $ .
2003-03-03 00:59:24 +00:00
\subsubsection { ECB Mode}
2004-05-31 02:36:47 +00:00
\index { ECB mode}
2003-03-03 00:59:24 +00:00
ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
\begin { equation}
C_ i = E_ k(P_ i)
\end { equation}
This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
than once.
\subsubsection { CBC Mode}
2004-05-31 02:36:47 +00:00
\index { CBC mode}
2003-03-03 00:59:24 +00:00
CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
It is given as:
\begin { equation}
C_ i = E_ k(P_ i \oplus C_ { i - 1} )
\end { equation}
2017-09-20 11:54:42 +00:00
It is important that the initialization vector be unique and preferably random for each message encrypted under the same key.
2003-03-03 00:59:24 +00:00
\subsubsection { CTR Mode}
2004-05-31 02:36:47 +00:00
\index { CTR mode}
2017-09-20 11:54:42 +00:00
CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initialization vector which is
2003-03-03 00:59:24 +00:00
treated as a large binary counter the CTR mode is given as:
\begin { eqnarray}
C_ { -1} = C_ { -1} + 1\mbox { } (\mbox { mod } 2^ W) \nonumber \\
C_ i = P_ i \oplus E_ k(C_ { -1} )
\end { eqnarray}
2017-09-20 11:54:42 +00:00
Where $ W $ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initialization vector is random for each message
2003-03-03 00:59:24 +00:00
encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
2017-09-20 11:54:42 +00:00
as the block cipher is under a chosen plaintext attack (provided the initialization vector is unique).
2003-03-03 00:59:24 +00:00
\subsubsection { CFB Mode}
2004-05-31 02:36:47 +00:00
\index { CFB mode}
2003-03-03 00:59:24 +00:00
CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
\begin { eqnarray}
C_ i = P_ i \oplus C_ { -1} \nonumber \\
C_ { -1} = E_ k(C_ i)
\end { eqnarray}
Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
2017-09-20 11:54:42 +00:00
blocks without a delay. When this mode is first setup it will initially encrypt the initialization vector as required.
2003-03-03 00:59:24 +00:00
\subsubsection { OFB Mode}
2004-05-31 02:36:47 +00:00
\index { OFB mode}
2003-03-03 00:59:24 +00:00
OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
\begin { eqnarray}
C_ { -1} = E_ k(C_ { -1} ) \nonumber \\
C_ i = P_ i \oplus C_ { -1}
\end { eqnarray}
Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
\subsection { Choice of Mode}
My personal preference is for the CTR mode since it has several key benefits:
\begin { enumerate}
\item No short cycles which is possible in the OFB and CFB modes.
\item Provably as secure as the block cipher being used under a chosen plaintext attack.
\item Technically does not require the decryption routine of the cipher.
\item Allows random access to the plaintext.
\item Allows the encryption of block sizes that are not equal to the size of the block cipher.
\end { enumerate}
2014-08-28 12:42:19 +00:00
The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
2003-03-03 00:59:24 +00:00
block of memory with either of the three modes.
2006-11-17 14:21:24 +00:00
The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
2003-03-03 00:59:24 +00:00
other modes.
2006-11-17 14:21:24 +00:00
\subsection { Ciphertext Stealing}
\index { Ciphertext stealing}
Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
2014-08-28 12:42:19 +00:00
support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_ encrypt() callback function.
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
2006-11-17 14:21:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Initialization}
2003-03-03 00:59:24 +00:00
\index { CBC Mode} \index { CTR Mode}
\index { OFB Mode} \index { CFB Mode}
2014-08-28 12:42:19 +00:00
The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
2006-11-17 14:21:24 +00:00
you want is XXX there is a structure called \textit { symmetric\_ XXX} that will contain the information required to
2005-06-09 00:08:13 +00:00
use that mode. They have identical setup routines (except CTR and ECB mode):
2004-05-31 02:36:47 +00:00
\index { ecb\_ start()} \index { cfb\_ start()} \index { cbc\_ start()} \index { ofb\_ start()} \index { ctr\_ start()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ start( int cipher,
const unsigned char *IV,
const unsigned char *key,
int keylen,
int num_ rounds,
2006-11-17 14:21:24 +00:00
symmetric_ XXX *XXX);
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
int ctr_ start( int cipher,
2005-06-09 00:08:13 +00:00
const unsigned char *IV,
2014-08-28 12:42:19 +00:00
const unsigned char *key,
2006-11-17 14:21:24 +00:00
int keylen,
2014-08-28 12:42:19 +00:00
int num_ rounds,
2006-11-17 14:21:24 +00:00
int ctr_ mode,
symmetric_ CTR *ctr);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int ecb_ start( int cipher,
const unsigned char *key,
int keylen,
int num_ rounds,
2006-11-17 14:21:24 +00:00
symmetric_ ECB *ecb);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
In each case, \textit { cipher} is the index into the cipher\_ descriptor array of the cipher you want to use. The \textit { IV} value is
the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
length as the block size\footnote { In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
parameters \textit { key} , \textit { keylen} and \textit { num\_ rounds} are the same as in the XXX\_ setup() function call. The final parameter
2003-03-03 00:59:24 +00:00
is a pointer to the structure you want to hold the information for the mode of operation.
2014-08-28 12:42:19 +00:00
The routines return { \bf CRYPT\_ OK} if the cipher initialized correctly, otherwise, they return an error code.
2005-06-09 00:08:13 +00:00
2007-07-20 17:48:02 +00:00
\subsubsection { CTR Mode}
2006-11-17 14:21:24 +00:00
In the case of CTR mode there is an additional parameter \textit { ctr\_ mode} which specifies the mode that the counter is to be used in.
2014-08-28 12:42:19 +00:00
If \textbf { CTR\_ COUNTER\_ LITTLE\_ ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
2006-11-17 14:21:24 +00:00
\textbf { CTR\_ COUNTER\_ BIG\_ ENDIAN} was specified the counter will be treated as a big endian value. As of v1.15 the RFC 3686 style of
increment then encrypt is also supported. By OR'ing \textbf { LTC\_ CTR\_ RFC3686} with the CTR \textit { mode} value, ctr\_ start() will increment
the counter before encrypting it for the first time.
2005-06-09 00:08:13 +00:00
2007-07-20 17:48:02 +00:00
As of V1.17, the library supports variable length counters for CTR mode. The (optional) counter length is specified by OR'ing the octet
length of the counter against the \textit { ctr\_ mode} parameter. The default, zero, indicates that a full block length counter will be used. This also
ensures backwards compatibility with software that uses older versions of the library.
\begin { small}
\begin { verbatim}
symmetric_ CTR ctr;
int err;
unsigned char IV[16], key[16];
/* use a 32-bit little endian counter */
if ((err = ctr_ start(find_ cipher("aes"),
IV, key, 16, 0,
2014-08-28 12:42:19 +00:00
CTR_ COUNTER_ LITTLE_ ENDIAN | 4,
2007-07-20 17:48:02 +00:00
& ctr)) != CRYPT_ OK) {
handle_ error(err);
}
\end { verbatim}
\end { small}
Changing the counter size has little (really no) effect on the performance of the CTR chaining mode. It is provided for compatibility
with other software (and hardware) which have smaller fixed sized counters.
2005-04-17 11:37:13 +00:00
\subsection { Encryption and Decryption}
To actually encrypt or decrypt the following routines are provided:
2014-08-28 12:42:19 +00:00
\index { ecb\_ encrypt()} \index { ecb\_ decrypt()} \index { cfb\_ encrypt()} \index { cfb\_ decrypt()}
2004-05-31 02:36:47 +00:00
\index { cbc\_ encrypt()} \index { cbc\_ decrypt()} \index { ofb\_ encrypt()} \index { ofb\_ decrypt()} \index { ctr\_ encrypt()} \index { ctr\_ decrypt()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ encrypt(const unsigned char *pt,
unsigned char *ct,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ YYY *YYY);
2014-08-28 12:42:19 +00:00
int XXX_ decrypt(const unsigned char *ct,
unsigned char *pt,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ YYY *YYY);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Where \textit { XXX} is one of $ \lbrace ecb, cbc, ctr, cfb, ofb \rbrace $ .
2005-04-17 11:37:13 +00:00
2006-11-17 14:21:24 +00:00
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
2003-03-03 01:01:40 +00:00
five of the modes will return { \bf CRYPT\_ OK} on success from the encrypt or decrypt functions.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
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
2005-04-17 11:37:13 +00:00
zeroes or with whatever your protocol requires).
2006-11-17 14:21:24 +00:00
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.
2004-05-31 02:36:47 +00:00
2005-04-17 11:37:13 +00:00
\subsection { IV Manipulation}
2004-05-31 02:36:47 +00:00
To change or read the IV of a previously initialized chaining mode use the following two functions.
\index { cbc\_ setiv()} \index { cbc\_ getiv()} \index { ofb\_ setiv()} \index { ofb\_ getiv()} \index { cfb\_ setiv()} \index { cfb\_ getiv()}
\index { ctr\_ setiv()} \index { ctr\_ getiv()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ getiv(unsigned char *IV,
unsigned long *len,
2006-11-17 14:21:24 +00:00
symmetric_ XXX *XXX);
2014-08-28 12:42:19 +00:00
int XXX_ setiv(const unsigned char *IV,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ XXX *XXX);
2004-05-31 02:36:47 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
The XXX\_ getiv() functions will read the IV out of the chaining mode and store it into \textit { IV} along with the length of the IV
2006-11-17 14:21:24 +00:00
stored in \textit { len} . The XXX\_ setiv will initialize the chaining mode state as if the original IV were the new IV specified. The length
2004-05-31 02:36:47 +00:00
of the IV passed in must be the size of the ciphers block size.
2014-08-28 12:42:19 +00:00
The XXX\_ setiv() functions are handy if you wish to change the IV without re--keying the cipher.
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
What the \textit { setiv} function will do depends on the mode being changed. In CBC mode, the new IV replaces the existing IV as if it
2006-11-17 14:21:24 +00:00
were the last ciphertext block. In CFB mode, the IV is encrypted as if it were the prior encrypted pad. In CTR mode, the IV is encrypted without
first incrementing it (regardless of the LTC\_ RFC\_ 3686 flag presence). In F8 mode, the IV is encrypted and becomes the new pad. It does not change
the salted IV, and is only meant to allow seeking within a session. In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
2005-04-17 11:37:13 +00:00
\subsection { Stream Termination}
To terminate an open stream call the done function.
\index { ecb\_ done()} \index { cbc\_ done()} \index { cfb\_ done()} \index { ofb\_ done()} \index { ctr\_ done()}
\begin { verbatim}
int XXX_ done(symmetric_ XXX *XXX);
\end { verbatim}
This will terminate the stream (by terminating the cipher) and return \textbf { CRYPT\_ OK} if successful.
2003-03-03 00:59:24 +00:00
\newpage
2006-11-17 14:21:24 +00:00
\subsection { Examples}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char key[16], IV[16], buffer[512];
symmetric_ CTR ctr;
2004-05-31 02:36:47 +00:00
int x, err;
2003-03-03 00:59:24 +00:00
/* register twofish first */
if (register_ cipher(& twofish_ desc) == -1) {
printf("Error registering cipher.\n ");
return -1;
}
/* somehow fill out key and IV */
/* start up CTR mode */
2004-06-20 02:41:49 +00:00
if ((err = ctr_ start(
find_ cipher("twofish"), /* index of desired cipher */
2017-09-20 11:54:42 +00:00
IV, /* the initialization vector */
2004-06-20 02:41:49 +00:00
key, /* the secret key */
2006-11-17 14:21:24 +00:00
16, /* length of secret key (16 bytes) */
2004-06-20 02:41:49 +00:00
0, /* 0 == default # of rounds */
2005-06-09 00:08:13 +00:00
CTR_ COUNTER_ LITTLE_ ENDIAN, /* Little endian counter */
2006-11-17 14:21:24 +00:00
& ctr) /* where to store the CTR state */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("ctr_ start error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* somehow fill buffer than encrypt it */
2004-05-31 02:36:47 +00:00
if ((err = ctr_ encrypt( buffer, /* plaintext */
buffer, /* ciphertext */
2006-11-17 14:21:24 +00:00
sizeof(buffer), /* length of plaintext pt */
& ctr) /* CTR state */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("ctr_ encrypt error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* make use of ciphertext... */
2004-05-31 02:36:47 +00:00
/* now we want to decrypt so let's use ctr_ setiv */
if ((err = ctr_ setiv( IV, /* the initial IV we gave to ctr_ start */
16, /* the IV is 16 bytes long */
& ctr) /* the ctr state we wish to modify */
) != CRYPT_ OK) {
printf("ctr_ setiv error: %s\n", error_to_string(err));
return -1;
}
if ((err = ctr_ decrypt( buffer, /* ciphertext */
buffer, /* plaintext */
2006-11-17 14:21:24 +00:00
sizeof(buffer), /* length of plaintext */
& ctr) /* CTR state */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("ctr_ decrypt error: %s\n", error_to_string(err));
return -1;
}
2005-04-17 11:37:13 +00:00
/* terminate the stream */
if ((err = ctr_ done(& ctr)) != CRYPT_ OK) {
printf("ctr_ done error: %s\n", error_to_string(err));
return -1;
}
2003-03-03 00:59:24 +00:00
/* clear up and return */
zeromem(key, sizeof(key));
zeromem(& ctr, sizeof(ctr));
return 0;
}
\end { verbatim}
\end { small}
2006-01-26 18:11:56 +00:00
\subsection { LRW Mode}
2014-08-28 12:42:19 +00:00
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
2006-01-26 18:11:56 +00:00
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.
2014-08-28 12:42:19 +00:00
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.
2006-01-26 18:11:56 +00:00
To initialize LRW mode use:
\index { lrw\_ start()}
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int lrw_ start( int cipher,
2006-01-26 18:11:56 +00:00
const unsigned char *IV,
2014-08-28 12:42:19 +00:00
const unsigned char *key,
2006-11-17 14:21:24 +00:00
int keylen,
2006-01-26 18:11:56 +00:00
const unsigned char *tweak,
2014-08-28 12:42:19 +00:00
int num_ rounds,
2006-11-17 14:21:24 +00:00
symmetric_ LRW *lrw);
2006-01-26 18:11:56 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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} .
2006-11-17 14:21:24 +00:00
While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit { cipher} . The
number of rounds for the block cipher \textit { num\_ rounds} can be 0 to use the default number of rounds for the given cipher.
2006-01-26 18:11:56 +00:00
To process data use the following functions:
\index { lrw\_ encrypt()} \index { lrw\_ decrypt()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int lrw_ encrypt(const unsigned char *pt,
unsigned char *ct,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ LRW *lrw);
2014-08-28 12:42:19 +00:00
int lrw_ decrypt(const unsigned char *ct,
unsigned char *pt,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ LRW *lrw);
2006-01-26 18:11:56 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
of 16. The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.
2006-01-26 18:11:56 +00:00
To manipulate the IV use the following functions:
2014-08-28 12:42:19 +00:00
\index { lrw\_ getiv()} \index { lrw\_ setiv()}
2006-01-26 18:11:56 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int lrw_ getiv(unsigned char *IV,
unsigned long *len,
2006-11-17 14:21:24 +00:00
symmetric_ LRW *lrw);
2006-01-26 18:11:56 +00:00
2014-08-28 12:42:19 +00:00
int lrw_ setiv(const unsigned char *IV,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ LRW *lrw);
\end { verbatim}
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
2006-01-26 18:11:56 +00:00
updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
To terminate the LRW state use the following:
\index { lrw\_ done()}
\begin { verbatim}
int lrw_ done(symmetric_ LRW *lrw);
\end { verbatim}
2007-07-20 17:48:02 +00:00
\subsection { XTS Mode}
2014-08-28 12:42:19 +00:00
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.
2007-07-20 17:48:02 +00:00
To initialize XTS mode use the following function call:
\index { xts\_ start()}
\begin { verbatim}
int xts_ start( int cipher,
2014-08-28 12:42:19 +00:00
const unsigned char *key1,
const unsigned char *key2,
2007-07-20 17:48:02 +00:00
unsigned long keylen,
2014-08-28 12:42:19 +00:00
int num_ rounds,
2007-07-20 17:48:02 +00:00
symmetric_ xts *xts)
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will start the XTS mode with the two keys pointed to by \textit { key1} and \textit { key2} of length \textit { keylen} octets each.
2007-07-20 17:48:02 +00:00
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}
2014-08-28 12:42:19 +00:00
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).
2007-07-20 17:48:02 +00:00
2014-08-28 12:42:19 +00:00
The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.
2007-07-20 17:48:02 +00:00
To terminate the XTS state call the following function:
\index { xts\_ done()}
\begin { verbatim}
void xts_ done(symmetric_ xts *xts);
\end { verbatim}
2006-08-30 23:30:00 +00:00
\subsection { F8 Mode}
\index { F8 Mode}
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
2006-11-17 14:21:24 +00:00
initialize F8 mode with the following function call:
2006-08-30 23:30:00 +00:00
\index { f8\_ start()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int f8_ start( int cipher,
const unsigned char *IV,
const unsigned char *key,
int keylen,
const unsigned char *salt_ key,
2006-11-17 14:21:24 +00:00
int skeylen,
2014-08-28 12:42:19 +00:00
int num_ rounds,
2006-11-17 14:21:24 +00:00
symmetric_ F8 *f8);
2006-08-30 23:30:00 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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.
2006-08-30 23:30:00 +00:00
To encrypt or decrypt data we use the following two functions:
\index { f8\_ encrypt()} \index { f8\_ decrypt()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int f8_ encrypt(const unsigned char *pt,
unsigned char *ct,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ F8 *f8);
2006-08-30 23:30:00 +00:00
2014-08-28 12:42:19 +00:00
int f8_ decrypt(const unsigned char *ct,
unsigned char *pt,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ F8 *f8);
2006-08-30 23:30:00 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-08-30 23:30:00 +00:00
of the ciphers block size.
To change or retrieve the current counter IV value use the following functions:
2006-11-17 14:21:24 +00:00
\index { f8\_ getiv()} \index { f8\_ setiv()}
2006-08-30 23:30:00 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int f8_ getiv(unsigned char *IV,
unsigned long *len,
2006-11-17 14:21:24 +00:00
symmetric_ F8 *f8);
2014-08-28 12:42:19 +00:00
int f8_ setiv(const unsigned char *IV,
unsigned long len,
2006-11-17 14:21:24 +00:00
symmetric_ F8 *f8);
2006-08-30 23:30:00 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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
2006-08-30 23:30:00 +00:00
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:
\index { f8\_ done()}
\begin { verbatim}
int f8_ done(symmetric_ F8 *f8);
\end { verbatim}
2017-07-17 22:07:47 +00:00
\chapter { Stream Ciphers}
2017-07-20 21:09:28 +00:00
Stream ciphers are symmetric key ciphers which operate on a stream of bytes (in theory on a stream of bits
however LibTomCrypt's implementation works with bytes).
2017-08-07 10:06:58 +00:00
The API for all stream ciphers operates in mode: \textit { setup} -- \textit { crypt} -- \textit { crypt} -- ... -- \textit { done} .
2017-08-08 19:38:23 +00:00
Please note that both encryption and decryption are implemented via \textit { crypt} .
2017-07-20 21:09:28 +00:00
2017-08-08 19:38:23 +00:00
Another useful feature of the stream ciphers API is generation of a random stream of bytes which works like:
2017-07-20 21:09:28 +00:00
\textit { setup} -- \textit { keystream} -- \textit { keystream} -- ... -- \textit { done} . The random stream generation is
2017-08-08 19:38:23 +00:00
implemented like encryption of a stream of \textit { 0x00} bytes.
2017-07-20 21:09:28 +00:00
2017-08-14 22:07:53 +00:00
Note: You shouldn't use the keystream interface as a PRNG, as it doesn't allow to re-seed the internal state.
2017-07-20 21:09:28 +00:00
\mysection { ChaCha}
2017-08-08 19:38:23 +00:00
\textit { ChaCha} is currently the most modern stream cipher included in LibTomCrypt, so use this one unless you
2017-07-20 21:09:28 +00:00
have a reason for using some of the older algorithms.
For more information about ChaCha see \url { https://en.wikipedia.org/wiki/ChaCha_ (cipher)} .
Supported key size: 16 or 32 bytes (128 or 256 bits).
You can initialize ChaCha with 96bit \textit { nonce} + 32bit \textit { counter} :
\begin { verbatim}
chacha_ state st;
err = chacha_ setup(& st, key, key_ len, rounds);
err = chacha_ ivctr32(& st, nonce, 12, initial_ 32bit_ ctr);
\end { verbatim}
Or with 64bit \textit { nonce} + 64bit \textit { counter} :
\begin { verbatim}
chacha_ state st;
err = chacha_ setup(& st, key, key_ len, rounds);
err = chacha_ ivctr64(& st, nonce, 8, initial_ 64bit_ ctr);
\end { verbatim}
2017-08-08 19:38:23 +00:00
The \textit { chacha\_ setup} takes the number of rounds as a parameter -- choose 20 if you are not sure.
As always never ever use the same key + nonce pair more than once.
2017-07-20 21:09:28 +00:00
2017-08-08 19:38:23 +00:00
For the actual encryption or decryption you have to call:
2017-07-20 21:09:28 +00:00
\begin { verbatim}
err = chacha_ crypt(& st, in_ buffer, in_ len, out_ buffer);
\end { verbatim}
2017-08-08 19:38:23 +00:00
If you just want a random stream of bytes initialize the cipher with a truly random \textit { key} (32 bytes),
a truly random \textit { nonce} (8 bytes) and zero initial counter. After that you can get a stream of pseudo--random
2017-07-20 21:09:28 +00:00
bytes via:
\begin { verbatim}
err = chacha_ keystream(& st, out_ buffer, out_ len);
\end { verbatim}
At the end you have to terminate the state:
\begin { verbatim}
err = chacha_ done(& st);
\end { verbatim}
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using ChaCha for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = chacha_ memory(key, keylen, iv, ivlen, datain, datalen, rounds, dataout);
\end { verbatim}
2018-05-31 18:58:21 +00:00
\mysection { Salsa20 and XSalsa20}
\textit { Salsa20} was Daniel Bernstein's submission to the EU eSTREAM
competition where a reduced-round version, \textit { Salsa20/12} , was named
one of the winners. A third version, \textit { Salsa20/8} , was also evaluated.
\vspace { 1mm}
While 20 rounds is the conservative default number of rounds, eSTREAM deemed
12 rounds to be a decent balance between strength and better performance.
The 8-round version, while still secure as of this writing, is faster but
does not enjoy the same margin of safety. Regardless of the number of rounds,
\textit { Salsa20} accepts either a 128- or a 256-bit key, a 64-bit IV, and a
64-bit counter.
\vspace { 1mm}
\textit { XSalsa20} is yet another variant of \textit { Salsa20} designed to accept
only a 256-bit key and a longer 192-bit nonce, initialization being the only
difference between \textit { XSalsa20} and \textit { Salsa20} . Even the
\textit { salsa20\_ state} is the same. Thereafter, salsa20\_ crypt(),
salsa20\_ keystream(), and salsa20\_ done() are used unaltered.
salsa20\_ ivctr64() is NOT used with xsalsa20\_ setup().
\vspace { 1mm}
To initialize \textit { Salsa20} for 8, 12, or 20 rounds with a 128- or a
256-bit key (16 or 32 bytes), a 64-bit IV (8 bytes), and counter (typically
zero), use:
2017-10-23 22:41:42 +00:00
\begin { verbatim}
salsa20_ state st;
2018-05-31 18:58:21 +00:00
ulong64 counter = 0;
2017-10-23 22:41:42 +00:00
err = salsa20_ setup(& st, key, key_ len, rounds);
2018-05-31 18:58:21 +00:00
err = salsa20_ ivctr64(& st, nonce, 8, counter);
2017-10-23 22:41:42 +00:00
\end { verbatim}
2018-05-31 18:58:21 +00:00
To initialize \textit { XSalsa20} for the recommended 20 rounds with a 256-bit
2018-05-23 07:50:48 +00:00
key (32 bytes) and a 192-bit nonce (24 bytes), use:
2017-10-23 22:41:42 +00:00
2018-05-31 18:58:21 +00:00
\begin { verbatim}
salsa20_ state st;
err = xsalsa20_ setup(& st, key, key_ len, nonce, nonce_ len, rounds);
\end { verbatim}
Both \textit { Salsa20} and \textit { XSalsa20} use the following functions. To
encrypt or decrypt call:
2017-10-23 22:41:42 +00:00
\begin { verbatim}
err = salsa20_ crypt(& st, in_ buffer, in_ len, out_ buffer);
\end { verbatim}
2018-05-31 18:58:21 +00:00
For a random keystream initialize the cipher with a truly random \textit { key}
and random \textit { nonce} after which you can get a stream of
pseudo--random bytes via:
2017-10-23 22:41:42 +00:00
\begin { verbatim}
err = salsa20_ keystream(& st, out_ buffer, out_ len);
\end { verbatim}
2018-05-31 18:58:21 +00:00
Finally, when finished you should wipe the state.
2017-10-23 22:41:42 +00:00
\begin { verbatim}
err = salsa20_ done(& st);
\end { verbatim}
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using Salsa20 for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = salsa20_ memory(key, keylen, iv, ivlen, datain, datalen, rounds, dataout);
\end { verbatim}
To encrypt plaintext (or decrypt ciphertext) using XSalsa20 for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = xsalsa20_ memory(key, keylen, nonce, nonce_ len, datain, datalen, rounds, dataout);
\end { verbatim}
2018-05-31 18:58:21 +00:00
For both \textit { Salsa20} and \textit { XSalsa20} rounds must be an even number
and if set to 0 the default number of rounds, 20, will be used.
\vspace { 1mm}
2018-06-03 15:45:15 +00:00
If you define \textit { LTC\_ XSALSA20} to include \textit { XSalsa20} in a minimal
\textit { libtomcrypt} library build, you must also define \textit { LTC\_ SALSA20} .
2018-05-31 18:58:21 +00:00
\vspace { 1mm}
As always, never ever use the same key + nonce/IV pair more than once.
\vspace { 1mm}
For more information about Salsa20 see
\url { https://en.wikipedia.org/wiki/Salsa20} .
\vspace { 1mm}
For more information about XSalsa20 see
\url { https://cr.yp.to/snuffle/xsalsa-20081128.pdf} .
\vspace { 1mm}
2017-11-20 10:41:30 +00:00
\mysection { Sosemanuk}
\textit { Sosemanuk} , along with Salsa20, HC-128, and Rabbit, was named one of the winners in
the EU eSTREAM competition. Sosemanuk is a stream cipher that borrows heavily from SNOW,
another stream cipher, and the block cipher Serpent. (Sosemanuk means "snow snake" in the
Cree Indian language.)
Sosemanuk will accept a key between 1 and 256 bits, but Sosemanuk's security level of 128
bits is achieved only if the key is between 128 and 256 bits. Keys longer than 128 bits
are not guaranteed to provided higher security. The initialization vector is 128 bits.
2017-12-05 06:15:18 +00:00
(All length arguments are expressed in bytes.)
2017-11-20 10:41:30 +00:00
See \url { http://www.ecrypt.eu.org/stream/p3ciphers/sosemanuk/sosemanuk_ p3.pdf} for more
information.
2017-12-05 06:15:18 +00:00
Initialize by creating a Sosemanuk state and provide a 128- to 256-bit key to \textit { sosemanuk\_ setup()} .
2017-11-20 10:41:30 +00:00
\begin { verbatim}
2018-07-10 00:31:24 +00:00
sosemanuk_ state st;
err = sosemanuk_ setup(& st, key, keylen);
2017-11-20 10:41:30 +00:00
\end { verbatim}
2017-12-05 06:15:18 +00:00
Finish initializing with an iv of up to 128 bits.
2017-11-20 10:41:30 +00:00
\begin { verbatim}
2018-07-10 00:31:24 +00:00
err = sosemanuk_ setiv(& st, iv, ivlen);
2017-11-20 10:41:30 +00:00
\end { verbatim}
For the actual encryption or decryption, call:
\begin { verbatim}
2018-07-10 00:31:24 +00:00
err = sosemanuk_ crypt(& st, in, inlen, out);
2017-11-20 10:41:30 +00:00
\end { verbatim}
2017-12-05 06:15:18 +00:00
If you just want a random stream of bytes initialize the cipher with a truly random
2017-12-05 17:53:15 +00:00
\textit { key} (256 bits) and a truly random \textit { iv} (128 bits). After that you can
2017-11-20 10:41:30 +00:00
get a stream of pseudo--random bytes via:
\begin { verbatim}
2018-07-10 00:31:24 +00:00
err = sosemanuk_ keystream(& st, out, outlen);
2017-11-20 10:41:30 +00:00
\end { verbatim}
2017-12-05 08:55:07 +00:00
When finished you should wipe the key by running \textit { sosemanuk\_ done()} .
2017-11-20 10:41:30 +00:00
\begin { verbatim}
2018-07-10 00:31:24 +00:00
err = sosemanuk_ done(& st);
2017-11-20 10:41:30 +00:00
\end { verbatim}
2017-12-05 06:15:18 +00:00
To do multiple encryptions and decryptions with the same key, you will want to set the iv but
you do not need to re-run \textit { sosemanuk\_ setup()} again, unless of course, you called
\textit { sosemanuk\_ done()} .
2017-11-20 10:41:30 +00:00
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using Sosemanuk for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = sosemanuk_ memory(key, keylen, iv, ivlen, datain, datalen, dataout);
\end { verbatim}
2017-12-06 06:12:50 +00:00
\mysection { Rabbit}
\textit { Rabbit} , along with Salsa20, Sosemanuk, and HC-128, was named one of the winners
in the EU eSTREAM competition. Rabbit is a simple and fast cipher suitable for resource
constrained platforms.
This implementation of Rabbit will accept a key of up to 16 bytes (128 bits), and an
initialization vector of up to 8 bytes (64 bits). If the provided key or IV is shorter,
they will be null padded to that length. There is no rounds option.
The calls to \textit { rabbit\_ crypt()} or \textit { rabbit\_ keystream()} may be for any
number bytes although their generation will be more efficient if the requests are for
multiples of 16 bytes.
You begin initializing Rabbit by creating a state and calling \textit { rabbit\_ setup()}
with a 128-bit key.
\begin { verbatim}
rabbit_ state st;
err = rabbit_ setup(& st, key, keylen);
\end { verbatim}
2018-01-20 14:31:00 +00:00
Set the IV using \textit { rabbit\_ setiv()} with a 64-bit IV.
2017-12-06 06:12:50 +00:00
\begin { verbatim}
err = rabbit_ setiv(& st, iv, iv_ len);
\end { verbatim}
For the actual encryption or decryption, call:
\begin { verbatim}
err = rabbit_ crypt(& st, in_ buffer, inlen, out_ buffer);
\end { verbatim}
If you just want a random stream of bytes initialize the cipher with a truly random \textit { key}
(16 bytes), a truly random \textit { iv} (8 bytes). After that you can
get a stream of pseudo--random bytes via:
\begin { verbatim}
err = rabbit_ keystream(& st, out_ buffer, length);
\end { verbatim}
When finished you should wipe the key and the state:
\begin { verbatim}
err = rabbit_ done(& st);
\end { verbatim}
Technically, it is possible to initialize Rabbit with only a call to \textit { rabbit\_ setup()} ,
skipping the call to \textit { rabbit\_ setiv()} . This is not recommended for interoperability reasons,
but there may be special cases like closed systems or custom protocols where doing so might be
appropriate. Please note that skipping \textit { rabbit\_ setiv()} will give results different than
2018-01-20 14:31:00 +00:00
calling \textit { rabbit\_ setiv()} passing a zero-valued IV. You should call \textit { rabbit\_ setiv()} unless
2017-12-06 06:12:50 +00:00
you have a special reason for not doing so.
To do multiple encryptions and decryptions with the same key, you can reset the algorithm
using \textit { rabbit\_ setiv()} if you saved the state and did not wipe it with \textit { rabbit\_ done()} .
You will want to use a different IV but you do not need to call \textit { rabbit\_ setup()} a 2nd time,
unless of course, you skipped calling \textit { rabbit\_ setiv()} .
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using Rabbit for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = rabbit_ memory(key, keylen, iv, ivlen, datain, datalen, dataout);
\end { verbatim}
2017-12-06 06:12:50 +00:00
For more information, see: \newline
\hspace { 4em} - \url { http://www.ecrypt.eu.org/stream/p3ciphers/rabbit/rabbit_ p3.pdf} \newline
\hspace { 4em} - \url { https://tools.ietf.org/html/rfc4503}
2017-07-17 22:07:47 +00:00
\mysection { RC4}
2017-07-20 21:09:28 +00:00
For more information about RC4 see \url { https://en.wikipedia.org/wiki/RC4} .
2017-07-17 22:07:47 +00:00
2017-07-20 21:09:28 +00:00
Supported key size: 5--256 bytes
2017-08-08 19:38:23 +00:00
You need to initialize RC4 only with a \textit { key} .
2017-07-17 22:07:47 +00:00
\begin { verbatim}
2017-07-20 21:09:28 +00:00
rc4_ state st;
err = rc4_ stream_ setup(& st, key, key_ len);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2017-08-08 19:38:23 +00:00
For the actual encryption or decryption you have to call:
2017-07-20 21:09:28 +00:00
\begin { verbatim}
err = rc4_ stream_ crypt(& st, in_ buffer, in_ len, out_ buffer);
\end { verbatim}
2017-07-17 22:07:47 +00:00
2017-07-20 21:09:28 +00:00
If you just want a random stream of bytes initialize the cipher with truly random \textit { key} .
After that you can get a stream of pseudo--random bytes via:
\begin { verbatim}
err = rc4_ stream_ keystream(& st, out_ buffer, out_ len);
\end { verbatim}
2017-07-17 22:07:47 +00:00
2017-07-20 21:09:28 +00:00
At the end you have to terminate the state:
2017-07-17 22:07:47 +00:00
\begin { verbatim}
2017-07-20 21:09:28 +00:00
err = rc4_ stream_ done(& st);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using RC6 for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = rc4_ stream_ memory(key, keylen, datain, datalen, dataout);
\end { verbatim}
2017-07-20 21:09:28 +00:00
\mysection { Sober128}
2017-07-17 22:07:47 +00:00
2017-07-20 21:09:28 +00:00
Supported key size: must be multiple of 4 bytes
2004-01-25 17:40:34 +00:00
2017-07-20 21:09:28 +00:00
You need to initialize Sober128 with a \textit { key} and a \textit { nonce} (must be multiple of 4 bytes).
\begin { verbatim}
sober128_ state st;
err = sober128_ stream_ setup(& st, key, 16);
err = sober128_ stream_ setiv(& st, nonce, 12);
\end { verbatim}
2017-07-17 22:07:47 +00:00
2017-07-20 21:09:28 +00:00
For the actual encryption or decryption you to call:
2017-07-17 22:07:47 +00:00
\begin { verbatim}
2017-07-20 21:09:28 +00:00
err = sober128_ stream_ crypt(& st, in_ buffer, in_ len, out_ buffer);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2017-07-20 21:09:28 +00:00
If you just want a random stream of bytes initialize the cipher with a truly random \textit { key}
and a truly random \textit { nonce} . After that you can get a stream of pseudo--random bytes via:
\begin { verbatim}
err = sober128_ stream_ keystream(& st, out_ buffer, out_ len);
\end { verbatim}
At the end you have to terminate the state:
\begin { verbatim}
err = sober128_ stream_ done(& st);
\end { verbatim}
2017-07-17 22:07:47 +00:00
2018-07-30 05:12:42 +00:00
To encrypt plaintext (or decrypt ciphertext) using Sober128 for data already in
memory with a single function call, the following function may be used.
\begin { verbatim}
err = sober128_ stream_ memory(key, keylen, iv, ivlen, datain, datalen, dataout);
\end { verbatim}
2017-07-17 22:07:47 +00:00
\chapter { Authenticated Encryption}
Authenticated Encryption - sometimes also called Authenticated Encryption with Associated Data (AEAD) - is a variant of encryption
that provides not only confidentiality (as other symmetric or stream ciphers) but also integrity.
2017-08-07 10:06:58 +00:00
The inputs of Authenticated Encryption are: \textit { key} , \textit { nonce} (sometimes called initialization vector), \textit { plaintext} ,
2017-07-17 22:07:47 +00:00
optional \textit { header} (sometimes called additional authenticated data - AAD). The outputs are: \textit { ciphertext} and \textit { tag} .
\mysection { EAX Mode}
2014-08-28 12:42:19 +00:00
LibTomCrypt provides support for a mode called EAX\footnote { See
M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
by the designers. First, a short description of what EAX mode is before we explain how to use it. EAX is a mode that requires a cipher,
CTR and OMAC support and provides encryption and
authentication\footnote { Note that since EAX only requires OMAC and CTR you may use \textit { encrypt only} cipher descriptors with this mode.} .
2006-11-17 14:21:24 +00:00
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.
2004-01-25 17:40:34 +00:00
2006-11-17 14:21:24 +00:00
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.
2004-01-25 17:40:34 +00:00
The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
2006-11-17 14:21:24 +00:00
called a \textit { tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
2004-01-25 17:40:34 +00:00
sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
of operation.
The mode is initialized with the following function.
2004-05-31 02:36:47 +00:00
\index { eax\_ init()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int eax_ init( eax_ state *eax,
int cipher,
const unsigned char *key,
2006-11-17 14:21:24 +00:00
unsigned long keylen,
2014-08-28 12:42:19 +00:00
const unsigned char *nonce,
2006-11-17 14:21:24 +00:00
unsigned long noncelen,
2014-08-28 12:42:19 +00:00
const unsigned char *header,
2006-11-17 14:21:24 +00:00
unsigned long headerlen);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Where \textit { eax} is the EAX state. The \textit { cipher} parameter is the index of the desired cipher in the descriptor table.
The \textit { key} parameter is the shared secret symmetric key of length \textit { keylen} octets. The \textit { nonce} parameter is the
random public string of length \textit { noncelen} octets. The \textit { header} parameter is the random (or fixed or \textbf { NULL} ) header for the
2006-11-17 14:21:24 +00:00
message of length \textit { headerlen} octets.
2004-01-25 17:40:34 +00:00
2014-08-28 12:42:19 +00:00
When this function completes, the \textit { eax} state will be initialized such that you can now either have data decrypted or
2006-11-17 14:21:24 +00:00
encrypted in EAX mode. Note: if \textit { headerlen} is zero you may pass \textit { header} as \textbf { NULL} to indicate there is no initial header data.
2004-01-25 17:40:34 +00:00
To encrypt or decrypt data in a streaming mode use the following.
2004-05-31 02:36:47 +00:00
\index { eax\_ encrypt()} \index { eax\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int eax_ encrypt( eax_ state *eax,
const unsigned char *pt,
unsigned char *ct,
2006-11-17 14:21:24 +00:00
unsigned long length);
2004-01-25 17:40:34 +00:00
2014-08-28 12:42:19 +00:00
int eax_ decrypt( eax_ state *eax,
const unsigned char *ct,
unsigned char *pt,
2006-11-17 14:21:24 +00:00
unsigned long length);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
The function \textit { eax\_ encrypt} will encrypt the bytes in \textit { pt} of \textit { length} octets, and store the ciphertext in
\textit { ct} . Note: \textit { ct} and \textit { pt} may be the same region in memory. This function will also send the ciphertext
2014-08-28 12:42:19 +00:00
through the OMAC function. The function \textit { eax\_ decrypt} decrypts \textit { ct} , and stores it in \textit { pt} . This also allows
\textit { pt} and \textit { ct} to be the same region in memory.
2004-01-25 17:40:34 +00:00
2014-08-28 12:42:19 +00:00
You cannot both encrypt or decrypt with the same \textit { eax} context. For bi--directional communication you will need to initialize
two EAX contexts (preferably with different headers and nonces).
2004-05-31 02:36:47 +00:00
2006-11-17 14:21:24 +00:00
Note: both of these functions allow you to send the data in any granularity but the order is important. While
2004-01-25 17:40:34 +00:00
the eax\_ init() function allows you to add initial header data to the stream you can also add header data during the
EAX stream with the following.
2004-05-31 02:36:47 +00:00
\index { eax\_ addheader()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int eax_ addheader( eax_ state *eax,
const unsigned char *header,
2006-11-17 14:21:24 +00:00
unsigned long length);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will add the \textit { length} octet from \textit { header} to the given \textit { eax} header. Once the message is finished, the
2006-11-17 14:21:24 +00:00
\textit { tag} (checksum) may be computed with the following function:
2004-01-25 17:40:34 +00:00
2004-05-31 02:36:47 +00:00
\index { eax\_ done()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int eax_ done( eax_ state *eax,
unsigned char *tag,
2006-11-17 14:21:24 +00:00
unsigned long *taglen);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will terminate the EAX state \textit { eax} , and store up to \textit { taglen} bytes of the message tag in \textit { tag} . The function
then stores how many bytes of the tag were written out back in to \textit { taglen} .
2004-01-25 17:40:34 +00:00
2006-11-17 14:21:24 +00:00
The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
2004-05-31 02:36:47 +00:00
\index { eax\_ test()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
int eax_ test(void);
\end { verbatim}
This requires that the AES (or Rijndael) block cipher be registered with the cipher\_ descriptor table first.
2004-05-31 02:36:47 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-05-31 02:36:47 +00:00
int main(void)
{
int err;
eax_ state eax;
unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
unsigned long taglen;
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael");
return EXIT_ FAILURE;
}
/* ... make up random nonce and key ... */
/* initialize context */
2006-11-17 14:21:24 +00:00
if ((err = eax_ init( & eax, /* context */
find_ cipher("rijndael"), /* cipher id */
nonce, /* the nonce */
16, /* nonce is 16 bytes */
"TestApp", /* example header */
7) /* header length */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("Error eax_ init: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* now encrypt data, say in a loop or whatever */
2006-11-17 14:21:24 +00:00
if ((err = eax_ encrypt( & eax, /* eax context */
pt, /* plaintext (source) */
ct, /* ciphertext (destination) */
sizeof(pt) /* size of plaintext */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("Error eax_ encrypt: %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* finish message and get authentication tag */
taglen = sizeof(tag);
2006-11-17 14:21:24 +00:00
if ((err = eax_ done( & eax, /* eax context */
tag, /* where to put tag */
& taglen /* length of tag space */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("Error eax_ done: %s", error_to_string(err));
return EXIT_ FAILURE;
}
2014-08-28 12:42:19 +00:00
/* now we have the authentication tag in "tag" and
2006-11-17 14:21:24 +00:00
* it's taglen bytes long */
2004-05-31 02:36:47 +00:00
}
\end { verbatim}
2014-08-28 12:42:19 +00:00
You can also perform an entire EAX state on a block of memory in a single function call with the
2004-05-31 02:36:47 +00:00
following functions.
\index { eax\_ encrypt\_ authenticate\_ memory} \index { eax\_ decrypt\_ verify\_ memory}
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int eax_ encrypt_ authenticate_ memory(
int cipher,
2004-05-31 02:36:47 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
2006-11-17 14:21:24 +00:00
int eax_ decrypt_ verify_ memory(
int cipher,
2004-05-31 02:36:47 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
unsigned char *tag, unsigned long taglen,
int *res);
\end { verbatim}
Both essentially just call eax\_ init() followed by eax\_ encrypt() (or eax\_ decrypt() respectively) and eax\_ done(). The parameters
2014-08-28 12:42:19 +00:00
have the same meaning as with those respective functions.
2004-05-31 02:36:47 +00:00
The only difference is eax\_ decrypt\_ verify\_ memory() does not emit a tag. Instead you pass it a tag as input and it compares it against
2006-11-17 14:21:24 +00:00
the tag it computed while decrypting the message. If the tags match then it stores a $ 1 $ in \textit { res} , otherwise it stores a $ 0 $ .
2004-05-31 02:36:47 +00:00
2017-08-07 10:06:58 +00:00
\mysection { OCB Modes}
\subsection { Preface}
LibTomCrypt provides support for a mode called OCB in version 1 ''OCB''\footnote { See
2006-11-17 14:21:24 +00:00
P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit { OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption} .}
2017-08-07 10:06:58 +00:00
and version 3 ''OCB3''\footnote { See RFC7253, T. Krovetz, P. Rogaway, \textit { The OCB Authenticated-Encryption Algorithm} .} .
OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
but is less flexible.
Please be aware that all versions of OCB are patented and there are several licensing models provided by P. Rogaway, the patent holder
-- see \url { http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm} .
\subsection { OCB}
\subsubsection { Initialization and processing}
Let's review how to initialize an OCB context.
2004-01-25 17:40:34 +00:00
2004-05-31 02:36:47 +00:00
\index { ocb\_ init()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ocb_ init( ocb_ state *ocb,
int cipher,
const unsigned char *key,
unsigned long keylen,
2004-01-25 17:40:34 +00:00
const unsigned char *nonce);
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will initialize the \textit { ocb} context using cipher descriptor \textit { cipher} . It will use a \textit { key} of length \textit { keylen}
and the random \textit { nonce} . Note that \textit { nonce} must be a random (public) string the same length as the block ciphers
2004-05-31 02:36:47 +00:00
block size (e.g. 16 bytes for AES).
2004-01-25 17:40:34 +00:00
2006-11-17 14:21:24 +00:00
This mode has no \textit { Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
2004-01-25 17:40:34 +00:00
To encrypt or decrypt data use the following.
2004-05-31 02:36:47 +00:00
\index { ocb\_ encrypt()} \index { ocb\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ocb_ encrypt( ocb_ state *ocb,
const unsigned char *pt,
2006-11-17 14:21:24 +00:00
unsigned char *ct);
2014-08-28 12:42:19 +00:00
int ocb_ decrypt( ocb_ state *ocb,
const unsigned char *ct,
2006-11-17 14:21:24 +00:00
unsigned char *pt);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will encrypt (or decrypt for the latter) a fixed length of data from \textit { pt} to \textit { ct} (vice versa for the latter).
They assume that \textit { pt} and \textit { ct} are the same size as the block cipher's block size. Note that you cannot call
2006-11-17 14:21:24 +00:00
both functions given a single \textit { ocb} state. For bi-directional communication you will have to initialize two \textit { ocb}
states (with different nonces). Also \textit { pt} and \textit { ct} may point to the same location in memory.
2004-01-25 17:40:34 +00:00
2017-08-07 10:06:58 +00:00
\subsubsection { State Termination}
2005-04-17 11:37:13 +00:00
2004-01-25 17:40:34 +00:00
When you are finished encrypting the message you call the following function to compute the tag.
2004-05-31 02:36:47 +00:00
\index { ocb\_ done\_ encrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ocb_ done_ encrypt( ocb_ state *ocb,
const unsigned char *pt,
2006-11-17 14:21:24 +00:00
unsigned long ptlen,
2014-08-28 12:42:19 +00:00
unsigned char *ct,
unsigned char *tag,
2006-11-17 14:21:24 +00:00
unsigned long *taglen);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will terminate an encrypt stream \textit { ocb} . If you have trailing bytes of plaintext that will not complete a block
2006-11-17 14:21:24 +00:00
you can pass them here. This will also encrypt the \textit { ptlen} bytes in \textit { pt} and store them in \textit { ct} . It will also
store up to \textit { taglen} bytes of the tag into \textit { tag} .
2004-01-25 17:40:34 +00:00
2014-08-28 12:42:19 +00:00
Note that \textit { ptlen} must be less than or equal to the block size of block cipher chosen. Also note that if you have
an input message equal to the length of the block size then you pass the data here (not to ocb\_ encrypt()) only.
2004-01-25 17:40:34 +00:00
To terminate a decrypt stream and compared the tag you call the following.
2004-05-31 02:36:47 +00:00
\index { ocb\_ done\_ decrypt()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ocb_ done_ decrypt( ocb_ state *ocb,
const unsigned char *ct,
2006-11-17 14:21:24 +00:00
unsigned long ctlen,
2014-08-28 12:42:19 +00:00
unsigned char *pt,
const unsigned char *tag,
unsigned long taglen,
2006-11-17 14:21:24 +00:00
int *res);
2004-01-25 17:40:34 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
2006-11-17 14:21:24 +00:00
tag of the message (internally) and then compare it against the \textit { taglen} bytes of \textit { tag} provided. By default
\textit { res} is set to zero. If all \textit { taglen} bytes of \textit { tag} can be verified then \textit { res} is set to one (authenticated
2004-01-25 17:40:34 +00:00
message).
2017-08-07 10:06:58 +00:00
\subsubsection { Packet Functions}
2004-01-25 17:40:34 +00:00
To make life simpler the following two functions are provided for memory bound OCB.
2006-12-16 18:10:04 +00:00
%\index{ocb\_encrypt\_authenticate\_memory()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int ocb_ encrypt_ authenticate_ memory(
int cipher,
2004-01-25 17:40:34 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const unsigned char *nonce,
2004-01-25 17:40:34 +00:00
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will OCB encrypt the message \textit { pt} of length \textit { ptlen} , and store the ciphertext in \textit { ct} . The length \textit { ptlen}
2014-08-28 12:42:19 +00:00
can be any arbitrary length.
2004-01-25 17:40:34 +00:00
2004-05-31 02:36:47 +00:00
\index { ocb\_ decrypt\_ verify\_ memory()}
2004-01-25 17:40:34 +00:00
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int ocb_ decrypt_ verify_ memory(
int cipher,
2004-01-25 17:40:34 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const unsigned char *nonce,
2004-01-25 17:40:34 +00:00
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *res);
\end { verbatim}
2014-08-28 12:42:19 +00:00
Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit { res} is set
2017-08-07 10:06:58 +00:00
appropriately to \textit { 1} if the tag matches or to \textit { 0} if it doesn't match.
2017-07-20 21:44:30 +00:00
2017-08-07 10:06:58 +00:00
\subsection { OCB3}
\subsubsection { Initialization and processing}
2017-07-20 21:44:30 +00:00
2017-08-07 10:06:58 +00:00
\index { ocb3\_ init()}
2017-07-20 21:44:30 +00:00
\begin { verbatim}
int ocb3_ init(ocb3_ state *ocb, int cipher,
const unsigned char *key, unsigned long keylen,
2017-08-08 18:14:42 +00:00
const unsigned char *nonce, unsigned long noncelen,
unsigned long taglen);
2017-08-07 10:06:58 +00:00
\end { verbatim}
This will initialize the \textit { ocb} context using cipher descriptor \textit { cipher} . It will use a \textit { key} of length \textit { keylen}
2017-08-08 18:14:42 +00:00
and the random \textit { nonce} of length \textit { noncelen} . The \textit { nonce} must be a random (public) string of an arbitrary length
between 1 and 15 octets. The desired length of the TAG that should be created when terminating the state has to be passed in \textit { taglen}
and has to be between 0 and 16 octets.
Note that you can only use ciphers with a block length of 16.
2017-08-07 10:06:58 +00:00
\subsubsection { Additional Authenticated Data}
2017-07-20 21:44:30 +00:00
2017-08-07 10:06:58 +00:00
OCB3 has, in contrary to OCB, the possibility to add "Additional Authenticated Data" (AAD) when performing cryptographic operations.
\index { ocb3\_ add\_ aad()}
\begin { verbatim}
int ocb3_ add_ aad(ocb3_ state *ocb, const unsigned char *aad, unsigned long aadlen);
\end { verbatim}
This will add the AAD at \textit { aad} of the arbitrary length \textit { aadlen} to be authenticated within the context \textit { ocb} .
\index { ocb3\_ encrypt()} \index { ocb3\_ decrypt()}
\begin { verbatim}
int ocb3_ encrypt( ocb3_ state *ocb,
const unsigned char *pt,
unsigned long ptlen,
unsigned char *ct);
int ocb3_ decrypt( ocb3_ state *ocb,
const unsigned char *ct,
unsigned long ctlen,
unsigned char *pt);
\end { verbatim}
This will encrypt (or decrypt for the latter) a fixed length of data from \textit { pt} to \textit { ct} (vice versa for the latter).
They assume that \textit { pt} and \textit { ct} are the same size as the block cipher's block size. Note that you cannot call
both functions given a single \textit { ocb} state. For bi-directional communication you will have to initialize two \textit { ocb}
states (with different nonces). Also \textit { pt} and \textit { ct} may point to the same location in memory.
\subsubsection { State Termination}
\index { ocb3\_ encrypt\_ last()} \index { ocb3\_ decrypt\_ last()}
\begin { verbatim}
2017-08-08 18:14:42 +00:00
int ocb3_ encrypt_ last( ocb3_ state *ocb,
const unsigned char *pt,
unsigned long ptlen,
unsigned char *ct);
2017-08-07 10:06:58 +00:00
2017-08-08 18:14:42 +00:00
int ocb3_ decrypt_ last( ocb3_ state *ocb,
const unsigned char *ct,
unsigned long ctlen,
unsigned char *pt);
2017-08-07 10:06:58 +00:00
\end { verbatim}
2017-08-08 18:14:42 +00:00
This has to be called for the last encrypt (or decrypt) operation. Note that if you have to invoke only a single operation you can
directly use these functions instead of \textit { ocb3\_ encrypt()} or \textit { ocb3\_ decrypt()} .
2017-08-07 10:06:58 +00:00
When you are finished encrypting the message you call the following function to compute the tag.
\index { ocb3\_ done()}
\begin { verbatim}
2017-07-20 21:44:30 +00:00
int ocb3_ done(ocb3_ state *ocb, unsigned char *tag, unsigned long *taglen);
2017-08-07 10:06:58 +00:00
\end { verbatim}
This stores the tag of the \textit { ocb} state in \textit { tag} .
The \textit { taglen} parameter defines on input the length of the tag to output and will be set to the actual length written, which
2017-08-08 18:14:42 +00:00
is at most 16 octets.
2017-07-20 21:44:30 +00:00
2017-08-07 10:06:58 +00:00
\subsubsection { Packet Functions}
To make life simpler the following two functions are provided for memory bound OCB3.
\index { ocb3\_ encrypt\_ authenticate\_ memory()}
\begin { verbatim}
2017-07-20 21:44:30 +00:00
int ocb3_ encrypt_ authenticate_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *adata, unsigned long adatalen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
2017-08-07 10:06:58 +00:00
\end { verbatim}
2017-07-20 21:44:30 +00:00
2017-08-08 18:14:42 +00:00
This will OCB3 encrypt the message \textit { pt} of length \textit { ptlen} , and store the ciphertext in \textit { ct} . The length \textit { ptlen}
can be any arbitrary length. The additional authenticated data \textit { adata} of length \textit { adatalen} is optional and can be left out
by passing \textit { NULL} as \textit { adata} . The length of the authentication TAG will be stored in \textit { tag} , which is also optional.
The length of the TAG passed in \textit { taglen} has to be between 0 and 16.
2017-08-07 10:06:58 +00:00
\index { ocb3\_ decrypt\_ verify\_ memory()}
\begin { verbatim}
2017-07-20 21:44:30 +00:00
int ocb3_ decrypt_ verify_ memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *adata, unsigned long adatalen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *stat);
\end { verbatim}
2017-08-08 18:14:42 +00:00
Similarly, this will OCB3 decrypt, and compare the internally computed tag against the tag provided. \textit { res} is set
appropriately to \textit { 1} if the tag matches or to \textit { 0} if it doesn't match.
2017-07-17 22:07:47 +00:00
\mysection { CCM Mode}
2017-07-09 10:45:52 +00:00
CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.
2014-11-03 09:25:40 +00:00
2017-07-17 22:07:47 +00:00
\subsection { Initialization}
2014-11-03 09:25:40 +00:00
To initialize the CCM context with a secret key call the following function.
\index { ccm\_ init()}
\begin { verbatim}
int ccm_ init( ccm_ state *ccm,
int cipher,
const unsigned char *key,
int keylen,
int ptlen,
int taglen,
int aadlen);
\end { verbatim}
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
as \textit { aadlen} .
2017-07-17 22:07:47 +00:00
\subsection { Nonce Vector}
2017-09-20 11:54:42 +00:00
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.
2014-11-03 09:25:40 +00:00
\index { ccm\_ add\_ nonce()}
\begin { verbatim}
int ccm_ add_ nonce( ccm_ state *ccm,
const unsigned char *nonce,
unsigned long noncelen);
\end { verbatim}
2014-11-03 22:13:07 +00:00
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
2014-11-03 09:25:40 +00:00
once and only once.
2017-07-17 22:07:47 +00:00
\subsection { Additional Authentication Data}
2014-11-03 22:13:07 +00:00
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.
2014-11-03 09:25:40 +00:00
\index { ccm\_ add\_ aad()}
\begin { verbatim}
int ccm_ add_ aad( ccm_ state *ccm,
const unsigned char *adata,
unsigned long adatalen);
\end { verbatim}
This adds the additional authentication data \textit { adata} of length \textit { adatalen} to the CCM state \textit { ccm} .
2017-07-17 22:07:47 +00:00
\subsection { Plaintext Processing}
2014-11-03 09:25:40 +00:00
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
\index { ccm\_ process()}
\begin { verbatim}
int ccm_ process(ccm_ state *ccm,
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 { CCM\_ ENCRYPT} the plaintext is read,
encrypted and stored in the ciphertext buffer. When \textit { direction} equals \textbf { CCM\_ DECRYPT} the opposite occurs.
2017-07-17 22:07:47 +00:00
\subsection { State Termination}
2014-11-03 09:25:40 +00:00
To terminate a CCM state and retrieve the message authentication tag call the following function.
\index { ccm\_ done()}
\begin { verbatim}
int ccm_ done( ccm_ state *ccm,
unsigned char *tag,
unsigned long *taglen);
\end { verbatim}
This terminates the CCM state \textit { ccm} and stores the tag in \textit { tag} of length \textit { taglen} octets.
2017-07-17 22:07:47 +00:00
\subsection { State Reset}
2014-11-03 09:25:40 +00:00
The call to ccm\_ init() will perform considerable pre--computation and if you're going to be dealing with a lot of packets
2014-11-03 22:13:07 +00:00
it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function is provided.
2014-11-03 09:25:40 +00:00
\index { ccm\_ reset()}
\begin { verbatim}
int ccm_ reset(ccm_ state *ccm);
\end { verbatim}
This will reset the CCM state \textit { ccm} to the state that ccm\_ init() left it. The user would then call ccm\_ add\_ nonce(), ccm\_ add\_ aad(), etc.
2017-07-17 22:07:47 +00:00
\subsection { One--Shot Packet}
2014-11-03 09:25:40 +00:00
To process a single packet under any given key the following helper function can be used.
2005-04-17 11:37:13 +00:00
\index { ccm\_ memory()}
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int ccm_ memory(
int cipher,
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
2005-11-18 05:15:37 +00:00
symmetric_ key *uskey,
2005-04-17 11:37:13 +00:00
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
\end { verbatim}
2014-11-03 09:25:40 +00:00
This will initialize the CCM state with the given key, nonce 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.
2005-11-18 05:15:37 +00:00
2014-11-03 09:25:40 +00:00
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.
2005-11-18 05:15:37 +00:00
2017-07-17 22:07:47 +00:00
\subsection { Example Usage}
2014-11-03 09:25:40 +00:00
The following is an example usage of how to use CCM over multiple packets with a shared secret key.
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
\begin { small}
\begin { verbatim}
#include <tomcrypt.h>
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
int send_ packet(const unsigned char *pt, unsigned long ptlen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *aad, unsigned long aadlen,
ccm_ state *ccm)
{
int err;
unsigned long taglen;
unsigned char tag[16];
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
/* reset the state */
if ((err = ccm_ reset(ccm)) != CRYPT_ OK) {
return err;
}
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
/* Add the nonce */
if ((err = ccm_ add_ nonce(ccm, nonce, noncelen)) != CRYPT_ OK) {
return err;
}
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
/* Add the AAD (note: aad can be NULL if aadlen == 0) */
if ((err = ccm_ add_ aad(ccm, aad, aadlen)) != CRYPT_ OK) {
return err;
}
2005-04-17 11:37:13 +00:00
2014-11-03 09:25:40 +00:00
/* process the plaintext */
if ((err =
ccm_ process(ccm, pt, ptlen, pt, CCM_ ENCRYPT)) != CRYPT_ OK) {
return err;
}
/* Finish up and get the MAC tag */
taglen = sizeof(tag);
if ((err = ccm_ done(ccm, tag, & taglen)) != CRYPT_ OK) {
return err;
}
/* ... send a header describing the lengths ... */
/* depending on the protocol and how nonce is
* generated you may have to send it too... */
send(socket, nonce, noncelen, 0);
/* send the aad */
send(socket, aad, aadlen, 0);
/* send the ciphertext */
send(socket, pt, ptlen, 0);
/* send the tag */
send(socket, tag, taglen, 0);
return CRYPT_ OK;
}
2006-11-17 14:21:24 +00:00
int main(void)
{
2014-11-03 09:25:40 +00:00
ccm_ state ccm;
unsigned char key[16], NONCE[12], pt[PACKET_ SIZE];
int err, x;
unsigned long ptlen;
2006-11-17 14:21:24 +00:00
2014-11-03 09:25:40 +00:00
/* somehow fill key/NONCE with random values */
2006-11-17 14:21:24 +00:00
2014-11-03 09:25:40 +00:00
/* register AES */
register_ cipher(& aes_ desc);
2014-08-28 12:42:19 +00:00
2014-11-03 09:25:40 +00:00
/* init the CCM state */
2014-08-28 12:42:19 +00:00
if ((err =
2014-11-03 09:25:40 +00:00
ccm_ init(& ccm, find_ cipher("aes"), key, 16, PACKET_ SIZE, 16, size(NONCE))) != CRYPT_ OK) {
whine_ and_ pout(err);
2006-11-17 14:21:24 +00:00
}
2014-11-03 09:25:40 +00:00
/* handle us some packets */
for (;;) {
ptlen = make_ packet_ we_ want_ to_ send(pt);
/* use NONCE as counter (12 byte counter) */
for (x = 11; x >= 0; x--) {
if (++NONCE[x]) {
break;
}
}
if ((err = send_ packet(pt, ptlen, NONCE, 12, NULL, 0, & ccm))
!= CRYPT_ OK) {
whine_ and_ pout(err);
}
2006-11-17 14:21:24 +00:00
}
2014-11-03 09:25:40 +00:00
return EXIT_ SUCCESS;
2006-11-17 14:21:24 +00:00
}
\end { verbatim}
\end { small}
2017-07-17 22:07:47 +00:00
\mysection { GCM Mode}
2014-08-28 12:42:19 +00:00
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
2006-11-17 14:21:24 +00:00
block ciphers with a 16--byte block.
2005-04-17 11:37:13 +00:00
2017-09-20 11:54:42 +00:00
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
2014-08-28 12:42:19 +00:00
unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { Initialization}
2005-04-17 11:37:13 +00:00
To initialize the GCM context with a secret key call the following function.
\index { gcm\_ init()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int gcm_ init( gcm_ state *gcm,
2006-11-17 14:21:24 +00:00
int cipher,
2014-08-28 12:42:19 +00:00
const unsigned char *key,
2006-11-17 14:21:24 +00:00
int keylen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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).
2005-04-17 11:37:13 +00:00
2017-09-20 11:54:42 +00:00
\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.
2005-04-17 11:37:13 +00:00
\index { gcm\_ add\_ iv()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int gcm_ add_ iv( gcm_ state *gcm,
const unsigned char *IV,
2006-11-17 14:21:24 +00:00
unsigned long IVlen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2017-09-20 11:54:42 +00:00
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
2014-08-28 12:42:19 +00:00
to process the entire IV.
2005-04-17 11:37:13 +00:00
2006-11-17 14:21:24 +00:00
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.
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { Additional Authentication Data}
2006-11-17 14:21:24 +00:00
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.
2005-04-17 11:37:13 +00:00
\index { gcm\_ add\_ aad()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int gcm_ add_ aad( gcm_ state *gcm,
const unsigned char *adata,
2006-11-17 14:21:24 +00:00
unsigned long adatalen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This adds the additional authentication data \textit { adata} of length \textit { adatalen} to the GCM state \textit { gcm} .
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { Plaintext Processing}
2014-08-28 12:42:19 +00:00
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
2005-04-17 11:37:13 +00:00
\index { gcm\_ process()}
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int gcm_ process( gcm_ state *gcm,
2014-08-28 12:42:19 +00:00
unsigned char *pt,
2006-11-17 14:21:24 +00:00
unsigned long ptlen,
unsigned char *ct,
int direction);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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,
2006-11-17 14:21:24 +00:00
encrypted and stored in the ciphertext buffer. When \textit { direction} equals \textbf { GCM\_ DECRYPT} the opposite occurs.
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { State Termination}
2005-04-17 11:37:13 +00:00
To terminate a GCM state and retrieve the message authentication tag call the following function.
\index { gcm\_ done()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int gcm_ done( gcm_ state *gcm,
unsigned char *tag,
2006-11-17 14:21:24 +00:00
unsigned long *taglen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This terminates the GCM state \textit { gcm} and stores the tag in \textit { tag} of length \textit { taglen} octets.
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { State Reset}
2005-04-17 11:37:13 +00:00
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
2006-11-17 14:21:24 +00:00
it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
2005-04-17 11:37:13 +00:00
\index { gcm\_ reset()}
\begin { verbatim}
int gcm_ reset(gcm_ state *gcm);
\end { verbatim}
2006-11-17 14:21:24 +00:00
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.
2005-04-17 11:37:13 +00:00
2017-07-17 22:07:47 +00:00
\subsection { One--Shot Packet}
2005-04-17 11:37:13 +00:00
To process a single packet under any given key the following helper function can be used.
\index { gcm\_ memory()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int gcm_ memory(
2006-11-17 14:21:24 +00:00
int cipher,
2014-08-28 12:42:19 +00:00
const unsigned char *key,
2006-11-17 14:21:24 +00:00
unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
2014-08-28 12:42:19 +00:00
unsigned char *ct,
2006-11-17 14:21:24 +00:00
unsigned char *tag, unsigned long *taglen,
int direction);
2005-04-17 11:37:13 +00:00
\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.
2017-07-17 22:07:47 +00:00
\subsection { Example Usage}
2005-04-17 11:37:13 +00:00
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;
}
2014-08-28 12:42:19 +00:00
2005-04-17 11:37:13 +00:00
/* Add the IV */
if ((err = gcm_ add_ iv(gcm, iv, ivlen)) != CRYPT_ OK) {
return err;
}
/* Add the AAD (note: aad can be NULL if aadlen == 0) */
if ((err = gcm_ add_ aad(gcm, aad, aadlen)) != CRYPT_ OK) {
return err;
}
/* process the plaintext */
2014-08-28 12:42:19 +00:00
if ((err =
2006-12-16 18:10:04 +00:00
gcm_ process(gcm, pt, ptlen, pt, GCM_ ENCRYPT)) != CRYPT_ OK) {
2005-04-17 11:37:13 +00:00
return err;
}
/* Finish up and get the MAC tag */
taglen = sizeof(tag);
if ((err = gcm_ done(gcm, tag, & taglen)) != CRYPT_ OK) {
return err;
}
2005-06-09 00:08:13 +00:00
/* ... send a header describing the lengths ... */
2014-08-28 12:42:19 +00:00
/* depending on the protocol and how IV is
2006-11-17 14:21:24 +00:00
* generated you may have to send it too... */
2005-04-17 11:37:13 +00:00
send(socket, iv, ivlen, 0);
/* send the aad */
send(socket, aad, aadlen, 0);
/* send the ciphertext */
send(socket, pt, ptlen, 0);
/* send the tag */
send(socket, tag, taglen, 0);
return CRYPT_ OK;
}
int main(void)
{
gcm_ state gcm;
unsigned char key[16], IV[12], pt[PACKET_ SIZE];
int err, x;
2014-08-28 12:42:19 +00:00
unsigned long ptlen;
2005-04-17 11:37:13 +00:00
/* somehow fill key/IV with random values */
2014-08-28 12:42:19 +00:00
2005-04-17 11:37:13 +00:00
/* register AES */
register_ cipher(& aes_ desc);
/* init the GCM state */
2014-08-28 12:42:19 +00:00
if ((err =
2006-12-16 18:10:04 +00:00
gcm_ init(& gcm, find_ cipher("aes"), key, 16)) != CRYPT_ OK) {
2005-04-17 11:37:13 +00:00
whine_ and_ pout(err);
}
/* handle us some packets */
for (;;) {
ptlen = make_ packet_ we_ want_ to_ send(pt);
/* use IV as counter (12 byte counter) */
for (x = 11; x >= 0; x--) {
if (++IV[x]) {
break;
}
}
2014-08-28 12:42:19 +00:00
if ((err = send_ packet(pt, ptlen, iv, 12, NULL, 0, & gcm))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2005-04-17 11:37:13 +00:00
whine_ and_ pout(err);
}
}
return EXIT_ SUCCESS;
}
\end { verbatim}
\end { small}
2017-07-17 22:07:47 +00:00
\mysection { ChaCha20--Poly1305}
This authenticated encryption is based on ChaCha20 stream cipher and Poly1305 authenticator.
2017-09-19 20:23:21 +00:00
It is defined by \url { https://tools.ietf.org/html/rfc7539} .
2017-07-17 22:07:47 +00:00
2017-09-19 20:23:21 +00:00
\subsection { Initialization}
To initialize the ChaCha20--Poly1305 context with a secret key call the following function.
2017-07-17 22:07:47 +00:00
2017-09-19 20:23:21 +00:00
\index { chacha20poly1305\_ init()}
2017-07-17 22:07:47 +00:00
\begin { verbatim}
2017-09-19 20:23:21 +00:00
int chacha20poly1305_ init(chacha20poly1305_ state *st,
const unsigned char *key,
unsigned long keylen);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2017-09-19 20:23:21 +00:00
This initializes the ChaCha20--Poly1305 state \textit { st} with a secret key \textit { key} of length \textit { keylen}
octets (valid lengths: 32 or 16).
2017-09-20 11:54:42 +00:00
\subsection { Initialization Vector}
After the state has been initialized the next step is to add the initialization vector.
2017-09-19 20:23:21 +00:00
\index { chacha20poly1305\_ setiv()}
\begin { verbatim}
int chacha20poly1305_ setiv(chacha20poly1305_ state *st,
const unsigned char *iv,
unsigned long ivlen);
\end { verbatim}
2017-09-20 11:54:42 +00:00
This adds the initialization vector from \textit { iv} of length \textit { ivlen} octects (valid lengths: 8 or 12) to
2017-09-19 20:23:21 +00:00
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}
2017-09-20 11:54:42 +00:00
This also adds the initialization vector from \textit { iv} of length \textit { ivlen} octects (valid lengths: 8 or 12) to
2017-09-19 20:23:21 +00:00
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} .
2017-07-17 22:07:47 +00:00
2017-09-19 20:23:21 +00:00
\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
2017-10-17 21:37:30 +00:00
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
2017-09-19 20:23:21 +00:00
variables is the same as it is for all the manual functions.
2017-07-17 22:07:47 +00:00
2003-03-03 00:59:24 +00:00
\chapter { One-Way Cryptographic Hash Functions}
2006-11-17 14:21:24 +00:00
\mysection { Core Functions}
2014-08-28 12:42:19 +00:00
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
2006-11-17 14:21:24 +00:00
XXX (where XXX is the name) call:
2003-03-03 00:59:24 +00:00
\index { Hash Functions}
\begin { verbatim}
void XXX_ init(hash_ state *md);
\end { verbatim}
2006-11-17 14:21:24 +00:00
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:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ process( hash_ state *md,
const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2017-08-14 09:48:05 +00:00
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:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
md5_ process(& md, "hello ", 6);
md5_ process(& md, "world", 5);
\end { verbatim}
Will produce the same message digest as the single call:
\index { Message Digest}
\begin { verbatim}
md5_ process(& md, "hello world", 11);
\end { verbatim}
To finally get the message digest (the hash) call:
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ done( hash_ state *md,
2006-11-17 14:21:24 +00:00
unsigned char *out);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This function will finish up the hash and store the result in the \textit { out} array. You must ensure that \textit { out} is long
enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the \textit { XXX\_ done()} functions
will wipe the \textit { md} variable before returning automatically.
2003-03-03 00:59:24 +00:00
To test a hash function call:
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will return { \bf CRYPT\_ OK} if the hash matches the test vectors, otherwise it returns an error code. An
2003-03-03 00:59:24 +00:00
example snippet that hashes a message with md5 is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
hash_ state md;
unsigned char *in = "hello world", out[16];
/* setup the hash */
md5_ init(& md);
/* add the message */
md5_ process(& md, in, strlen(in));
2003-03-13 02:12:16 +00:00
/* get the hash in out[0..15] */
2003-03-03 00:59:24 +00:00
md5_ done(& md, out);
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
\mysection { Hash Descriptors}
Like the set of ciphers, the set of hashes have descriptors as well. They are stored in an array called \textit { hash\_ descriptor} and
2003-03-03 00:59:24 +00:00
are defined by:
\begin { verbatim}
struct _ hash_ descriptor {
char *name;
2006-11-17 14:21:24 +00:00
2003-03-03 00:59:24 +00:00
unsigned long hashsize; /* digest output size in bytes */
unsigned long blocksize; /* the block size the hash uses */
2006-11-17 14:21:24 +00:00
2004-12-30 23:55:53 +00:00
void (*init) (hash_ state *hash);
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
int (*process)( hash_ state *hash,
const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen);
2004-12-30 23:55:53 +00:00
int (*done) (hash_ state *hash, unsigned char *out);
2006-11-17 14:21:24 +00:00
2003-03-03 00:59:24 +00:00
int (*test) (void);
} ;
\end { verbatim}
2005-08-01 16:36:47 +00:00
\index { find\_ hash()}
2006-11-17 14:21:24 +00:00
The \textit { name} member is the name of the hash function (all lowercase). The \textit { hashsize} member is the size of the digest output
in bytes, while \textit { blocksize} is the size of blocks the hash expects to the compression function. Technically, this detail is not important
2014-08-28 12:42:19 +00:00
for high level developers but is useful to know for performance reasons.
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
The \textit { init} member initializes the hash, \textit { process} passes data through the hash, \textit { done} terminates the hash and retrieves the
2006-11-17 14:21:24 +00:00
digest. The \textit { test} member tests the hash against the specified test vectors.
There is a function to search the array as well called \textit { int find\_ hash(char *name)} . It returns -1 if the hash is not found, otherwise, the
2003-03-03 00:59:24 +00:00
position in the descriptor table of the hash.
2006-11-17 14:21:24 +00:00
In addition, there is also find\_ hash\_ oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
\index { find\_ hash\_ oid()}
2005-08-01 16:36:47 +00:00
\begin { verbatim}
int find_ hash_ oid(const unsigned long *ID, unsigned long IDlen);
\end { verbatim}
2006-11-17 14:21:24 +00:00
You can use the table to indirectly call a hash function that is chosen at run-time. For example:
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
unsigned char buffer[100], hash[MAXBLOCKSIZE];
int idx, x;
hash_ state md;
/* register hashes .... */
if (register_ hash(& md5_ desc) == -1) {
printf("Error registering MD5.\n ");
return -1;
}
/* register other hashes ... */
/* prompt for name and strip newline */
printf("Enter hash name: \n ");
fgets(buffer, sizeof(buffer), stdin);
buffer[strlen(buffer) - 1] = 0;
/* get hash index */
idx = find_ hash(buffer);
if (idx == -1) {
printf("Invalid hash name!\n ");
return -1;
}
/* hash input until blank line */
hash_ descriptor[idx].init(& md);
while (fgets(buffer, sizeof(buffer), stdin) != NULL)
hash_ descriptor[idx].process(& md, buffer, strlen(buffer));
hash_ descriptor[idx].done(& md, hash);
/* dump to screen */
for (x = 0; x < hash_ descriptor[idx].hashsize; x++)
printf("%02x ", hash[x]);
printf("\n ");
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
Note the usage of \textbf { MAXBLOCKSIZE} . In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf { MAXBLOCKSIZE} in
2003-03-03 00:59:24 +00:00
length. This provides a simple size you can set your automatic arrays to that will not get overrun.
2006-12-16 18:10:04 +00:00
There are three helper functions to make working with hashes easier. The first is a function to hash a buffer, and produce the digest in a single
function call.
2014-08-28 12:42:19 +00:00
\index { hash\_ memory()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hash_ memory( int hash,
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2006-12-16 18:10:04 +00:00
\end { verbatim}
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
This will hash the data pointed to by \textit { in} of length \textit { inlen} . The hash used is indexed by the \textit { hash} parameter. The message
2014-08-28 12:42:19 +00:00
digest is stored in \textit { out} , and the \textit { outlen} parameter is updated to hold the message digest size.
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
The next helper function allows for the hashing of a file based on a file name.
2006-12-16 18:10:04 +00:00
\index { hash\_ file()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hash_ file( int hash,
const char *fname,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2006-12-16 18:10:04 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will hash the file named by \textit { fname} using the hash indexed by \textit { hash} . The file named in this function call must be readable by the
2006-12-16 18:10:04 +00:00
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}
2014-08-28 12:42:19 +00:00
when it is called. The message digest is stored in \textit { out} , and the \textit { outlen} parameter is updated to hold the message digest size.
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
\index { hash\_ filehandle()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hash_ filehandle( int hash,
FILE *in,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
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}
2014-08-28 12:42:19 +00:00
when it is called. The message digest is stored in \textit { out} , and the \textit { outlen} parameter is updated to hold the message digest size.
2003-03-03 00:59:24 +00:00
To perform the above hash with md5 the following code could be used:
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int idx, err;
2003-03-03 00:59:24 +00:00
unsigned long len;
unsigned char out[MAXBLOCKSIZE];
/* register the hash */
if (register_ hash(& md5_ desc) == -1) {
printf("Error registering MD5.\n ");
return -1;
}
/* get the index of the hash */
idx = find_ hash("md5");
/* call the hash */
len = sizeof(out);
2014-08-28 12:42:19 +00:00
if ((err =
2006-11-17 14:21:24 +00:00
hash_ memory(idx, "hello world", 11, out, & len)) != CRYPT_ OK) {
2004-05-31 02:36:47 +00:00
printf("Error hashing data: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
\subsection { Hash Registration}
Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
work exactly like those of the cipher registration code. The functions are:
\index { register\_ hash()} \index { unregister\_ hash()}
\begin { verbatim}
int register_ hash(const struct _ hash_ descriptor *hash);
int unregister_ hash(const struct _ hash_ descriptor *hash);
\end { verbatim}
The following hashes are provided as of this release within the LibTomCrypt library:
2004-05-31 02:36:47 +00:00
\index { Hash descriptor table}
2006-11-17 14:21:24 +00:00
2017-09-20 12:33:04 +00:00
\begin { figure} [H]
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|c|}
2006-11-17 14:21:24 +00:00
\hline \textbf { Name} & \textbf { Descriptor Name} & \textbf { Size of Message Digest (bytes)} \\
2004-02-20 20:03:32 +00:00
\hline WHIRLPOOL & whirlpool\_ desc & 64 \\
2018-03-07 13:55:10 +00:00
\hline Keccak512 & keccak\_ 512\_ desc & 64 \\
2017-04-23 19:34:49 +00:00
\hline SHA3-512 & sha3\_ 512\_ desc & 64 \\
2003-03-03 00:59:24 +00:00
\hline SHA-512 & sha512\_ desc & 64 \\
2017-04-23 19:34:49 +00:00
\hline BLAKE2B-512 & blake2b\_ 512\_ desc & 64 \\
2018-03-07 13:55:10 +00:00
\hline Keccak384 & keccak\_ 384\_ desc & 48 \\
2017-04-23 19:34:49 +00:00
\hline SHA3-384 & sha3\_ 384\_ desc & 48 \\
2003-03-03 00:59:24 +00:00
\hline SHA-384 & sha384\_ desc & 48 \\
2006-11-17 14:21:24 +00:00
\hline RIPEMD-320 & rmd160\_ desc & 40 \\
2014-08-27 12:39:03 +00:00
\hline SHA-512/256 & sha512\_ 256\_ desc & 32 \\
2018-03-07 13:55:10 +00:00
\hline Keccak256 & keccak\_ 256\_ desc & 32 \\
2017-04-23 19:34:49 +00:00
\hline SHA3-256 & sha3\_ 256\_ desc & 32 \\
2003-03-03 00:59:24 +00:00
\hline SHA-256 & sha256\_ desc & 32 \\
2006-11-17 14:21:24 +00:00
\hline RIPEMD-256 & rmd160\_ desc & 32 \\
2017-04-23 19:34:49 +00:00
\hline BLAKE2S-256 & blake2s\_ 256\_ desc & 32 \\
\hline BLAKE2B-256 & blake2b\_ 256\_ desc & 32 \\
2014-08-27 12:39:03 +00:00
\hline SHA-512/224 & sha512\_ 224\_ desc & 28 \\
2018-03-07 13:55:10 +00:00
\hline Keccak224 & keccak\_ 224\_ desc & 28 \\
2017-04-23 19:34:49 +00:00
\hline SHA3-224 & sha3\_ 224\_ desc & 28 \\
2003-12-24 18:59:57 +00:00
\hline SHA-224 & sha224\_ desc & 28 \\
2017-04-23 19:34:49 +00:00
\hline BLAKE2S-224 & blake2s\_ 224\_ desc & 28 \\
\hline BLAKE2B-384 & blake2b\_ 384\_ desc & 48 \\
2003-03-03 00:59:24 +00:00
\hline TIGER-192 & tiger\_ desc & 24 \\
\hline SHA-1 & sha1\_ desc & 20 \\
2003-09-08 01:06:11 +00:00
\hline RIPEMD-160 & rmd160\_ desc & 20 \\
2017-04-23 19:34:49 +00:00
\hline BLAKE2S-160 & blake2s\_ 160\_ desc & 20 \\
\hline BLAKE2B-160 & blake2b\_ 160\_ desc & 20 \\
2003-09-08 01:06:11 +00:00
\hline RIPEMD-128 & rmd128\_ desc & 16 \\
2003-03-03 00:59:24 +00:00
\hline MD5 & md5\_ desc & 16 \\
\hline MD4 & md4\_ desc & 16 \\
\hline MD2 & md2\_ desc & 16 \\
2017-04-23 19:34:49 +00:00
\hline BLAKE2S-128 & blake2s\_ 128\_ desc & 16 \\
2003-03-03 00:59:24 +00:00
\hline
\end { tabular}
\end { center}
2006-11-17 14:21:24 +00:00
\caption { Built--In Software Hashes}
\end { figure}
\vfil
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Cipher Hash Construction}
2004-10-30 03:00:26 +00:00
\index { Cipher Hash Construction}
2006-11-17 14:21:24 +00:00
An addition to the suite of hash functions is the \textit { Cipher Hash Construction} or \textit { CHC} mode. In this mode
2014-08-28 12:42:19 +00:00
applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
2004-10-30 03:00:26 +00:00
particular this allows a cryptosystem to be designed using very few moving parts.
2006-11-17 14:21:24 +00:00
In order to use the CHC system the developer will have to take a few extra steps. First the \textit { chc\_ desc} hash
2004-10-30 03:00:26 +00:00
descriptor must be registered with register\_ hash(). At this point the CHC hash cannot be used to hash
data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
via the chc\_ register() function.
\index { chc\_ register()}
\begin { verbatim}
int chc_ register(int cipher);
\end { verbatim}
2014-08-28 12:42:19 +00:00
A cipher has to be registered with CHC (and also in the cipher descriptor tables with
register\_ cipher()). The chc\_ register() function will bind a cipher to the CHC system. Only one cipher can
2004-10-30 03:00:26 +00:00
be bound to the CHC hash at a time. There are additional requirements for the system to work.
\begin { enumerate}
2014-08-28 12:42:19 +00:00
\item The cipher must have a block size greater than 64--bits.
2004-10-30 03:00:26 +00:00
\item The cipher must allow an input key the size of the block size.
\end { enumerate}
Example of using CHC with the AES block cipher.
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-10-30 03:00:26 +00:00
int main(void)
{
2014-08-28 12:42:19 +00:00
int err;
2004-10-30 03:00:26 +00:00
/* register cipher and hash */
if (register_ cipher(& aes_ enc_ desc) == -1) {
printf("Could not register cipher\n ");
return EXIT_ FAILURE;
}
if (register_ hash(& chc_ desc) == -1) {
printf("Could not register hash\n ");
return EXIT_ FAILURE;
}
/* start chc with AES */
if ((err = chc_ register(find_ cipher("aes"))) != CRYPT_ OK) {
2014-08-28 12:42:19 +00:00
printf("Error binding AES to CHC: %s\n",
2006-11-17 14:21:24 +00:00
error_ to_ string(err));
2004-10-30 03:00:26 +00:00
}
2014-08-28 12:42:19 +00:00
/* now you can use chc_ hash in any LTC function
2006-11-17 14:21:24 +00:00
* [aside from pkcs...] */
}
2004-10-30 03:00:26 +00:00
\end { verbatim}
2017-08-14 09:48:05 +00:00
\mysection { SHA3 SHAKE}
The SHA3 class of algorithms provides a special XOF (Extendable Output Functions) mode, called SHAKE.
SHAKE operates in 2 security configurations, 128bit or 256bit, and allows to generate message digests of an arbitrary length.
For further information see \url { https://en.wikipedia.org/wiki/SHA-3}
Example of using SHAKE256 with an arbitrary length output.
\begin { verbatim}
#include <tomcrypt.h>
int main(void)
{
int err;
hash_ state state;
const void* msg = "The quick brown fox jumps over the lazy dog";
unsigned char output[345];
if ((err = sha3_ shake_ init(& state, 256)) != CRYPT_ OK) {
printf("Could not init SHAKE256 (%s)\n", error_to_string(err));
return EXIT_ FAILURE;
}
if ((err = sha3_ shake_ process(& state, msg, strlen(msg))) != CRYPT_ OK) {
printf("Could not process SHAKE256 (%s)\n", error_to_string(err));
return EXIT_ FAILURE;
}
if ((err = sha3_ shake_ done(& state, output, sizeof(output))) != CRYPT_ OK) {
printf("Could not finish SHAKE256 (%s)\n", error_to_string(err));
return EXIT_ FAILURE;
}
return EXIT_ SUCCESS;
}
\end { verbatim}
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Notice}
2017-04-23 19:34:49 +00:00
It is highly recommended that you \textbf { not} use the MD2, MD4, MD5, or SHA-1 hashes for the purposes of digital signatures or authentication codes.
2003-03-03 00:59:24 +00:00
These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
(e.g. Yarrow).
2014-10-10 14:43:53 +00:00
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
2003-03-03 00:59:24 +00:00
for all purposes you would normally use a hash for.
2017-07-20 21:44:30 +00:00
\chapter { Checksum Functions}
2017-08-09 13:56:13 +00:00
\mysection { Preface}
2017-07-20 21:44:30 +00:00
2017-08-09 13:56:13 +00:00
The API for all checksum functions operate in mode: \textit { init} -- \textit { update} -- \textit { update} -- ... -- \textit { finish} .
The \textit { finish} functions allow to output a partial result if necessary.
\mysection { CRC-32 -- Cyclic redundancy check}
A Cyclic Redundancy Check is an error-detecting code, where LibTomCrypt implements CRC-32 with the polynomial \textit { 0x04C11DB7} .
For further information see \url { https://en.wikipedia.org/wiki/Cyclic_ redundancy_ check}
2017-07-20 21:44:30 +00:00
\begin { verbatim}
void crc32_ init(crc32_ state *ctx);
void crc32_ update(crc32_ state *ctx, const unsigned char *input, unsigned long length);
void crc32_ finish(crc32_ state *ctx, void *hash, unsigned long size);
\end { verbatim}
2017-08-09 13:56:13 +00:00
\mysection { Adler-32}
Adler-32 is a checksum algorithm.
2017-07-20 21:44:30 +00:00
2017-08-09 13:56:13 +00:00
For further information see \url { https://en.wikipedia.org/wiki/Adler-32} .
2017-07-20 21:44:30 +00:00
\begin { verbatim}
void adler32_ init(adler32_ state *ctx);
void adler32_ update(adler32_ state *ctx, const unsigned char *input, unsigned long length);
void adler32_ finish(adler32_ state *ctx, void *hash, unsigned long size);
\end { verbatim}
2004-02-20 20:03:32 +00:00
\chapter { Message Authentication Codes}
2006-11-17 14:21:24 +00:00
\mysection { HMAC Protocol}
Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short. An HMAC
of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify. The purpose is
2003-03-03 00:59:24 +00:00
to allow an owner of a private symmetric key to produce an HMAC on a message then later verify if it is correct. Any impostor or
2014-08-28 12:42:19 +00:00
eavesdropper will not be able to verify the authenticity of a message.
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
2003-03-03 00:59:24 +00:00
and its length. The key is much like a key you would pass to a cipher. That is, it is simply an array of octets stored in
2006-11-17 14:21:24 +00:00
unsigned characters. The initialization routine is:
2004-05-31 02:36:47 +00:00
\index { hmac\_ init()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hmac_ init( hmac_ state *hmac,
int hash,
const unsigned char *key,
2006-11-17 14:21:24 +00:00
unsigned long keylen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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
2003-03-03 00:59:24 +00:00
length (in octets) of the key you want to use to authenticate the message. To send octets of a message through the HMAC system you must use the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ process()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hmac_ process( hmac_ state *hmac,
const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2007-07-20 17:48:02 +00:00
\textit { hmac} is the HMAC state you are working with. \textit { in} is the array of octets to send into the HMAC process. \textit { inlen} is the
2014-08-28 12:42:19 +00:00
number of octets to process. Like the hash process routines, you can send the data in arbitrarily sized chunks. When you
2003-03-03 00:59:24 +00:00
are finished with the HMAC process you must call the following function to get the HMAC code:
2004-05-31 02:36:47 +00:00
\index { hmac\_ done()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int hmac_ done( hmac_ state *hmac,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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.
2006-11-17 14:21:24 +00:00
You must set \textit { outlen} to the size of the destination buffer before calling this function. It is updated with the length of the HMAC code
produced (depending on which hash was picked). If \textit { outlen} is less than the size of the message digest (and ultimately
the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit { outlen} bytes).
2003-03-13 02:12:16 +00:00
2006-11-17 14:21:24 +00:00
There are two utility functions provided to make using HMACs easier to do. They accept the key and information about the
message (file pointer, address in memory), and produce the HMAC result in one shot. These are useful if you want to avoid
2003-03-13 02:12:16 +00:00
calling the three step process yourself.
2004-05-31 02:36:47 +00:00
\index { hmac\_ memory()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int hmac_ memory(
2014-08-28 12:42:19 +00:00
int hash,
2006-11-17 14:21:24 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const unsigned char *in, unsigned long inlen,
2006-11-17 14:21:24 +00:00
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will produce an HMAC code for the array of octets in \textit { in} of length \textit { inlen} . The index into the hash descriptor
table must be provided in \textit { hash} . It uses the key from \textit { key} with a key length of \textit { keylen} .
2006-11-17 14:21:24 +00:00
The result is stored in the array of octets \textit { out} and the length in \textit { outlen} . The value of \textit { outlen} must be set
2003-06-01 18:55:11 +00:00
to the size of the destination buffer before calling this function. Similarly for files there is the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ file()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int hmac_ file(
2014-08-28 12:42:19 +00:00
int hash,
const char *fname,
const unsigned char *key, unsigned long keylen,
2006-11-17 14:21:24 +00:00
unsigned char *out, unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
\textit { hash} is the index into the hash descriptor table of the hash you want to use. \textit { fname} is the filename to process.
\textit { key} is the array of octets to use as the key of length \textit { keylen} . \textit { out} is the array of octets where the
2003-03-13 02:12:16 +00:00
result should be stored.
2003-03-03 00:59:24 +00:00
To test if the HMAC code is working there is the following function:
2004-05-31 02:36:47 +00:00
\index { hmac\_ test()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int hmac_ test(void);
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code. Some example code for using the
2003-03-03 00:59:24 +00:00
HMAC system is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
2004-05-31 02:36:47 +00:00
int idx, err;
2003-03-03 00:59:24 +00:00
hmac_ state hmac;
unsigned char key[16], dst[MAXBLOCKSIZE];
2003-09-08 01:06:11 +00:00
unsigned long dstlen;
2003-03-03 00:59:24 +00:00
/* register SHA-1 */
if (register_ hash(& sha1_ desc) == -1) {
printf("Error registering SHA1\n ");
return -1;
}
/* get index of SHA1 in hash descriptor table */
idx = find_ hash("sha1");
/* we would make up our symmetric key in "key[]" here */
/* start the HMAC */
2004-05-31 02:36:47 +00:00
if ((err = hmac_ init(& hmac, idx, key, 16)) != CRYPT_ OK) {
printf("Error setting up hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* process a few octets */
2004-05-31 02:36:47 +00:00
if((err = hmac_ process(& hmac, "hello", 5) != CRYPT_ OK) {
printf("Error processing hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* get result (presumably to use it somehow...) */
2003-09-08 01:06:11 +00:00
dstlen = sizeof(dst);
2004-05-31 02:36:47 +00:00
if ((err = hmac_ done(& hmac, dst, & dstlen)) != CRYPT_ OK) {
printf("Error finishing hmac: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
2003-09-08 01:06:11 +00:00
printf("The hmac is %lu bytes long\n", dstlen);
2014-08-28 12:42:19 +00:00
2003-03-03 00:59:24 +00:00
/* return */
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
\mysection { OMAC Support}
\index { OMAC} \index { CMAC}
2014-08-28 12:42:19 +00:00
OMAC\footnote { \url { http://crypt.cis.ibaraki.ac.jp/omac/omac.html} } , which stands for \textit { One-Key CBC MAC} is an
2006-11-17 14:21:24 +00:00
algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. Note: OMAC has been standardized as
2014-08-28 12:42:19 +00:00
CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous. From an API standpoint, the OMAC routines work much like the
HMAC routines. Instead, in this case a cipher is used instead of a hash.
2003-12-24 18:59:57 +00:00
To start an OMAC state you call
2004-05-31 02:36:47 +00:00
\index { omac\_ init()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int omac_ init( omac_ state *omac,
int cipher,
const unsigned char *key,
2006-11-17 14:21:24 +00:00
unsigned long keylen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
The \textit { omac} parameter is the state for the OMAC algorithm. The \textit { cipher} parameter is the index into the cipher\_ descriptor table
2003-12-24 18:59:57 +00:00
of the cipher\footnote { The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
2006-11-17 14:21:24 +00:00
wish to use. The \textit { key} and \textit { keylen} parameters are the keys used to authenticate the data.
2003-12-24 18:59:57 +00:00
To send data through the algorithm call
2004-05-31 02:36:47 +00:00
\index { omac\_ process()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int omac_ process( omac_ state *state,
const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will send \textit { inlen} bytes from \textit { in} through the active OMAC state \textit { state} . Returns \textbf { CRYPT\_ OK} if the
2004-02-20 20:03:32 +00:00
function succeeds. The function is not sensitive to the granularity of the data. For example,
\begin { verbatim}
omac_ process(& mystate, "hello", 5);
omac_ process(& mystate, " world", 6);
\end { verbatim}
Would produce the same result as,
\begin { verbatim}
omac_ process(& mystate, "hello world", 11);
\end { verbatim}
When you are done processing the message you can call the following to compute the message tag.
2003-12-24 18:59:57 +00:00
2004-05-31 02:36:47 +00:00
\index { omac\_ done()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int omac_ done( omac_ state *state,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which will terminate the OMAC and output the \textit { tag} (MAC) to \textit { out} . Note that unlike the HMAC and other code
\textit { outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
2003-12-24 18:59:57 +00:00
specification states that the output may be truncated. So if you pass in $ outlen = 5 $ and use AES as your cipher than
2006-11-17 14:21:24 +00:00
the output MAC code will only be five bytes long. If \textit { outlen} is larger than the default size it is set to the default
2003-12-24 18:59:57 +00:00
size to show how many bytes were actually used.
2014-08-28 12:42:19 +00:00
Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
2003-12-24 18:59:57 +00:00
following function.
2004-05-31 02:36:47 +00:00
\index { omac\_ memory()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int omac_ memory(
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will compute the OMAC of \textit { inlen} bytes of \textit { in} 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
2003-12-24 18:59:57 +00:00
rules as omac\_ done.
To OMAC a file use
2004-05-31 02:36:47 +00:00
\index { omac\_ file()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2006-12-16 18:10:04 +00:00
int omac_ file(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const char *filename,
2006-12-16 18:10:04 +00:00
unsigned char *out, unsigned long *outlen);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
Which will OMAC the entire contents of the file specified by \textit { filename} using the key \textit { key} of length \textit { keylen} bytes
2014-08-28 12:42:19 +00:00
and the cipher specified by the \textit { cipher} 'th entry in the cipher\_ descriptor table. It will store the MAC in \textit { out} with
2003-12-24 18:59:57 +00:00
the same rules as omac\_ done.
To test if the OMAC code is working there is the following function:
2004-05-31 02:36:47 +00:00
\index { omac\_ test()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int omac_ test(void);
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code. Some example code for using the
2003-12-24 18:59:57 +00:00
OMAC system is given below.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-12-24 18:59:57 +00:00
int main(void)
{
2004-02-20 20:03:32 +00:00
int idx, err;
2003-12-24 18:59:57 +00:00
omac_ state omac;
unsigned char key[16], dst[MAXBLOCKSIZE];
unsigned long dstlen;
/* register Rijndael */
if (register_ cipher(& rijndael_ desc) == -1) {
printf("Error registering Rijndael\n ");
return -1;
}
/* get index of Rijndael in cipher descriptor table */
idx = find_ cipher("rijndael");
/* we would make up our symmetric key in "key[]" here */
/* start the OMAC */
2004-02-20 20:03:32 +00:00
if ((err = omac_ init(& omac, idx, key, 16)) != CRYPT_ OK) {
printf("Error setting up omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
/* process a few octets */
2004-02-20 20:03:32 +00:00
if((err = omac_ process(& omac, "hello", 5) != CRYPT_ OK) {
printf("Error processing omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
/* get result (presumably to use it somehow...) */
dstlen = sizeof(dst);
2004-02-20 20:03:32 +00:00
if ((err = omac_ done(& omac, dst, & dstlen)) != CRYPT_ OK) {
printf("Error finishing omac: %s\n", error_to_string(err));
2003-12-24 18:59:57 +00:00
return -1;
}
printf("The omac is %lu bytes long\n", dstlen);
2014-08-28 12:42:19 +00:00
2003-12-24 18:59:57 +00:00
/* return */
return 0;
}
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
\mysection { PMAC Support}
2014-08-28 12:42:19 +00:00
The PMAC\footnote { J.Black, P.Rogaway, \textit { A Block--Cipher Mode of Operation for Parallelizable Message Authentication} }
2004-02-20 20:03:32 +00:00
protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
2014-08-28 12:42:19 +00:00
API as the provided OMAC code.
2004-02-20 20:03:32 +00:00
A PMAC state is initialized with the following.
2004-05-31 02:36:47 +00:00
\index { pmac\_ init()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int pmac_ init( pmac_ state *pmac,
int cipher,
const unsigned char *key,
2006-12-16 18:10:04 +00:00
unsigned long keylen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
Which initializes the \textit { pmac} state with the given \textit { cipher} and \textit { key} of length \textit { keylen} bytes. The chosen cipher
2004-02-20 20:03:32 +00:00
must have a 64 or 128 bit block size (e.x. AES).
To MAC data simply send it through the process function.
2004-05-31 02:36:47 +00:00
\index { pmac\_ process()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int pmac_ process( pmac_ state *state,
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will process \textit { inlen} bytes of \textit { in} in the given \textit { state} . The function is not sensitive to the granularity of the
2004-02-20 20:03:32 +00:00
data. For example,
\begin { verbatim}
pmac_ process(& mystate, "hello", 5);
pmac_ process(& mystate, " world", 6);
\end { verbatim}
Would produce the same result as,
\begin { verbatim}
pmac_ process(& mystate, "hello world", 11);
\end { verbatim}
When a complete message has been processed the following function can be called to compute the message tag.
2004-05-31 02:36:47 +00:00
\index { pmac\_ done()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int pmac_ done( pmac_ state *state,
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will store up to \textit { outlen} bytes of the tag for the given \textit { state} into \textit { out} . Note that if \textit { outlen} is larger
2006-11-17 14:21:24 +00:00
than the size of the tag it is set to the amount of bytes stored in \textit { out} .
2004-02-20 20:03:32 +00:00
2014-08-28 12:42:19 +00:00
Similar to the OMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
2004-02-20 20:03:32 +00:00
following function.
2004-05-31 02:36:47 +00:00
\index { pmac\_ memory()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
2006-12-16 18:10:04 +00:00
int pmac_ memory(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will compute the PMAC of \textit { msglen} bytes of \textit { msg} using the key \textit { key} of length \textit { keylen} bytes, and the cipher
2006-11-17 14:21:24 +00:00
specified by the \textit { cipher} 'th entry in the cipher\_ descriptor table. It will store the MAC in \textit { out} with the same
2006-12-16 18:10:04 +00:00
rules as pmac\_ done().
2004-02-20 20:03:32 +00:00
To PMAC a file use
2004-05-31 02:36:47 +00:00
\index { pmac\_ file()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
2006-12-16 18:10:04 +00:00
int pmac_ file(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const char *filename,
2006-12-16 18:10:04 +00:00
unsigned char *out, unsigned long *outlen);
2004-02-20 20:03:32 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which will PMAC 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
2006-12-16 18:10:04 +00:00
the same rules as pmac\_ done().
2004-02-20 20:03:32 +00:00
To test if the PMAC code is working there is the following function:
2005-04-17 11:37:13 +00:00
\index { pmac\_ test()}
2004-02-20 20:03:32 +00:00
\begin { verbatim}
int pmac_ test(void);
\end { verbatim}
Which returns { \bf CRYPT\_ OK} if the code passes otherwise it returns an error code.
2006-11-17 14:21:24 +00:00
\mysection { Pelican MAC}
2014-08-28 12:42:19 +00:00
Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit { mixing function} . It achieves a very high
2005-04-17 11:37:13 +00:00
rate of processing and is potentially very secure. It requires AES to be enabled to function. You do not have to register\_ cipher() AES first though
as it calls AES directly.
\index { pelican\_ init()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int pelican_ init( pelican_ state *pelmac,
const unsigned char *key,
2006-11-17 14:21:24 +00:00
unsigned long keylen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
\index { pelican\_ process()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int pelican_ process( pelican_ state *pelmac,
const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen);
2005-04-17 11:37:13 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will process \textit { inlen} bytes of \textit { in} through the Pelican MAC. It's best that you pass in multiples of 16 bytes as it makes the
2005-04-17 11:37:13 +00:00
routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
an entire message.
\index { pelican\_ done()}
\begin { verbatim}
int pelican_ done(pelican_ state *pelmac, unsigned char *out);
\end { verbatim}
2006-11-17 14:21:24 +00:00
This terminates a Pelican MAC and writes the 16--octet tag to \textit { out} .
2005-04-17 11:37:13 +00:00
\subsection { Example}
\begin { verbatim}
#include <tomcrypt.h>
int main(void)
{
pelican_ state pelstate;
unsigned char key[32], tag[16];
int err;
/* somehow initialize a key */
/* initialize pelican mac */
2006-11-17 14:21:24 +00:00
if ((err = pelican_ init(& pelstate, /* the state */
key, /* user key */
32 /* key length in octets */
2005-04-17 11:37:13 +00:00
)) != CRYPT_ OK) {
2014-08-28 12:42:19 +00:00
printf("Error initializing Pelican: %s",
2006-11-17 14:21:24 +00:00
error_ to_ string(err));
2005-04-17 11:37:13 +00:00
return EXIT_ FAILURE;
}
/* MAC some data */
if ((err = pelican_ process(& pelstate, /* the state */
2014-08-28 12:42:19 +00:00
"hello world", /* data to mac */
2005-04-17 11:37:13 +00:00
11 /* length of data */
)) != CRYPT_ OK) {
2014-08-28 12:42:19 +00:00
printf("Error processing Pelican: %s",
2006-11-17 14:21:24 +00:00
error_ to_ string(err));
2005-04-17 11:37:13 +00:00
return EXIT_ FAILURE;
}
/* Terminate the MAC */
2006-11-17 14:21:24 +00:00
if ((err = pelican_ done(& pelstate,/* the state */
tag /* where to store the tag */
2005-04-17 11:37:13 +00:00
)) != CRYPT_ OK) {
2014-08-28 12:42:19 +00:00
printf("Error terminating Pelican: %s",
2006-11-17 14:21:24 +00:00
error_ to_ string(err));
2005-04-17 11:37:13 +00:00
return EXIT_ FAILURE;
}
/* tag[0..15] has the MAC output now */
return EXIT_ SUCCESS;
}
\end { verbatim}
2006-12-16 18:10:04 +00:00
\mysection { XCBC-MAC}
As of LibTomCrypt v1.15, XCBC-MAC (RFC 3566) has been provided to support TLS encryption suites. Like OMAC, it computes a message authentication code
by using a cipher in CBC mode. It also uses a single key which it expands into the requisite three keys for the MAC function. A XCBC--MAC state is
initialized with the following function:
\index { xcbc\_ init()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int xcbc_ init( xcbc_ state *xcbc,
int cipher,
const unsigned char *key,
2006-12-16 18:10:04 +00:00
unsigned long keylen);
\end { verbatim}
This will initialize the XCBC--MAC state \textit { xcbc} , 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.
2007-07-20 17:48:02 +00:00
\index { LTC\_ XCBC\_ PURE}
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
2014-08-28 12:42:19 +00:00
interpretted as three keys. If the cipher has a block size of $ n $ octets, the first key is then $ keylen - 2 n $ octets and is the encryption key. The next
2007-07-20 17:48:02 +00:00
$ 2 n $ 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 \cdot 16 = 56 $ octets.
The three keys are interpretted as if they were concatenated in the \textit { key} buffer.
2006-12-16 18:10:04 +00:00
To process data through XCBC--MAC use the following function:
\index { xcbc\_ process()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int xcbc_ process( xcbc_ state *state,
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen);
\end { verbatim}
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:
\index { xcbc\_ done()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int xcbc_ done( xcbc_ state *state,
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
\end { verbatim}
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:
\index { xcbc\_ memory()}
\begin { verbatim}
int xcbc_ memory(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
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 XCBC--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 xcbc\_ done().
To xcbc a file use
\index { xcbc\_ file()}
\begin { verbatim}
int xcbc_ file(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const char *filename,
2006-12-16 18:10:04 +00:00
unsigned char *out, unsigned long *outlen);
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
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 xcbc\_ done().
To test XCBC--MAC for RFC 3566 compliance use the following function:
\index { xcbc\_ test()}
\begin { verbatim}
int xcbc_ test(void);
\end { verbatim}
2014-08-28 12:42:19 +00:00
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} .
2006-12-16 18:10:04 +00:00
\mysection { F9--MAC}
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
2014-08-28 12:42:19 +00:00
with other ciphers. For LibTomCrypt, the F9--MAC code can use any cipher.
2006-12-16 18:10:04 +00:00
\subsection { Usage Notice}
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
2014-08-28 12:42:19 +00:00
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.
2006-12-16 18:10:04 +00:00
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:
\index { f9\_ init()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int f9_ init( f9_ state *f9,
int cipher,
const unsigned char *key,
2006-12-16 18:10:04 +00:00
unsigned long keylen);
\end { verbatim}
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}
2014-08-28 12:42:19 +00:00
int f9_ process( f9_ state *state,
const unsigned char *in,
2006-12-16 18:10:04 +00:00
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}
2014-08-28 12:42:19 +00:00
int f9_ done( f9_ state *state,
unsigned char *out,
2006-12-16 18:10:04 +00:00
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
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
\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(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
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(
2014-08-28 12:42:19 +00:00
int cipher,
2006-12-16 18:10:04 +00:00
const unsigned char *key, unsigned long keylen,
2014-08-28 12:42:19 +00:00
const char *filename,
2006-12-16 18:10:04 +00:00
unsigned char *out, unsigned long *outlen);
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
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}
2014-08-28 12:42:19 +00:00
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} .
2004-02-20 20:03:32 +00:00
2017-09-19 20:38:29 +00:00
\mysection { Poly1305--MAC}
2017-07-17 22:07:47 +00:00
2017-09-19 20:38:29 +00:00
The Poly1305--MAC is a cryptographic message authentication code created by Daniel J. Bernstein.
More info at \url { https://en.wikipedia.org/wiki/Poly1305} .
2017-07-17 22:07:47 +00:00
2017-09-19 20:38:29 +00:00
A Poly1305--MAC state is initialized with the following function:
\index { poly1305\_ init()}
2017-07-17 22:07:47 +00:00
\begin { verbatim}
2017-09-19 20:38:29 +00:00
int poly1305_ init( poly1305_ state *st,
const unsigned char *key,
unsigned long keylen);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2017-09-19 20:38:29 +00:00
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().
2017-07-17 22:07:47 +00:00
2017-07-20 21:44:30 +00:00
\mysection { BLAKE2s + BLAKE2b MAC}
2017-09-19 20:53:47 +00:00
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} .
2017-07-20 21:44:30 +00:00
2017-09-19 20:53:47 +00:00
A BLAKE2s/b--MAC state is initialized with the following function:
\index { blake2smac\_ init()}
2017-07-20 21:44:30 +00:00
\begin { verbatim}
2017-09-19 20:53:47 +00:00
int blake2smac_ init(blake2smac_ state *st,
unsigned long outlen,
const unsigned char *key,
unsigned long keylen);
2017-07-20 21:44:30 +00:00
\end { verbatim}
2017-09-19 20:53:47 +00:00
\index { blake2bmac\_ init()}
\begin { verbatim}
int blake2bmac_ init(blake2smac_ state *st,
unsigned long outlen,
const unsigned char *key,
unsigned long keylen);
\end { verbatim}
This will initialize the BLAKE2s/b--MAC state \textit { st} , with the key specified in \textit { key} of length \textit { keylen} octets (up to 64).
The \textit { outlen} specifies the size of the final tag (up to 64 octets).
To process data through BLAKE2s/b--MAC use the following function:
\index { blake2smac\_ process()}
\begin { verbatim}
int blake2smac_ process( blake2smac_ state *st,
const unsigned char *in,
unsigned long inlen);
\end { verbatim}
\index { blake2bmac\_ process()}
\begin { verbatim}
int blake2bmac_ process( blake2bmac_ 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 BLAKE2s/b--MAC state pointed to by \textit { st} .
To compute the MAC tag value use the following function:
\index { blake2smac\_ done()}
\begin { verbatim}
int blake2smac_ done(blake2smac_ state *st,
unsigned char *mac,
unsigned long *maclen);
\end { verbatim}
\index { blake2bmac\_ done()}
\begin { verbatim}
int blake2bmac_ done(blake2bmac_ state *st,
unsigned char *mac,
unsigned long *maclen);
\end { verbatim}
This will retrieve the BLAKE2s/b--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 { blake2smac\_ memory()}
\begin { verbatim}
int blake2smac_ memory(const unsigned char *key,
unsigned long keylen,
const unsigned char *in,
unsigned long inlen,
unsigned char *mac,
unsigned long *maclen);
\end { verbatim}
\index { blake2bmac\_ memory()}
\begin { verbatim}
int blake2bmac_ 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 BLAKE2s/b--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 blake2smac\_ done().
To BLAKE2s/b--MAC a file use
\index { blake2smac\_ file()}
\begin { verbatim}
int blake2smac_ file( const char *fname,
const unsigned char *key,
unsigned long keylen,
unsigned char *mac,
unsigned long *maclen);
\end { verbatim}
\index { blake2bmac\_ file()}
\begin { verbatim}
int blake2bmac_ file( const char *fname,
const unsigned char *key,
unsigned long keylen,
unsigned char *mac,
unsigned long *maclen);
\end { verbatim}
Which will BLAKE2s/b--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 blake2smac\_ done().
2017-07-17 22:07:47 +00:00
2003-03-03 00:59:24 +00:00
\chapter { Pseudo-Random Number Generators}
2006-11-17 14:21:24 +00:00
\mysection { Core Functions}
2003-03-03 00:59:24 +00:00
The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
used to expand a shorter bit string into a longer bit string. PRNGs are used wherever random data is required such as Public Key (PK)
2006-11-17 14:21:24 +00:00
key generation. There is a universal structure called \textit { prng\_ state} . To initialize a PRNG call:
2004-08-06 16:42:41 +00:00
\index { PRNG start}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ start(prng_ state *prng);
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will setup the PRNG for future use and not seed it. In order for the PRNG to be cryptographically useful you must give it
2004-12-30 23:55:53 +00:00
entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
2004-08-06 16:42:41 +00:00
\index { PRNG add\_ entropy}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ add_ entropy(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
Which returns { \bf CRYPT\_ OK} if the entropy was accepted. Once you think you have enough entropy you call another
2003-03-03 00:59:24 +00:00
function to put the entropy into action.
2004-08-06 16:42:41 +00:00
\index { PRNG ready}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int XXX_ ready(prng_ state *prng);
\end { verbatim}
2006-12-16 18:10:04 +00:00
Which returns { \bf CRYPT\_ OK} if it is ready. Finally to actually read bytes call:
2004-08-06 16:42:41 +00:00
\index { PRNG read}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
unsigned long XXX_ read(unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long outlen,
prng_ state *prng);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2004-08-06 16:42:41 +00:00
Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
the following.
\index { PRNG done}
\begin { verbatim}
void XXX_ done(prng_ state *prng);
\end { verbatim}
This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
so that you can later resume the PRNG call the following.
\index { PRNG export}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ export(unsigned char *out,
unsigned long *outlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2004-08-06 16:42:41 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will write a \textit { PRNG state} to the buffer \textit { out} of length \textit { outlen} bytes. The idea of
2006-11-17 14:21:24 +00:00
the export is meant to be used as a \textit { seed file} . That is, when the program starts up there will not likely
2004-08-06 16:42:41 +00:00
be that much entropy available. To import a state to seed a PRNG call the following function.
\index { PRNG import}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int XXX_ import(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2004-08-06 16:42:41 +00:00
\end { verbatim}
This will call the start and add\_ entropy functions of the given PRNG. It will use the state in
2006-11-17 14:21:24 +00:00
\textit { in} of length \textit { inlen} as the initial seed. You must pass the same seed length as was exported
2004-08-06 16:42:41 +00:00
by the corresponding export function.
2006-11-17 14:21:24 +00:00
Note that importing a state will not \textit { resume} the PRNG from where it left off. That is, if you export
2014-08-28 12:42:19 +00:00
a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
2004-08-06 16:42:41 +00:00
specifically equal the 8 bytes you generated previously.
2006-12-16 18:10:04 +00:00
When a program is first executed the normal course of operation is:
2004-08-06 16:42:41 +00:00
\begin { enumerate}
\item Gather entropy from your sources for a given period of time or number of events.
\item Start, use your entropy via add\_ entropy and ready the PRNG yourself.
\end { enumerate}
When your program is finished you simply call the export function and save the state to a medium (disk,
2014-08-28 12:42:19 +00:00
flash memory, etc). The next time your application starts up you can detect the state, feed it to the
2006-12-16 18:10:04 +00:00
import function and go on your way. It is ideal that (as soon as possible) after start up you export a
2004-08-06 16:42:41 +00:00
fresh state. This helps in the case that the program aborts or the machine is powered down without
2014-08-28 12:42:19 +00:00
being given a chance to exit properly.
2004-08-06 16:42:41 +00:00
Note that even if you have a state to import it is important to add new entropy to the state. However,
2014-08-28 12:42:19 +00:00
there is less pressure to do so.
2004-08-06 16:42:41 +00:00
To test a PRNG for operational conformity call the following functions.
\index { PRNG test}
\begin { verbatim}
int XXX_ test(void);
\end { verbatim}
This will return \textbf { CRYPT\_ OK} if PRNG is operating properly.
2003-03-03 00:59:24 +00:00
\subsection { Remarks}
It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
and call ready() you can now read from it. You can also keep adding new entropy to it. The new entropy will not be used
2014-08-28 12:42:19 +00:00
in the PRNG until ready() is called again. This allows the PRNG to be used and re-seeded at the same time. No real error
2006-12-16 18:10:04 +00:00
checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
2003-03-03 00:59:24 +00:00
\subsection { Example}
2014-08-28 12:42:19 +00:00
Below is a simple snippet to read 10 bytes from Yarrow. It is important to note that this snippet is { \bf NOT} secure since
2006-12-16 18:10:04 +00:00
the entropy added is not random.
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
prng_ state prng;
unsigned char buf[10];
2004-02-20 20:03:32 +00:00
int err;
2014-08-28 12:42:19 +00:00
2003-03-03 00:59:24 +00:00
/* start it */
2004-02-20 20:03:32 +00:00
if ((err = yarrow_ start(& prng)) != CRYPT_ OK) {
printf("Start error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
/* add entropy */
2014-08-28 12:42:19 +00:00
if ((err = yarrow_ add_ entropy("hello world", 11, & prng))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2004-02-20 20:03:32 +00:00
printf("Add_ entropy error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
/* ready and read */
2004-02-20 20:03:32 +00:00
if ((err = yarrow_ ready(& prng)) != CRYPT_ OK) {
printf("Ready error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
}
2014-08-28 12:42:19 +00:00
printf("Read %lu bytes from yarrow\n",
2006-12-16 18:10:04 +00:00
yarrow_ read(buf, sizeof(buf), & prng));
2003-03-03 00:59:24 +00:00
return 0;
}
\end { verbatim}
2006-11-17 14:21:24 +00:00
\mysection { PRNG Descriptors}
2003-03-03 00:59:24 +00:00
\index { PRNG Descriptor}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
format of an element is:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
struct _ prng_ descriptor {
char *name;
2004-08-06 16:42:41 +00:00
int export_ size; /* size in bytes of exported state */
2006-11-17 14:21:24 +00:00
2003-03-03 00:59:24 +00:00
int (*start) (prng_ state *);
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
int (*add_ entropy)(const unsigned char *, unsigned long,
2006-11-17 14:21:24 +00:00
prng_ state *);
2003-03-03 00:59:24 +00:00
int (*ready) (prng_ state *);
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
unsigned long (*read)(unsigned char *, unsigned long len,
2006-11-17 14:21:24 +00:00
prng_ state *);
2004-08-06 16:42:41 +00:00
void (*done)(prng_ state *);
2006-11-17 14:21:24 +00:00
2017-06-28 17:10:45 +00:00
int (*pexport)(unsigned char *, unsigned long *, prng_ state *);
2006-11-17 14:21:24 +00:00
2017-06-28 17:10:45 +00:00
int (*pimport)(const unsigned char *, unsigned long, prng_ state *);
2006-11-17 14:21:24 +00:00
2004-08-06 16:42:41 +00:00
int (*test)(void);
2003-03-03 00:59:24 +00:00
} ;
\end { verbatim}
2006-12-16 18:10:04 +00:00
To find a PRNG in the descriptor table the following function can be used:
2005-08-01 16:36:47 +00:00
\index { find\_ prng()}
2006-12-16 18:10:04 +00:00
\begin { verbatim}
int find_ prng(const char *name);
\end { verbatim}
This will search the PRNG descriptor table for the PRNG named \textit { name} . It will return -1 if the PRNG is not found, otherwise, it returns
the index into the descriptor table.
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
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.
2006-12-16 18:10:04 +00:00
They are the following:
\index { register\_ prng()} \index { unregister\_ prng()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int register_ prng(const struct _ prng_ descriptor *prng);
int unregister_ prng(const struct _ prng_ descriptor *prng);
\end { verbatim}
2006-12-16 18:10:04 +00:00
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} .
2004-08-06 16:42:41 +00:00
\subsection { PRNGs Provided}
2017-09-20 12:33:04 +00:00
\begin { figure} [H]
2004-08-06 16:42:41 +00:00
\begin { center}
\begin { small}
\begin { tabular} { |c|c|l|}
\hline \textbf { Name} & \textbf { Descriptor} & \textbf { Usage} \\
2017-06-28 17:10:45 +00:00
\hline ChaCha20 & chacha20\_ prng\_ desc & Stream Cipher PRNG (recommended, fast) \\
\hline Fortuna & fortuna\_ desc & Fast long-term PRNG (recommended, secure) \\
\hline RC4 & rc4\_ desc & Stream Cipher PRNG \\
\hline SOBER-128 & sober128\_ desc & Stream Cipher PRNG \\
\hline sprng & sprng\_ desc & Secure PRNG using the System RNG \\
2004-08-06 16:42:41 +00:00
\hline Yarrow & yarrow\_ desc & Fast short-term PRNG \\
\hline
\end { tabular}
\end { small}
\end { center}
\caption { List of Provided PRNGs}
\end { figure}
\subsubsection { Yarrow}
2014-08-28 12:42:19 +00:00
Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
(keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.
2004-08-06 16:42:41 +00:00
2006-12-16 18:10:04 +00:00
\textit { Note:} This PRNG is still secure for most tasks but is no longer recommended. Users
2017-06-28 17:10:45 +00:00
should use Fortuna or ChaCha20 instead.
2004-08-06 16:42:41 +00:00
\subsubsection { Fortuna}
Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
usage. It is faster than the default implementation of Yarrow\footnote { Yarrow has been implemented
to work with most cipher and hash combos based on which you have chosen to build into the library.} while
2014-08-28 12:42:19 +00:00
providing more security.
2004-08-06 16:42:41 +00:00
2014-08-28 12:42:19 +00:00
Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
2006-12-16 18:10:04 +00:00
and SHA--256 hash function. Technically, Fortuna will work with any block cipher that accepts a 256--bit
key, and any hash that produces at least a 256--bit output. However, to make the implementation simpler
2004-08-06 16:42:41 +00:00
it has been fixed to those choices.
2014-08-28 12:42:19 +00:00
Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
2017-12-07 11:00:22 +00:00
added to the PRNG learn far less about the state than that of Yarrow. Without getting into too many
2004-08-06 16:42:41 +00:00
details Fortuna has the ability to recover from state determination attacks where the attacker starts
2014-08-28 12:42:19 +00:00
to learn information from the PRNGs output about the internal state. Yarrow on the other hand, cannot
2004-08-06 16:42:41 +00:00
recover from that problem until new entropy is added to the pool and put to use through the ready() function.
2017-12-07 11:00:22 +00:00
For detailed information on how the algorithm works and what you have to do to maintain the secure state
get a copy of the book\footnote { Niels Ferguson and Bruce Schneier, Practical Cryptography. ISBN 0-471-22357-3.} or
read the paper online\footnote { \url { https://www.schneier.com/academic/paperfiles/fortuna.pdf} [Accessed on 7th Dec. 2017]} .
2018-03-23 22:15:00 +00:00
Fortuna provides additional API functions to be able to implement some of the important steps proposed in the original algorithm specification.
\index { fortuna\_ add\_ random\_ event()}
\begin { verbatim}
int fortuna_ add_ random_ event( unsigned long source, unsigned long pool,
const unsigned char *in, unsigned long inlen,
prng_ state *prng);
\end { verbatim}
\textit { fortuna\_ add\_ random\_ event()} can be used as a powerful alternative to the more general \textit { add\_ entropy()} .
\index { fortuna\_ update\_ seed()}
\begin { verbatim}
int fortuna_ update_ seed(const unsigned char *in, unsigned long inlen,
prng_ state *prng);
\end { verbatim}
\textit { fortuna\_ update\_ seed()} can be used to implement the \textit { UpdateSeedFile} function from the original specification.
2004-08-06 16:42:41 +00:00
\subsubsection { RC4}
2006-12-16 18:10:04 +00:00
RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You key RC4 by
2017-06-28 17:10:45 +00:00
calling add\_ entropy(), and setup the key by calling ready().
2004-08-06 16:42:41 +00:00
2017-06-28 17:10:45 +00:00
You really should not use RC4 for cryptographical purposes, it's broken.
2004-08-06 16:42:41 +00:00
\subsubsection { SOBER-128}
2014-08-28 12:42:19 +00:00
SOBER--128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4, you key it by
calling add\_ entropy(). There is no need to call ready() for this PRNG as it does not do anything.
2004-08-06 16:42:41 +00:00
2014-08-28 12:42:19 +00:00
Note: this cipher has several oddities about how it operates. The first call to add\_ entropy() sets the cipher's key.
Every other time call to the add\_ entropy() function sets the cipher's IV variable. The IV mechanism allows you to
2006-12-16 18:10:04 +00:00
encrypt several messages with the same key, and not re--use the same key material.
2004-08-06 16:42:41 +00:00
2006-12-16 18:10:04 +00:00
Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
you pass it on the \textbf { first} call to add\_ entropy(). All buffers sent to add\_ entropy() must have a length
2004-08-06 16:42:41 +00:00
that is a multiple of four bytes.
2006-12-16 18:10:04 +00:00
Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner, you can use
2004-08-06 16:42:41 +00:00
sober128\_ read() as an encrypt (and decrypt) function.
2003-03-03 00:59:24 +00:00
2017-06-28 17:10:45 +00:00
Since SOBER--128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
2006-12-16 18:10:04 +00:00
key it from the output of Fortuna (or Yarrow), and use it to encrypt messages. It is also ideal for
2014-08-28 12:42:19 +00:00
simulations which need a high quality (and fast) stream of bytes.
2003-03-03 00:59:24 +00:00
2017-06-28 17:10:45 +00:00
\subsubsection { ChaCha20}
ChaCha20 is a fast stream cipher built on a pseudorandom function designed by Daniel J. Bernstein.
It can also double duty as a PRNG.
2017-07-20 21:44:30 +00:00
It is recommended to use 40 bytes of truly random bytes for initialization.
2017-06-28 17:10:45 +00:00
The implementation supports adding entropy via the add\_ entropy() function while already being operational.
2004-08-06 16:42:41 +00:00
\subsubsection { Example Usage}
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
prng_ state prng;
unsigned char buf[32];
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
2004-02-20 20:03:32 +00:00
if ((err = rc4_ start(& prng)) != CRYPT_ OK) {
printf("RC4 init error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
2006-12-16 18:10:04 +00:00
/* use "key" as the key */
2004-02-20 20:03:32 +00:00
if ((err = rc4_ add_ entropy("key", 3, & prng)) != CRYPT_ OK) {
printf("RC4 add entropy error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
/* setup RC4 for use */
2004-02-20 20:03:32 +00:00
if ((err = rc4_ ready(& prng)) != CRYPT_ OK) {
printf("RC4 ready error: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
exit(-1);
}
/* encrypt buffer */
strcpy(buf,"hello world");
if (rc4_ read(buf, 11, & prng) != 11) {
printf("RC4 read error\n ");
exit(-1);
}
return 0;
2014-08-28 12:42:19 +00:00
}
2003-03-03 00:59:24 +00:00
\end { verbatim}
\end { small}
2014-08-28 12:42:19 +00:00
To decrypt you have to do the exact same steps.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { The Secure RNG}
2003-03-03 00:59:24 +00:00
\index { Secure RNG}
2006-12-16 18:10:04 +00:00
An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data. They generate their random bits
2014-08-28 12:42:19 +00:00
by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
PRNG. Computers are deterministic that try hard not to stray from pre--determined paths. This makes gathering entropy needed to seed a PRNG
a hard task.
2003-03-03 00:59:24 +00:00
There is one small function that may help on certain platforms:
\index { rng\_ get\_ bytes()}
\begin { verbatim}
2006-12-16 18:10:04 +00:00
unsigned long rng_ get_ bytes(
2014-08-28 12:42:19 +00:00
unsigned char *buf,
unsigned long len,
2006-12-16 18:10:04 +00:00
void (*callback)(void));
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
any RNG source. There is a function to help setup a PRNG as well:
2003-03-03 00:59:24 +00:00
\index { rng\_ make\_ prng()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rng_ make_ prng( int bits,
int wprng,
prng_ state *prng,
2006-12-16 18:10:04 +00:00
void (*callback)(void));
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will try to initialize the prng with a state of at least \textit { bits} of entropy. The \textit { callback} parameter works much like
2006-11-17 14:21:24 +00:00
the callback in \textit { rng\_ get\_ bytes()} . It is highly recommended that you use this function to setup your PRNGs unless you have a
2006-12-16 18:10:04 +00:00
platform where the RNG does not work well. Example usage of this function is given below:
2003-03-03 00:59:24 +00:00
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
ecc_ key mykey;
prng_ state prng;
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* register yarrow */
if (register_ prng(& yarrow_ desc) == -1) {
printf("Error registering Yarrow\n ");
return -1;
}
/* setup the PRNG */
2014-08-28 12:42:19 +00:00
if ((err = rng_ make_ prng(128, find_ prng("yarrow"), & prng, NULL))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2004-02-20 20:03:32 +00:00
printf("Error setting up PRNG, %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
/* make a 192-bit ECC key */
2014-08-28 12:42:19 +00:00
if ((err = ecc_ make_ key(& prng, find_ prng("yarrow"), 24, & mykey))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2004-02-20 20:03:32 +00:00
printf("Error making key: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
\subsection { The Secure PRNG Interface}
2017-06-28 17:10:45 +00:00
\index { sprng\_ desc}
2006-12-16 18:10:04 +00:00
It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
2014-08-28 12:42:19 +00:00
as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
2006-12-16 18:10:04 +00:00
requires to be started, that is you need not call the start, add\_ entropy, or ready functions. For example, consider
2003-03-03 00:59:24 +00:00
the previous example using this PRNG.
\begin { small}
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2003-03-03 00:59:24 +00:00
int main(void)
{
ecc_ key mykey;
2004-02-20 20:03:32 +00:00
int err;
2003-03-03 00:59:24 +00:00
/* register SPRNG */
if (register_ prng(& sprng_ desc) == -1) {
printf("Error registering SPRNG\n ");
return -1;
}
/* make a 192-bit ECC key */
2014-08-28 12:42:19 +00:00
if ((err = ecc_ make_ key(NULL, find_ prng("sprng"), 24, & mykey))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2004-02-20 20:03:32 +00:00
printf("Error making key: %s\n", error_to_string(err));
2003-03-03 00:59:24 +00:00
return -1;
}
return 0;
}
\end { verbatim}
\end { small}
2004-05-12 20:42:16 +00:00
\chapter { RSA Public Key Cryptography}
2004-05-31 02:36:47 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Introduction}
2004-05-31 02:36:47 +00:00
RSA wrote the PKCS \# 1 specifications which detail RSA Public Key Cryptography. In the specifications are
2006-12-16 18:10:04 +00:00
padding algorithms for encryption and signatures. The standard includes the \textit { v1.5} and \textit { v2.1} algorithms.
2014-08-28 12:42:19 +00:00
To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.
2006-12-16 18:10:04 +00:00
\mysection { PKCS \# 1 Padding}
PKCS \# 1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function. Note: the
signature padding does \textbf { not} include the ASN.1 padding required. That is performed by the rsa\_ sign\_ hash\_ ex() function
2014-08-28 12:42:19 +00:00
documented later on in this chapter.
2006-12-16 18:10:04 +00:00
\subsection { PKCS \# 1 v1.5 Encoding}
The following function performs PKCS \# 1 v1.5 padding:
\index { pkcs\_ 1\_ v1\_ 5\_ encode()}
\begin { verbatim}
int pkcs_ 1_ v1_ 5_ encode(
2014-08-28 12:42:19 +00:00
const unsigned char *msg,
2006-12-16 18:10:04 +00:00
unsigned long msglen,
int block_ type,
unsigned long modulus_ bitlen,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
2006-12-16 18:10:04 +00:00
int prng_ idx,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
\end { verbatim}
This will encode the message pointed to by \textit { msg} of length \textit { msglen} octets. The \textit { block\_ type} parameter must be set to
2014-08-28 12:42:19 +00:00
\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
2006-12-16 18:10:04 +00:00
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:
\index { pkcs\_ 1\_ v1\_ 5\_ decode()}
\begin { verbatim}
int pkcs_ 1_ v1_ 5_ decode(
2014-08-28 12:42:19 +00:00
const unsigned char *msg,
2006-12-16 18:10:04 +00:00
unsigned long msglen,
int block_ type,
unsigned long modulus_ bitlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
int *is_ valid);
\end { verbatim}
\index { LTC\_ PKCS\_ 1\_ EME} \index { LTC\_ PKCS\_ 1\_ EMSA}
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}
2004-05-12 20:42:16 +00:00
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}
2006-12-16 18:10:04 +00:00
The following function performs PKCS \# 1 v2.1 encryption padding:
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ oaep\_ encode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
2006-12-16 18:10:04 +00:00
int pkcs_ 1_ oaep_ encode(
2014-08-28 12:42:19 +00:00
const unsigned char *msg,
2006-12-16 18:10:04 +00:00
unsigned long msglen,
2014-08-28 12:42:19 +00:00
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
unsigned long modulus_ bitlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng,
int prng_ idx,
int hash_ idx,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2004-05-12 20:42:16 +00:00
\end { alltt}
2006-11-17 14:21:24 +00:00
This accepts \textit { msg} as input of length \textit { msglen} which will be OAEP padded. The \textit { lparam} variable is an additional system specific
2004-05-12 20:42:16 +00:00
tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
2014-08-28 12:42:19 +00:00
\textit { lparam} can be set to \textbf { NULL} .
2004-05-12 20:42:16 +00:00
OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output. This is passed as the parameter
2014-08-28 12:42:19 +00:00
\textit { modulus\_ bitlen} . \textit { hash\_ idx} is the index into the hash descriptor table of the hash desired. PKCS \# 1 allows any hash to be
2004-05-12 20:42:16 +00:00
used but both the encoder and decoder must use the same hash in order for this to succeed. The size of hash output affects the maximum
2014-08-28 12:42:19 +00:00
sized input message. \textit { prng\_ idx} and \textit { prng} are the random number generator arguments required to randomize the padding process.
2006-11-17 14:21:24 +00:00
The padded message is stored in \textit { out} along with the length in \textit { outlen} .
2004-05-12 20:42:16 +00:00
2014-08-28 12:42:19 +00:00
If $ h $ is the length of the hash and $ m $ the length of the modulus (both in octets) then the maximum payload for \textit { msg} is
$ m - 2 h - 2 $ . For example, with a $ 1024 $ --bit RSA key and SHA--1 as the hash the maximum payload is $ 86 $ bytes.
2004-05-12 20:42:16 +00:00
2014-08-28 12:42:19 +00:00
Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
rsa\_ exptmod() to encrypt it.
2004-05-12 20:42:16 +00:00
\subsection { OAEP Decoding}
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ oaep\_ decode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
2006-12-16 18:10:04 +00:00
int pkcs_ 1_ oaep_ decode(
2014-08-28 12:42:19 +00:00
const unsigned char *msg,
2006-12-16 18:10:04 +00:00
unsigned long msglen,
2014-08-28 12:42:19 +00:00
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
unsigned long modulus_ bitlen,
2006-12-16 18:10:04 +00:00
int hash_ idx,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
int *res);
2004-05-12 20:42:16 +00:00
\end { alltt}
2014-08-28 12:42:19 +00:00
This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. \textit { msg} is the
2006-11-17 14:21:24 +00:00
output of pkcs\_ 1\_ oaep\_ encode() of length \textit { msglen} . \textit { lparam} is the same system variable passed to the OAEP encoder. If it does not
match what was used during encoding this function will not decode the packet. \textit { modulus\_ bitlen} is the size of the RSA modulus in bits
and must match what was used during encoding. Similarly the \textit { hash\_ idx} index into the hash descriptor table must match what was used
2004-05-12 20:42:16 +00:00
during encoding.
2014-08-28 12:42:19 +00:00
If the function succeeds it decodes the OAEP encoded message into \textit { out} of length \textit { outlen} and stores a
2006-11-17 14:21:24 +00:00
$ 1 $ in \textit { res} . If the packet is invalid it stores $ 0 $ in \textit { res} and if the function fails for another reason
2014-08-28 12:42:19 +00:00
it returns an error code.
2004-05-31 02:36:47 +00:00
2006-11-17 14:21:24 +00:00
\mysection { PKCS \# 1 Digital Signatures}
2004-05-12 20:42:16 +00:00
\subsection { PSS Encoding}
2014-08-28 12:42:19 +00:00
PSS encoding is the second half of the PKCS \# 1 standard which is padding to be applied to messages that are signed.
2004-05-12 20:42:16 +00:00
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ pss\_ encode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
2006-12-16 18:10:04 +00:00
int pkcs_ 1_ pss_ encode(
2014-08-28 12:42:19 +00:00
const unsigned char *msghash,
2006-12-16 18:10:04 +00:00
unsigned long msghashlen,
2014-08-28 12:42:19 +00:00
unsigned long saltlen,
prng_ state *prng,
int prng_ idx,
2006-12-16 18:10:04 +00:00
int hash_ idx,
unsigned long modulus_ bitlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2004-05-12 20:42:16 +00:00
\end { alltt}
2014-08-28 12:42:19 +00:00
This function assumes the message to be PSS encoded has previously been hashed. The input hash \textit { msghash} is of length
\textit { msghashlen} . PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
2006-11-17 14:21:24 +00:00
\textit { hash\_ idx} is the index into the hash descriptor table of the hash to use. \textit { prng\_ idx} and \textit { prng} are the random
2004-05-12 20:42:16 +00:00
number generator information required for the salt.
2006-11-17 14:21:24 +00:00
Similar to OAEP encoding \textit { modulus\_ bitlen} is the size of the RSA modulus (in bits). It limits the size of the salt. If $ m $ is the length
2014-08-28 12:42:19 +00:00
of the modulus $ h $ the length of the hash output (in octets) then there can be $ m - h - 2 $ bytes of salt.
2004-05-12 20:42:16 +00:00
This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_ exptmod().
\subsection { PSS Decoding}
To decode a PSS encoded signature block you have to use the following.
2004-05-31 02:36:47 +00:00
\index { pkcs\_ 1\_ pss\_ decode()}
2004-05-12 20:42:16 +00:00
\begin { alltt}
2006-12-16 18:10:04 +00:00
int pkcs_ 1_ pss_ decode(
2014-08-28 12:42:19 +00:00
const unsigned char *msghash,
2006-12-16 18:10:04 +00:00
unsigned long msghashlen,
2014-08-28 12:42:19 +00:00
const unsigned char *sig,
2006-12-16 18:10:04 +00:00
unsigned long siglen,
unsigned long saltlen,
int hash_ idx,
2014-08-28 12:42:19 +00:00
unsigned long modulus_ bitlen,
2006-12-16 18:10:04 +00:00
int *res);
2004-05-12 20:42:16 +00:00
\end { alltt}
2006-11-17 14:21:24 +00:00
This will decode the PSS encoded message in \textit { sig} of length \textit { siglen} and compare it to values in \textit { msghash} of length
2014-08-28 12:42:19 +00:00
\textit { msghashlen} . If the block is a valid PSS block and the decoded hash equals the hash supplied \textit { res} is set to non--zero. Otherwise,
2004-05-12 20:42:16 +00:00
it is set to zero. The rest of the parameters are as in the PSS encode call.
2006-11-17 14:21:24 +00:00
It's important to use the same \textit { saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
2004-05-12 20:42:16 +00:00
2006-12-16 18:10:04 +00:00
\mysection { RSA Key Operations}
2004-05-31 02:36:47 +00:00
\subsection { Background}
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
RSA is a public key algorithm that is based on the inability to find the \textit { e-th} root modulo a composite of unknown
2003-03-03 00:59:24 +00:00
factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
not strictly equivalent.
2006-11-17 14:21:24 +00:00
The system begins with with two primes $ p $ and $ q $ and their product $ N = pq $ . The order or \textit { Euler totient} of the
2014-08-28 12:42:19 +00:00
multiplicative sub-group formed modulo $ N $ is given as $ \phi ( N ) = ( p - 1 ) ( q - 1 ) $ which can be reduced to
$ \mbox { lcm } ( p - 1 , q - 1 ) $ . The public key consists of the composite $ N $ and some integer $ e $ such that
$ \mbox { gcd } ( e, \phi ( N ) ) = 1 $ . The private key consists of the composite $ N $ and the inverse of $ e $ modulo $ \phi ( N ) $
2003-03-03 00:59:24 +00:00
often simply denoted as $ de \equiv 1 \mbox { } ( \mbox { mod } \phi ( N ) ) $ .
2014-08-28 12:42:19 +00:00
A person who wants to encrypt with your public key simply forms an integer (the plaintext) $ M $ such that
2003-03-03 00:59:24 +00:00
$ 1 < M < N - 2 $ and computes the ciphertext $ C = M ^ e \mbox { } ( \mbox { mod } N ) $ . Since finding the inverse exponent $ d $
given only $ N $ and $ e $ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
2014-08-28 12:42:19 +00:00
$ C ^ d \equiv \left ( M ^ e \right ) ^ d \equiv M ^ 1 \equiv M \mbox { } ( \mbox { mod } N ) $ . Similarly the owner of the private key
can sign a message by \textit { decrypting} it. Others can verify it by \textit { encrypting} it.
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
2003-03-03 00:59:24 +00:00
Ideally $ e $ should be larger than $ 100 $ to prevent direct analysis. For example, if $ e $ is three and you do not pad
2014-08-28 12:42:19 +00:00
the plaintext to be encrypted than it is possible that $ M ^ 3 < N $ in which case finding the cube-root would be trivial.
The most often suggested value for $ e $ is $ 65537 $ since it is large enough to make such attacks impossible and also well
2003-03-03 00:59:24 +00:00
designed for fast exponentiation (requires 16 squarings and one multiplication).
2014-08-28 12:42:19 +00:00
It is important to pad the input to RSA since it has particular mathematical structure. For instance
2003-03-03 00:59:24 +00:00
$ M _ 1 ^ dM _ 2 ^ d = ( M _ 1 M _ 2 ) ^ d $ which can be used to forge a signature. Suppose $ M _ 3 = M _ 1 M _ 2 $ is a message you want
to have a forged signature for. Simply get the signatures for $ M _ 1 $ and $ M _ 2 $ on their own and multiply the result
2014-08-28 12:42:19 +00:00
together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
the hash of documents only but also to pad the inputs with data to remove such structure.
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\subsection { RSA Key Generation}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
For RSA routines a single \textit { rsa\_ key} structure is used. To make a new RSA key call:
2003-03-03 00:59:24 +00:00
\index { rsa\_ make\_ key()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ make_ key(prng_ state *prng,
int wprng,
int size,
long e,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
Where \textit { wprng} is the index into the PRNG descriptor array. The \textit { size} parameter is the size in bytes of the RSA modulus desired.
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
least 128 bytes, and no more than 512 bytes in size (\textit { that is from 1024 to 4096 bits} ).
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
\index { rsa\_ free()}
2014-08-28 12:42:19 +00:00
Note: the \textit { rsa\_ make\_ key()} function allocates memory at run--time when you make the key. Make sure to call
\textit { rsa\_ free()} (see below) when you are finished with the key. If \textit { rsa\_ make\_ key()} fails it will automatically
2006-12-16 18:10:04 +00:00
free the memory allocated.
2003-03-03 00:59:24 +00:00
2004-10-30 03:00:26 +00:00
\index { PK\_ PRIVATE} \index { PK\_ PUBLIC}
2014-08-28 12:42:19 +00:00
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.
2006-12-16 18:10:04 +00:00
It takes the form of a RSAPublicKey (PKCS \# 1 compliant).
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\subsection { RSA Exponentiation}
2006-12-16 18:10:04 +00:00
To do raw work with the RSA function, that is without padding, use the following function:
2003-03-03 00:59:24 +00:00
\index { rsa\_ exptmod()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ exptmod(const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
unsigned long *outlen,
int which,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
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
2014-08-28 12:42:19 +00:00
in \textit { out} and the size of the result in \textit { outlen} . \textit { which} is set to { \bf PK\_ PUBLIC} to use \textit { e}
2006-11-17 14:21:24 +00:00
(i.e. for encryption/verifying) and set to { \bf PK\_ PRIVATE} to use \textit { d} as the exponent (i.e. for decrypting/signing).
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
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.
2003-12-24 18:59:57 +00:00
2014-08-30 15:19:20 +00:00
\subsection { RSA Key Size}
To fetch the key size of an RSA key, use the following function:
\index { rsa\_ get\_ size()}
\begin { verbatim}
int rsa_ get_ size(rsa_ key *key);
\end { verbatim}
This can be used to determine the modulus size of an RSA key.
2006-12-16 18:10:04 +00:00
\mysection { RSA Key Encryption}
2004-05-31 02:36:47 +00:00
Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
To facilitate encrypting short keys the following functions have been provided.
\index { rsa\_ encrypt\_ key()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2006-12-16 18:10:04 +00:00
int rsa_ encrypt_ key(
2014-08-28 12:42:19 +00:00
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
2014-08-28 12:42:19 +00:00
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
int prng_ idx,
int hash_ idx,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
\end { verbatim}
This function will OAEP pad \textit { in} of length \textit { inlen} bytes, RSA encrypt it, and store the ciphertext
in \textit { out} of length \textit { outlen} octets. The \textit { lparam} and \textit { lparamlen} are the same parameters you would pass
to \index { pkcs\_ 1\_ oaep\_ encode()} pkcs\_ 1\_ oaep\_ encode().
\subsection { Extended Encryption}
As of v1.15, the library supports both v1.5 and v2.1 PKCS \# 1 style paddings in these higher level functions. The following is the extended
encryption function:
\index { rsa\_ encrypt\_ key\_ ex()}
\begin { verbatim}
int rsa_ encrypt_ key_ ex(
2014-08-28 12:42:19 +00:00
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
2014-08-28 12:42:19 +00:00
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
int prng_ idx,
int hash_ idx,
int padding,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
\end { verbatim}
\index { LTC\_ PKCS\_ 1\_ OAEP} \index { LTC\_ PKCS\_ 1\_ V1\_ 5}
The parameters are all the same as for rsa\_ encrypt\_ key() except for the addition of the \textit { padding} parameter. It must be set to
\textbf { LTC\_ PKCS\_ 1\_ V1\_ 5} to perform v1.5 encryption, or set to \textbf { LTC\_ PKCS\_ 1\_ OAEP} to perform v2.1 encryption.
When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf { NULL} or zero (respectively).
\mysection { RSA Key Decryption}
2004-05-31 02:36:47 +00:00
\index { rsa\_ decrypt\_ key()}
2003-06-01 18:55:11 +00:00
\begin { verbatim}
2006-12-16 18:10:04 +00:00
int rsa_ decrypt_ key(
2014-08-28 12:42:19 +00:00
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
unsigned long *outlen,
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-12-16 18:10:04 +00:00
int *stat,
rsa_ key *key);
\end { verbatim}
This function will RSA decrypt \textit { in} of length \textit { inlen} then OAEP de-pad the resulting data and store it in
2006-11-17 14:21:24 +00:00
\textit { out} of length \textit { outlen} . The \textit { lparam} and \textit { lparamlen} are the same parameters you would pass
2004-05-31 02:36:47 +00:00
to pkcs\_ 1\_ oaep\_ decode().
2006-12-16 18:10:04 +00:00
If the RSA decrypted data is not a valid OAEP packet then \textit { stat} is set to $ 0 $ . Otherwise, it is set to $ 1 $ .
2004-05-31 02:36:47 +00:00
2006-12-16 18:10:04 +00:00
\subsection { Extended Decryption}
As of v1.15, the library supports both v1.5 and v2.1 PKCS \# 1 style paddings in these higher level functions. The following is the extended
decryption function:
\index { rsa\_ decrypt\_ key\_ ex()}
\begin { verbatim}
int rsa_ decrypt_ key_ ex(
2014-08-28 12:42:19 +00:00
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
2014-08-28 12:42:19 +00:00
const unsigned char *lparam,
2006-12-16 18:10:04 +00:00
unsigned long lparamlen,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-12-16 18:10:04 +00:00
int padding,
int *stat,
rsa_ key *key);
\end { verbatim}
2014-08-28 12:42:19 +00:00
Similar to the extended encryption, the new parameter \textit { padding} indicates which version of the PKCS \# 1 standard to use.
2006-12-16 18:10:04 +00:00
It must be set to \textbf { LTC\_ PKCS\_ 1\_ V1\_ 5} to perform v1.5 decryption, or set to \textbf { LTC\_ PKCS\_ 1\_ OAEP} to perform v2.1 decryption.
When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf { NULL} or zero (respectively).
\mysection { RSA Signature Generation}
2006-11-17 14:21:24 +00:00
Similar to RSA key encryption RSA is also used to \textit { digitally sign} message digests (hashes). To facilitate this
2004-05-31 02:36:47 +00:00
process the following functions have been provided.
2003-03-03 00:59:24 +00:00
2004-05-31 02:36:47 +00:00
\index { rsa\_ sign\_ hash()}
2003-03-03 01:01:40 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ sign_ hash(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen,
prng_ state *prng,
2006-11-17 14:21:24 +00:00
int prng_ idx,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-11-17 14:21:24 +00:00
unsigned long saltlen,
rsa_ key *key);
2003-03-03 01:01:40 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will PSS encode the message digest pointed to by \textit { in} of length \textit { inlen} octets. Next, the PSS encoded hash will be RSA
\textit { signed} and the output stored in the buffer pointed to by \textit { out} of length \textit { outlen} octets.
2006-12-16 18:10:04 +00:00
The \textit { hash\_ idx} parameter indicates which hash will be used to create the PSS encoding. It should be the same as the hash used to
hash the message being signed. The \textit { saltlen} parameter indicates the length of the desired salt, and should typically be small. A good
default value is between 8 and 16 octets. Strictly, it must be small than $ modulus \_ len - hLen - 2 $ where \textit { modulus\_ len} is the size of
2014-08-28 12:42:19 +00:00
the RSA modulus (in octets), and \textit { hLen} is the length of the message digest produced by the chosen hash.
2006-12-16 18:10:04 +00:00
\subsection { Extended Signatures}
As of v1.15, the library supports both v1.5 and v2.1 signatures. The extended signature generation function has the following prototype:
\index { rsa\_ sign\_ hash\_ ex()}
\begin { verbatim}
int rsa_ sign_ hash_ ex(
2014-08-28 12:42:19 +00:00
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen,
int padding,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
2006-12-16 18:10:04 +00:00
int prng_ idx,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-12-16 18:10:04 +00:00
unsigned long saltlen,
rsa_ key *key);
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will PKCS encode the message digest pointed to by \textit { in} of length \textit { inlen} octets. Next, the PKCS encoded hash will be RSA
2006-12-16 18:10:04 +00:00
\textit { signed} and the output stored in the buffer pointed to by \textit { out} of length \textit { outlen} octets. The \textit { padding} parameter
2014-08-28 12:42:19 +00:00
must be set to \textbf { LTC\_ PKCS\_ 1\_ V1\_ 5} to produce a v1.5 signature, otherwise, it must be set to \textbf { LTC\_ PKCS\_ 1\_ PSS} to produce a
2006-12-16 18:10:04 +00:00
v2.1 signature.
2003-03-03 00:59:24 +00:00
2017-07-09 11:44:33 +00:00
\index { LTC\_ PKCS\_ 1\_ V1\_ 5\_ NA1}
As of v1.18.0, the library also supports v1.5 signature generation without ASN.1 encoding the signature which can be indicated by passing
\textbf { LTC\_ PKCS\_ 1\_ V1\_ 5\_ NA1} as \textit { padding} parameter. This option has been introduced to provide compatibilty to SSL3.0 implementations
which implemented this.
2017-10-07 23:04:42 +00:00
When generating a standard v1.5 signature the \textit { prng} , and \textit { prng\_ idx} parameters are ignored.
When generating a v1.5 signature without ASN.1 decoding additionally the textit{ hash\_ idx} parameter is ignored.
2004-05-31 02:36:47 +00:00
2006-12-16 18:10:04 +00:00
\mysection { RSA Signature Verification}
2004-05-31 02:36:47 +00:00
\index { rsa\_ verify\_ hash()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ verify_ hash(const unsigned char *sig,
2006-11-17 14:21:24 +00:00
unsigned long siglen,
2014-08-28 12:42:19 +00:00
const unsigned char *msghash,
2006-11-17 14:21:24 +00:00
unsigned long msghashlen,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-11-17 14:21:24 +00:00
unsigned long saltlen,
int *stat,
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will RSA \textit { verify} the signature pointed to by \textit { sig} of length \textit { siglen} octets. Next, the RSA decoded data is PSS decoded
and the extracted hash is compared against the message digest pointed to by \textit { msghash} of length \textit { msghashlen} octets.
2004-05-31 02:36:47 +00:00
2014-08-28 12:42:19 +00:00
If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit { msghash}
2006-12-16 18:10:04 +00:00
value, \textit { res} is set to $ 0 $ . Otherwise, if the function succeeds, and signature is valid \textit { res} is set to $ 1 $ .
2004-05-31 02:36:47 +00:00
2014-08-30 15:19:20 +00:00
\subsection { RSA Signature Salt Length}
The v2.1 signature algorithm requires a salt length to be able to properly
encode resp. decode. To fetch the maximum possible salt length this function
is provided:
\index { rsa\_ sign\_ saltlen\_ get\_ max()}
\begin { verbatim}
int rsa_ sign_ saltlen_ get_ max(int hash_ idx, rsa_ key *key);
\end { verbatim}
2014-08-31 15:02:07 +00:00
As stated in the PKCS\# 1 RFC3447 "Typical salt lengths in octets are hLen
2014-08-30 15:19:20 +00:00
(the length of the output of the hash function Hash) and 0".
This function is provided to be able to use other lengths as well and to make
sure at runtime that the RSA key can handle the desired salt length.
2006-12-16 18:10:04 +00:00
\subsection { Extended Verification}
As of v1.15, the library supports both v1.5 and v2.1 signature verification. The extended signature verification function has the following prototype:
\index { rsa\_ verify\_ hash\_ ex()}
\begin { verbatim}
int rsa_ verify_ hash_ ex(
2014-08-28 12:42:19 +00:00
const unsigned char *sig,
2006-12-16 18:10:04 +00:00
unsigned long siglen,
2014-08-28 12:42:19 +00:00
const unsigned char *hash,
2006-12-16 18:10:04 +00:00
unsigned long hashlen,
int padding,
2014-08-28 12:42:19 +00:00
int hash_ idx,
2006-12-16 18:10:04 +00:00
unsigned long saltlen,
2014-08-28 12:42:19 +00:00
int *stat,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
\end { verbatim}
This will RSA \textit { verify} the signature pointed to by \textit { sig} of length \textit { siglen} octets. Next, the RSA decoded data is PKCS decoded
and the extracted hash is compared against the message digest pointed to by \textit { msghash} of length \textit { msghashlen} octets.
2014-08-28 12:42:19 +00:00
If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit { msghash}
2006-12-16 18:10:04 +00:00
value, \textit { res} is set to $ 0 $ . Otherwise, if the function succeeds, and signature is valid \textit { res} is set to $ 1 $ .
2014-08-28 12:42:19 +00:00
The \textit { padding} parameter must be set to \textbf { LTC\_ PKCS\_ 1\_ V1\_ 5} to perform a v1.5 verification. Otherwise, it must be set to
2017-07-09 11:44:33 +00:00
\textbf { LTC\_ PKCS\_ 1\_ PSS} to perform a v2.1 verification.
As of v1.18.0, the library also supports v1.5 signature verification without ASN.1 decoding the signature which can be indicated by passing
\textbf { LTC\_ PKCS\_ 1\_ V1\_ 5\_ NA1} as \textit { padding} parameter.
When performing a standard v1.5 verification the \textit { saltlen} parameter is ignored.
When performing a v1.5 verification without ASN.1 decoding additionally the \textit { hash\_ idx} parameter is ignored.
2014-08-30 13:21:40 +00:00
2006-12-16 18:10:04 +00:00
\mysection { RSA Encryption Example}
\begin { small}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-05-31 02:36:47 +00:00
int main(void)
{
int err, hash_ idx, prng_ idx, res;
unsigned long l1, l2;
unsigned char pt[16], pt2[16], out[1024];
rsa_ key key;
/* register prng/hash */
if (register_ prng(& sprng_ desc) == -1) {
printf("Error registering sprng");
return EXIT_ FAILURE;
}
2006-11-17 14:21:24 +00:00
/* register a math library (in this case TomsFastMath)
2005-08-01 16:36:47 +00:00
ltc_ mp = tfm_ desc;
2004-05-31 02:36:47 +00:00
if (register_ hash(& sha1_ desc) == -1) {
printf("Error registering sha1");
return EXIT_ FAILURE;
}
hash_ idx = find_ hash("sha1");
prng_ idx = find_ prng("sprng");
/* make an RSA-1024 key */
if ((err = rsa_ make_ key(NULL, /* PRNG state */
prng_ idx, /* PRNG idx */
1024/8, /* 1024-bit key */
65537, /* we like e=65537 */
& key) /* where to store the key */
) != CRYPT_ OK) {
printf("rsa_ make_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* fill in pt[] with a key we want to send ... */
l1 = sizeof(out);
2006-11-17 14:21:24 +00:00
if ((err = rsa_ encrypt_ key(pt, /* data we wish to encrypt */
16, /* data is 16 bytes long */
out, /* where to store ciphertext */
& l1, /* length of ciphertext */
"TestApp", /* our lparam for this program */
7, /* lparam is 7 bytes long */
NULL, /* PRNG state */
prng_ idx, /* prng idx */
hash_ idx, /* hash idx */
& key) /* our RSA key */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("rsa_ encrypt_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* now let's decrypt the encrypted key */
l2 = sizeof(pt2);
if ((err = rsa_ decrypt_ key(out, /* encrypted data */
l1, /* length of ciphertext */
pt2, /* where to put plaintext */
& l2, /* plaintext length */
"TestApp", /* lparam for this program */
7, /* lparam is 7 bytes long */
hash_ idx, /* hash idx */
& res, /* validity of data */
2014-08-28 12:42:19 +00:00
& key) /* our RSA key */
2004-05-31 02:36:47 +00:00
) != CRYPT_ OK) {
printf("rsa_ decrypt_ key %s", error_to_string(err));
return EXIT_ FAILURE;
}
/* if all went well pt == pt2, l2 == 16, res == 1 */
}
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
\end { small}
\mysection { RSA Key Format}
2014-08-28 12:42:19 +00:00
The RSA key format adopted for exporting and importing keys is the PKCS \# 1 format defined by the ASN.1 constructs known as
2014-10-09 19:39:22 +00:00
RSAPublicKey and RSAPrivateKey. Additionally, the OpenSSL key format is supported as well.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\subsection { RSA Key Export}
To export a RSA key use the following function.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\index { rsa\_ export()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ export(unsigned char *out,
unsigned long *outlen,
int type,
2006-11-17 14:21:24 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2014-10-09 19:39:22 +00:00
This will export the RSA key depending on the value of \textit { type} .
The RSAPublicKey (PKCS \# 1 type) format will be used for the public key,
indicated by \textbf { PK\_ PUBLIC} .
The RSAPrivateKey (PKCS \# 1 type) format will be used for the private key,
indicated by \textbf { PK\_ PRIVATE} .
2017-07-09 11:42:52 +00:00
As of v1.18.0 this function can also export OpenSSL-compatible formatted public RSA keys.
2014-10-09 19:39:22 +00:00
By OR'ing \textbf { PK\_ STD} and \textbf { PK\_ PUBLIC} the public key will be exported
in the SubjectPublicKeyInfo (X.509 type) format.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\subsection { RSA Key Import}
2017-07-17 11:33:37 +00:00
To import a RSA key use one of the following function.
\subsubsection { Import from standard formats}
This will import the key stored in \textit { in} of length inlen and import it to \textit { key} .
These formats are normally distributed in the PEM format, consisting of a label defining the content and base64 encoded DER-serialized data.
All the import functions expect binary DER data.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
\index { rsa\_ import()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rsa_ import(const unsigned char *in,
unsigned long inlen,
2006-11-17 14:21:24 +00:00
rsa_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2017-07-17 11:33:37 +00:00
This function can import both RSAPublicKey and RSAPrivateKey formats.
2003-03-03 00:59:24 +00:00
2005-08-01 16:36:47 +00:00
As of v1.06 this function can also import OpenSSL DER formatted public RSA keys. They are essentially encapsulated RSAPublicKeys. LibTomCrypt will
2017-07-17 11:33:37 +00:00
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}
2017-07-17 20:11:43 +00:00
This function can import RSA private keys serialized in PKCS\# 8 format.
2017-07-17 11:33:37 +00:00
2018-10-06 09:40:16 +00:00
Where \textit { key} is the RSA key structure (uninitialized), \textit { inlen} bytes of \textit { in} buffer is the DER encoded key,
and \textit { pwdlen} bytes of \textit { pwd} is optional password/secret (use \textit { pwd = NULL} for keys without password protection).
2018-10-06 11:17:44 +00:00
For password-protected files all supported encryption algorithms are listed in \ref { fig:pkcs8} .
2017-07-17 11:33:37 +00:00
\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}
2017-07-17 20:11:43 +00:00
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.
2017-07-17 11:33:37 +00:00
\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}
2017-07-17 20:11:43 +00:00
This function can import the plain RSA key factors \textit { p} and \textit { q} .
2017-07-17 11:33:37 +00:00
\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}
2017-07-17 20:11:43 +00:00
This function can import the plain RSA CRT (chinese remainder theorem) parameters \textit { dP} , \textit { dQ} and \textit { qP} .
2003-03-03 01:01:40 +00:00
2017-07-17 20:11:43 +00:00
After importing \textit { p} , \textit { q} , \textit { dP} , \textit { dQ} and \textit { qP}
2017-07-17 11:33:37 +00:00
the library can perfrom the optimized CRT calculations on private key operations.
2011-01-18 19:06:03 +00:00
\chapter { Diffie-Hellman Key Exchange}
2017-08-14 22:07:53 +00:00
\mysection { Background}
2011-01-18 19:06:03 +00:00
Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
2014-08-28 12:42:19 +00:00
of finite fields. For Diffie-Hellman a prime $ p $ is chosen and a ``base'' $ b $ such that $ b ^ x \mbox { } ( \mbox { mod } p ) $
2011-01-18 19:06:03 +00:00
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
2014-08-28 12:42:19 +00:00
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
2011-01-18 19:06:03 +00:00
a shared key $ K \equiv B _ y ^ { A _ x } \equiv A _ y ^ { B _ x } \equiv g ^ { A _ xB _ x } \mbox { } ( \mbox { mod } p ) $ .
2014-08-28 12:42:19 +00:00
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
2011-01-18 19:06:03 +00:00
$ k' \equiv g ^ k \mbox { } ( \mbox { mod } p ) $ and uses $ K \equiv k' ^ { A _ x } \mbox { } ( \mbox { mod } p ) $ as a key to encrypt
2014-08-28 12:42:19 +00:00
the message with. Typically $ K $ would be sent to a one-way hash and the message digested used as a key in a
2011-01-18 19:06:03 +00:00
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
2014-08-28 12:42:19 +00:00
modulo each prime factor of $ r $ and the results combined using the Chinese Remainder Theorem. In the cases where
2011-01-18 19:06:03 +00:00
$ 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
2014-08-28 12:42:19 +00:00
the sub-group generated is a large prime namely $ { p - 1 } \over 2 $ . Such primes are known as ``strong primes'' and the
2011-01-18 19:06:03 +00:00
smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
2017-08-14 22:07:53 +00:00
\mysection { Core Functions}
2011-01-18 19:06:03 +00:00
2014-08-28 12:42:19 +00:00
This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
2011-01-18 19:06:03 +00:00
provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
2017-07-20 21:44:30 +00:00
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:
2011-01-18 19:06:03 +00:00
\index { dh\_ make\_ key()}
\begin { verbatim}
2017-07-20 21:44:30 +00:00
int dh_ set_ pg_ groupsize(int groupsize, dh_ key *key);
int dh_ generate_ key(prng_ state *prng, int wprng, dh_ key *key);
2011-01-18 19:06:03 +00:00
\end { verbatim}
2017-07-20 21:44:30 +00:00
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
2014-08-28 12:42:19 +00:00
specifying a size not explicitly supported by the library it will round { \em up} to the next key size. If the size is
2017-07-20 21:44:30 +00:00
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
2011-01-18 19:06:03 +00:00
to meet very specific goals. The primes are strong primes which means that if $ p $ is the prime then
$ p - 1 $ is equal to $ 2 r $ 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.
2017-08-14 22:07:53 +00:00
The next two routines are for exporting/importing Diffie-Hellman keys in/from DER encoded ASN.1. This is useful for transport
2014-08-28 12:42:19 +00:00
over communication mediums.
2011-01-18 19:06:03 +00:00
\index { dh\_ export()} \index { dh\_ import()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dh_ export(unsigned char *out, unsigned long *outlen,
2011-01-18 19:06:03 +00:00
int type, dh_ key *key);
int dh_ import(const unsigned char *in, unsigned long inlen, dh_ key *key);
\end { verbatim}
2017-08-14 22:07:53 +00:00
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) }
2017-09-20 12:18:57 +00:00
Flags ::= BIT STRING {
privateKey (0) -- this BIT is '1' if it's a private key
-- or '0' if it's a public key
2017-08-14 22:07:53 +00:00
}
\end { verbatim}
2014-08-28 12:42:19 +00:00
These two functions work just like the ``rsa\_ export()'' and ``rsa\_ import()'' functions except these work with
2017-08-14 22:07:53 +00:00
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:
2011-01-18 19:06:03 +00:00
\begin { verbatim}
void dh_ free(dh_ key *key);
\end { verbatim}
2014-08-28 12:42:19 +00:00
After you have exported a copy of your public key (using { \bf PK\_ PUBLIC} as ``type'') you can now create a shared secret
2011-01-18 19:06:03 +00:00
with the other user using:
\index { dh\_ shared\_ secret()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dh_ shared_ secret(dh_ key *private_ key,
dh_ key *public_ key,
2011-01-18 19:06:03 +00:00
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:
2017-07-20 21:44:30 +00:00
\index { dh\_ get\_ groupsize()}
2011-01-18 19:06:03 +00:00
\begin { verbatim}
2017-07-20 21:44:30 +00:00
int dh_ get_ groupsize(dh_ key *key);
2011-01-18 19:06:03 +00:00
\end { verbatim}
This returns the size in bytes of the modulus chosen for that key.
2017-08-14 22:07:53 +00:00
\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}
2014-08-28 12:42:19 +00:00
Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
2011-01-18 19:06:03 +00:00
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}
2014-08-28 12:42:19 +00:00
int establish_ secure_ socket(int sock, int mode, unsigned char *key,
2011-01-18 19:06:03 +00:00
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 */
2017-07-20 21:44:30 +00:00
if ((err = dh_ set_ pg_ groupsize(128, & mykey)) != CRYPT_ OK) {
return err;
}
if ((err = dh_ generate_ key(prng, wprng, & mykey)) != CRYPT_ OK) {
2011-01-18 19:06:03 +00:00
return err;
}
2014-08-28 12:42:19 +00:00
/* export our key as public */
2011-01-18 19:06:03 +00:00
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;
2014-08-28 12:42:19 +00:00
}
2011-01-18 19:06:03 +00:00
/* 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;
}
}
2014-08-28 12:42:19 +00:00
if ((err = dh_ import(buf2, inlen, & theirkey)) != CRYPT_ OK) {
2011-01-18 19:06:03 +00:00
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;
}
2014-08-28 12:42:19 +00:00
2011-01-18 19:06:03 +00:00
/* hash it */
len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
if ((err = hash_ memory(find_ hash("md5"), buf, x, key, & len)) != CRYPT_ OK) {
res = err;
goto done;
}
/* clean up and return */
res = CRYPT_ OK;
done:
dh_ free(& theirkey);
done2:
dh_ free(& mykey);
zeromem(buf, sizeof(buf));
zeromem(buf2, sizeof(buf2));
return res;
}
\end { verbatim}
\end { small}
\subsection { Remarks on The Snippet}
2017-08-14 22:07:53 +00:00
When the above code snippet is done (assuming all went well) there will be a shared 128-bit key in the ``key'' array
2011-01-18 19:06:03 +00:00
passed to ``establish\_ secure\_ socket()''.
2003-03-03 00:59:24 +00:00
\chapter { Elliptic Curve Cryptography}
2018-05-23 07:50:48 +00:00
\mysection { Introduction}
2003-03-03 00:59:24 +00:00
2018-07-03 16:58:11 +00:00
The library provides public-key cryptography based on elliptic curves over finite fields \textit { GF(p)} .
They are all curves over the integers modulo a prime. The curves have the basic equation:
2006-12-16 18:10:04 +00:00
2003-03-03 00:59:24 +00:00
\begin { equation}
2018-05-23 07:50:48 +00:00
y^ 2 = x^ 3 + a \cdot x + b\mbox { } (\mbox { mod } p)
2003-03-03 00:59:24 +00:00
\end { equation}
2018-07-03 16:58:11 +00:00
\label { ecc-gf-p-equation}
2003-03-03 00:59:24 +00:00
2018-07-03 16:58:11 +00:00
The built--in curves range in order from $ \approx 2 ^ { 112 } $ points to $ \approx 2 ^ { 521 } $ .
2003-03-03 00:59:24 +00:00
2018-05-23 07:50:48 +00:00
The advantage of ECC is the fact that it requires smaller keys than RSA or DSA to provide equivalent level of security.
2018-07-03 16:58:11 +00:00
The cryptographic foundation of ECC is the \textit { "elliptic curve discrete logarithm problem"} (ECDLP).
2006-05-29 23:12:56 +00:00
2018-05-23 07:50:48 +00:00
The library provides a set of core ECC functions as well as functions that are designed to be the Elliptic Curve
2018-07-03 16:58:11 +00:00
analogy for deriving a shared secret between a pair of keys (also known as \textit { ECDH} ) and functions implementing the
2018-05-23 07:50:48 +00:00
analogy for digital signatures (also known as \textit { ECDSA} ).
\mysection { Supported Curves}
2018-07-03 16:58:11 +00:00
The following table \ref { fig:builtincurves} shows all built--in curves supported by the library. On top of that one can also use a custom curve
defined by own parameters (the only limitation is that the curve must be based on equation \ref { ecc-gf-p-equation} ).
2006-05-29 23:12:56 +00:00
2018-07-03 16:58:11 +00:00
\begin { table} [H]
2018-05-23 07:50:48 +00:00
\begin { center}
\begin { tabular} { |l|l|l|l|}
\hline \textbf { Curve Name} & \textbf { Alternative Names} & \textbf { OID} \\
2018-07-03 16:58:11 +00:00
\hline secp112r1 & & 1.3.132.0.6 \\
\hline secp112r2 & & 1.3.132.0.7 \\
\hline secp128r1 & & 1.3.132.0.28 \\
\hline secp128r2 & & 1.3.132.0.29 \\
\hline secp160r1 & & 1.3.132.0.8 \\
\hline secp160r2 & & 1.3.132.0.30 \\
\hline secp160k1 & & 1.3.132.0.9 \\
\hline secp192r1 & nistp192, prime192v1, P-192 & 1.2.840.10045.3.1.1 \\
\hline prime192v2 & & 1.2.840.10045.3.1.2 \\
\hline prime192v3 & & 1.2.840.10045.3.1.3 \\
\hline secp192k1 & & 1.3.132.0.31 \\
\hline secp224r1 & nistp224, P-224 & 1.3.132.0.33 \\
\hline secp224k1 & & 1.3.132.0.32 \\
\hline secp256r1 & nistp256, prime256v1, P-256 & 1.2.840.10045.3.1.7 \\
\hline secp256k1 & & 1.3.132.0.10 \\
\hline secp384r1 & nistp384, P-384 & 1.3.132.0.34 \\
\hline secp521r1 & nistp521, P-521 & 1.3.132.0.35 \\
\hline prime239v1 & & 1.2.840.10045.3.1.4 \\
\hline prime239v2 & & 1.2.840.10045.3.1.5 \\
\hline prime239v3 & & 1.2.840.10045.3.1.6 \\
\hline brainpoolP160r1 & & 1.3.36.3.3.2.8.1.1.1 \\
\hline brainpoolP192r1 & & 1.3.36.3.3.2.8.1.1.3 \\
\hline brainpoolP224r1 & & 1.3.36.3.3.2.8.1.1.5 \\
\hline brainpoolP256r1 & & 1.3.36.3.3.2.8.1.1.7 \\
\hline brainpoolP320r1 & & 1.3.36.3.3.2.8.1.1.9 \\
\hline brainpoolP384r1 & & 1.3.36.3.3.2.8.1.1.11 \\
\hline brainpoolP512r1 & & 1.3.36.3.3.2.8.1.1.13 \\
\hline brainpoolP160t1 & & 1.3.36.3.3.2.8.1.1.2 \\
\hline brainpoolP192t1 & & 1.3.36.3.3.2.8.1.1.4 \\
\hline brainpoolP224t1 & & 1.3.36.3.3.2.8.1.1.6 \\
\hline brainpoolP256t1 & & 1.3.36.3.3.2.8.1.1.8 \\
\hline brainpoolP320t1 & & 1.3.36.3.3.2.8.1.1.10 \\
\hline brainpoolP384t1 & & 1.3.36.3.3.2.8.1.1.12 \\
\hline brainpoolP512t1 & & 1.3.36.3.3.2.8.1.1.14 \\
2018-05-23 07:50:48 +00:00
\hline
\end { tabular}
\caption { Built--In Elliptic Curves over GF(p)}
2018-07-03 16:58:11 +00:00
\end { center}
2018-05-23 07:50:48 +00:00
\label { fig:builtincurves}
2018-07-03 16:58:11 +00:00
\end { table}
2018-05-23 07:50:48 +00:00
\mysection { Key Generation}
2006-05-29 23:12:56 +00:00
2018-07-03 16:58:11 +00:00
There is a key structure called \textit { ecc\_ key} which is used by all ECC functions.
To generate a new private \textit { ecc\_ key} there are basically two ways provided.
The first is via using one of the built--in curves and the second way is via using a user--supplied curve.
2006-05-29 23:12:56 +00:00
2018-05-23 07:50:48 +00:00
\subsection { Using Built--in Curves}
2006-05-29 23:12:56 +00:00
2018-07-03 16:58:11 +00:00
First a function is provided to look up curve name or OID of built--in curves:
2018-07-04 09:47:29 +00:00
\index { ecc\_ find\_ curve()}
2006-05-29 23:12:56 +00:00
\begin { verbatim}
2018-07-04 09:47:29 +00:00
int ecc_ find_ curve(const char *name_ or_ oid,
const ltc_ ecc_ curve **cu);
2006-05-29 23:12:56 +00:00
\end { verbatim}
2018-07-03 16:58:11 +00:00
The \textit { name\_ or\_ oid} argument will search by name, alternative name or OID as mentioned in Table \ref { fig:builtincurves} .
2018-05-23 07:50:48 +00:00
2018-07-04 09:54:27 +00:00
\index { ecc\_ set\_ curve()}
2018-05-23 07:50:48 +00:00
\begin { verbatim}
2018-07-04 09:54:27 +00:00
int ecc_ set_ curve(const ltc_ ecc_ curve *cu,
ecc_ key *key);
\end { verbatim}
The function \textit { ecc\_ set\_ curve} initializes the \textit { key} structure with the curve parameters passed via \textit { cu} .
\index { ecc\_ generate\_ key()}
\begin { verbatim}
int ecc_ generate_ key(prng_ state *prng,
2018-05-23 07:50:48 +00:00
int wprng,
2018-07-04 09:54:27 +00:00
ecc_ key *key);
2018-05-23 07:50:48 +00:00
\end { verbatim}
2006-05-29 23:12:56 +00:00
2018-07-04 09:54:27 +00:00
The function \textit { ecc\_ generate\_ key} does the actual key generation. The function will free any internally
allocated resources if there is an error.
2005-06-09 00:08:13 +00:00
2018-05-23 07:50:48 +00:00
Example of creating an ECC key:
2005-06-09 00:08:13 +00:00
\begin { small}
\begin { verbatim}
2018-05-23 07:50:48 +00:00
prng_ state prng;
int wprng;
ecc_ key key;
2018-07-03 16:58:11 +00:00
const ltc_ ecc_ curve* cu;
2005-06-09 00:08:13 +00:00
2018-05-23 07:50:48 +00:00
if (register_ all_ prngs() != CRYPT_ OK) return -1;
wprng = find_ prng("yarrow");
if (rng_ make_ prng(128, wprng, & prng, NULL) != CRYPT_ OK) return -1;
2018-07-04 09:47:29 +00:00
if (ecc_ find_ curve("nistp256", & cu) != CRYPT_ OK) return -1;
2018-07-04 09:54:27 +00:00
if (ecc_ set_ curve(cu, & key) != CRYPT_ OK) return -1;
if (ecc_ generate_ key(& prng, wprng, & key) != CRYPT_ OK) return -1;
2005-06-09 00:08:13 +00:00
\end { verbatim}
\end { small}
2018-05-23 07:50:48 +00:00
\subsection { Extended Key Generation}
2006-12-16 18:10:04 +00:00
2018-07-03 16:58:11 +00:00
The library uses the following structure to describe an elliptic curve.
This structure can also be used for defining a custom curve based on user--supplied parameters.
2006-12-16 18:10:04 +00:00
2018-05-23 07:50:48 +00:00
\index { ltc\_ ecc\_ curve}
2006-12-16 18:10:04 +00:00
\begin { verbatim}
/** Structure defines a NIST GF(p) curve */
typedef struct {
2018-05-23 07:50:48 +00:00
/** The prime that defines the field the curve is in (encoded in hex) */
const char *prime;
2006-12-16 18:10:04 +00:00
2018-05-23 07:50:48 +00:00
/** The fields A param (hex) */
const char *A;
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
/** The fields B param (hex) */
2018-05-23 07:50:48 +00:00
const char *B;
2006-12-16 18:10:04 +00:00
/** The order of the curve (hex) */
2018-05-23 07:50:48 +00:00
const char *order;
2014-08-28 12:42:19 +00:00
2006-12-16 18:10:04 +00:00
/** The x co-ordinate of the base point on the curve (hex) */
2018-05-23 07:50:48 +00:00
const char *Gx;
2014-08-28 12:42:19 +00:00
2006-12-16 18:10:04 +00:00
/** The y co-ordinate of the base point on the curve (hex) */
2018-05-23 07:50:48 +00:00
const char *Gy;
/** The co-factor */
unsigned long cofactor;
/** The OID */
const char *OID;
} ltc_ ecc_ curve;
2006-12-16 18:10:04 +00:00
\end { verbatim}
2018-07-03 16:58:11 +00:00
The curve must be of the form $ y ^ 2 = x ^ 3 - a \cdot x + b $ , and all of the \textit { const char*} parameters have to be encoded in hexadecimal format.
2018-05-23 07:50:48 +00:00
Advanced example of creating an ECC key:
\begin { small}
\begin { verbatim}
prng_ state prng;
int wprng;
ecc_ key key;
2018-07-04 09:47:29 +00:00
const ltc_ ecc_ curve custom_ curve = {
2018-05-23 07:50:48 +00:00
"FFFFFFFFFFFFFFFFFFFFFFFFFDE7", /* prime */
"0000000000000000000000000000", /* A */
"0000000000000000000000000003", /* B */
"0100000000000001ECEA551AD837E9", /* order */
"0000000000000000000000000001", /* Gx */
"0000000000000000000000000002", /* Gy */
1, /* cofactor */
"2.23.43.1.4.8" /* OID */
} ;
if (register_ all_ prngs() != CRYPT_ OK) return -1;
wprng = find_ prng("yarrow");
if (rng_ make_ prng(128, wprng, & prng, NULL) != CRYPT_ OK) return -1;
2018-07-04 09:47:29 +00:00
if (ecc_ set_ curve(& custom_ curve, & key) != CRYPT_ OK) return -1;
2018-05-23 07:50:48 +00:00
if (ecc_ generate_ key(& prng, wprng, & key) != CRYPT_ OK) return -1;
\end { verbatim}
\end { small}
\subsection { Legacy Key Generation}
2018-07-03 16:58:11 +00:00
To generate a new key in a way compatible with libtomcrypt 1.18 and earlier the following function is provided:
2006-12-16 18:10:04 +00:00
2003-03-03 00:59:24 +00:00
\index { ecc\_ make\_ key()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ make_ key(prng_ state *prng,
int wprng,
int keysize,
2006-12-16 18:10:04 +00:00
ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2018-05-23 07:50:48 +00:00
Where \textit { keysize} maps to the specific curve as follows:
2005-08-01 16:36:47 +00:00
2018-07-03 16:58:11 +00:00
\begin { table} [H]
2018-05-23 07:50:48 +00:00
\begin { center}
\begin { tabular} { |c|l|}
\hline \textbf { keysize} & \textbf { curve name} \\
2018-07-03 16:58:11 +00:00
\hline 14 & secp112r1 \\
\hline 16 & secp128r1 \\
\hline 20 & secp160r1 \\
\hline 24 & secp192r1, nistp192, prime192v1, P-192 \\
\hline 28 & secp224r1, nistp224, P-224 \\
\hline 32 & secp256r1, nistp256, prime256v1, P-256 \\
\hline 48 & secp384r1, nistp384, P-384 \\
\hline 66 & secp521r1, nistp521, P-521 \\
2018-05-23 07:50:48 +00:00
\hline
\end { tabular}
2018-07-03 16:58:11 +00:00
\caption { Mapping of ecc\_ make\_ key() keysizes to curves}
2018-05-23 07:50:48 +00:00
\end { center}
2018-07-03 16:58:11 +00:00
\label { fig:legacy-curve-names}
\end { table}
2006-12-16 18:10:04 +00:00
2018-07-04 09:54:27 +00:00
For backwards compatibility the function \textit { ecc\_ make\_ key\_ ex} is provided, which is just a wrapper
around \textit { ecc\_ set\_ curve} and \textit { ecc\_ generate\_ key} .
\index { ecc\_ make\_ key\_ ex()}
\begin { verbatim}
int ecc_ make_ key_ ex(prng_ state *prng,
int wprng,
ecc_ key *key,
const ltc_ ecc_ curve *cu);
\end { verbatim}
This function generates a random ECC key over the curve specified by the parameters in \textit { cu} .
2018-07-04 09:47:29 +00:00
It is also possible to use a combination of \textit { ecc\_ set\_ curve\_ by\_ size} (similar to \textit { ecc\_ set\_ curve} ) and \textit { ecc\_ generate\_ key} .
2006-12-16 18:10:04 +00:00
2018-07-04 09:47:29 +00:00
\index { ecc\_ set\_ curve\_ by\_ size}
2006-12-16 18:10:04 +00:00
\begin { verbatim}
2018-07-04 09:47:29 +00:00
int ecc_ set_ curve_ by_ size( int keysize,
ecc_ key *key);
2006-12-16 18:10:04 +00:00
\end { verbatim}
2018-07-03 16:58:11 +00:00
The \textit { keysize} maps to the specific curve according to table \ref { fig:legacy-curve-names} .
2018-05-23 07:50:48 +00:00
\subsection { Key Free}
2018-07-03 16:58:11 +00:00
To free the memory allocated by one of \textit { ecc\_ generate\_ key()} , \textit { ecc\_ make\_ key()} , \textit { ecc\_ make\_ key\_ ex()} , \textit { ecc\_ import()} ,
\textit { ecc\_ import\_ openssl()} , \textit { ecc\_ import\_ x509()} , \textit { ecc\_ import\_ pkcs8()} , \textit { ecc\_ ansi\_ x963\_ import()} ,
\textit { ecc\_ ansi\_ x963\_ import\_ ex()} , or \textit { ecc\_ set\_ key()} the following function is provided:
2006-12-16 18:10:04 +00:00
2003-03-03 00:59:24 +00:00
\index { ecc\_ free()}
\begin { verbatim}
void ecc_ free(ecc_ key *key);
\end { verbatim}
2018-05-23 07:50:48 +00:00
\subsection { Key Helper Functions}
2018-07-03 16:58:11 +00:00
To get the curve OID as a NUL--terminated string the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ get\_ oid\_ str()}
\begin { verbatim}
int ecc_ get_ oid_ str( char *out,
unsigned long *outlen,
const ecc_ key *key);
\end { verbatim}
Where \textit { key} is the key for which we want to extract its OID,
\textit { out} is where the ASCII output is placed, and the \textit { outlen}
parameter is updated to hold the output OID size (including NUL byte).
\mysection { Key Export and Import}
\subsection { Export Raw Key}
2018-07-03 16:58:11 +00:00
To export the raw value of the key (private or public) the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ get\_ key()}
\begin { verbatim}
int ecc_ get_ key(unsigned char *out,
unsigned long *outlen,
int type,
const ecc_ key *key);
\end { verbatim}
2018-07-03 16:58:11 +00:00
Where \textit { key} is the key to export, \textit { out} is where the output is placed,
2018-05-23 07:50:48 +00:00
the \textit { outlen} parameter is updated to hold the output, and the \textit { type} indicates
2018-07-03 16:58:11 +00:00
what kind of export should be done (see table \ref { fig:ecc-get-key-type} ).
2018-05-23 07:50:48 +00:00
2018-07-03 16:58:11 +00:00
\begin { table} [H]
2018-05-23 07:50:48 +00:00
\begin { center}
\begin { tabular} { |l|l|l|}
\hline \textbf { type} & \textbf { description} & \textbf { NIST-256 example} \\
\hline \textit { PK\_ PRIVATE} & export the private key & output: 32 bytes \\
\hline \textit { PK\_ PUBLIC} & export the public key (long form) & output: 65 bytes \\
\hline \textit { PK\_ PUBLIC \textbar PK\_ COMPRESSED} & export the public key (short form) & output: 33 bytes \\
\hline
\end { tabular}
2018-07-03 16:58:11 +00:00
\caption { Possible types of ecc\_ get\_ key()}
\label { fig:ecc-get-key-type}
2018-05-23 07:50:48 +00:00
\end { center}
2018-07-03 16:58:11 +00:00
\end { table}
2018-05-23 07:50:48 +00:00
Please note that the output data does not contain the information about the elliptic curve of the exported key
2018-07-03 16:58:11 +00:00
(one can just assume the size of the curve which is unambiguous). The information about the curve has to be kept
separately to be able to re-use the key after importing.
2018-05-23 07:50:48 +00:00
\subsection { Import Raw Key}
2018-07-03 16:58:11 +00:00
To import the raw value of the key (private or public) the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ set\_ key()}
\begin { verbatim}
int ecc_ set_ key(const unsigned char *in,
unsigned long inlen,
int type,
ecc_ key *key);
\end { verbatim}
Where \textit { key} is the key structure with properly initialized curve parameters (see below),
\textit { inlen} bytes of \textit { in} buffer is imported, and the \textit { type} indicates
2018-07-03 16:58:11 +00:00
the key type -- either \textit { PK\_ PUBLIC} or \textit { PK\_ PRIVATE} .
2018-05-23 07:50:48 +00:00
For the actual import you need to know the curve of the imported key and load the key like this:
\begin { small}
\begin { verbatim}
ecc_ key key;
2018-07-04 09:47:29 +00:00
const ltc_ ecc_ curve* cu;
2018-05-23 07:50:48 +00:00
2018-07-04 09:47:29 +00:00
if (ecc_ find_ curve("nistp256", & cu) != CRYPT_ OK) return -1;
if (ecc_ set_ curve(cu, & key) != CRYPT_ OK) return -1;
2018-05-23 07:50:48 +00:00
if (ecc_ set_ key(keybuf, keylen, PK_ PRIVATE, & key) != CRYPT_ OK) return -1;
\end { verbatim}
\end { small}
\subsection { Key Export -- OpenSSL compatible}
2018-07-03 16:58:11 +00:00
To export the key (private or public) in DER format compatible with OpenSSL the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ export\_ openssl()}
\begin { verbatim}
int ecc_ export_ openssl(unsigned char *out,
unsigned long *outlen,
int type,
const ecc_ key *key);
\end { verbatim}
2018-07-03 16:58:11 +00:00
Where \textit { key} is the key to export, \textit { out} is where the output is placed,
2018-05-23 07:50:48 +00:00
the \textit { outlen} parameter is updated to hold the output, and the \textit { type} indicates
2018-07-03 16:58:11 +00:00
what kind of export should be done (see table \ref { fig:ecc-export-openssl-type} ).
2018-05-23 07:50:48 +00:00
2018-07-03 16:58:11 +00:00
\begin { table} [H]
2018-05-23 07:50:48 +00:00
\begin { center}
\begin { tabular} { |l|l|l|}
\hline \textbf { type} & \textbf { note} \\
\hline \textit { PK\_ PRIVATE} & the output contains all curve constants \\
\hline \textit { PK\_ PRIVATE \textbar PK\_ CURVEOID} & the output contains only curve OID \\
\hline \textit { PK\_ PUBLIC} & all curve constants \\
\hline \textit { PK\_ PUBLIC \textbar PK\_ COMPRESSED} & all curve constants + using point compression \\
\hline \textit { PK\_ PUBLIC \textbar PK\_ CURVEOID} & only curve OID \\
\hline \textit { PK\_ PUBLIC \textbar PK\_ COMPRESSED \textbar PK\_ CURVEOID} & only curve OID + using point compression \\
\hline
\end { tabular}
2018-07-03 16:58:11 +00:00
\caption { Possible types of ecc\_ export\_ openssl()}
\label { fig:ecc-export-openssl-type}
2018-05-23 07:50:48 +00:00
\end { center}
2018-07-03 16:58:11 +00:00
\end { table}
2018-05-23 07:50:48 +00:00
\subsection { Key Import -- OpenSSL compatible}
2018-07-03 16:58:11 +00:00
To import the key (private or public) in DER format compatible with OpenSSL the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ import\_ openssl()}
\begin { verbatim}
int ecc_ import_ openssl(const unsigned char *in,
unsigned long inlen,
ecc_ key *key);
\end { verbatim}
Where \textit { key} is the ECC key structure (uninitialized), \textit { inlen} bytes of \textit { in} buffer is the DER encoded key.
\subsection { Public Key Import -- X.509 certificates}
2018-07-03 16:58:11 +00:00
To import the public key from a X.509 certificate (DER encoded) the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ import\_ x509()}
\begin { verbatim}
int ecc_ import_ x509(const unsigned char *in,
unsigned long inlen,
ecc_ key *key);
\end { verbatim}
Where \textit { key} is the ECC key structure (uninitialized), \textit { inlen} bytes of \textit { in} buffer is the DER encoded certificate.
\subsection { Private Key Import -- PKCS\# 8}
2018-07-03 16:58:11 +00:00
To import the private key (optionally password protected/encrypted) in PKCS\# 8 (DER encoded) format the following function is provided:
2018-05-23 07:50:48 +00:00
\index { ecc\_ import\_ pkcs8()}
\begin { verbatim}
int ecc_ import_ pkcs8(const unsigned char *in,
unsigned long inlen,
const void *pwd,
unsigned long pwdlen,
ecc_ key *key);
\end { verbatim}
Where \textit { key} is the ECC key structure (uninitialized), \textit { inlen} bytes of \textit { in} buffer is the DER encoded key,
and \textit { pwdlen} bytes of \textit { pwd} is optional password/secret (use \textit { pwd = NULL} for keys without password protection).
2018-10-06 11:17:44 +00:00
For password-protected files all supported encryption algorithms are listed in \ref { fig:pkcs8} .
2018-05-23 07:50:48 +00:00
\subsection { Key Export -- LTC proprietary (deprecated)}
LTC proprietary format for ECC public and private keys is defined as follows:
\begin { small}
\begin { verbatim}
ECCPublicKey ::= SEQUENCE {
flags BIT STRING(0), -- public/private flag (always zero),
keySize INTEGER, -- Curve size (in bits) divided by eight
-- and rounded down, e.g. 521 => 65
pubkey.x INTEGER, -- The X co-ordinate of the public key point
pubkey.y INTEGER, -- The Y co-ordinate of the public key point
}
ECCPrivateKey ::= SEQUENCE {
flags BIT STRING(1), -- public/private flag (always one),
keySize INTEGER, -- Curve size (in bits) divided by eight
-- and rounded down, e.g. 521 => 65
pubkey.x INTEGER, -- The X co-ordinate of the public key point
pubkey.y INTEGER, -- The Y co-ordinate of the public key point
secret.k INTEGER, -- The secret key scalar
}
\end { verbatim}
\end { small}
The first flags bit denotes whether the key is public (zero) or private (one).
2018-07-03 16:58:11 +00:00
To export an ECC key using the LibTomCrypt format the following function is provided:
2003-03-03 00:59:24 +00:00
\index { ecc\_ export()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ export(unsigned char *out,
unsigned long *outlen,
int type,
2006-11-17 14:21:24 +00:00
ecc_ key *key);
2005-08-01 16:36:47 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will export the key with the given \textit { type} (\textbf { PK\_ PUBLIC} or \textbf { PK\_ PRIVATE} ), and store it to \textit { out} .
2003-03-03 00:59:24 +00:00
2018-05-23 07:50:48 +00:00
\subsection { Key Import -- LTC proprietary (deprecated)}
2006-12-16 18:10:04 +00:00
The following function imports a LibTomCrypt format ECC key:
2005-08-01 16:36:47 +00:00
\index { ecc\_ import()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ import(const unsigned char *in,
unsigned long inlen,
2006-11-17 14:21:24 +00:00
ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
This will import the ECC key from \textit { in} , and store it in the ecc\_ key structure pointed to by \textit { key} . If the operation fails it will free
2005-08-01 16:36:47 +00:00
any allocated memory automatically.
2006-12-16 18:10:04 +00:00
The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
\index { ecc\_ import\_ ex()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ import_ ex(const unsigned char *in,
unsigned long inlen,
ecc_ key *key,
2018-05-23 07:50:48 +00:00
const ltc_ ecc_ curve *dp);
2006-12-16 18:10:04 +00:00
\end { verbatim}
This will import the key from the array pointed to by \textit { in} of length \textit { inlen} octets. The key is stored in
the ECC structure pointed to by \textit { key} . The curve is specified by the parameters pointed to by \textit { dp} . The function will free
all internally allocated memory upon error.
2018-05-23 07:50:48 +00:00
\subsection { ANSI X9.63 Export (deprecated)}
2006-12-16 18:10:04 +00:00
The following function exports an ECC public key in the ANSI X9.63 format:
\index { ecc\_ ansi\_ x963\_ export()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ ansi_ x963_ export( ecc_ key *key,
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
\end { verbatim}
The ECC key pointed to by \textit { key} is exported in public fashion to the array pointed to by \textit { out} . The ANSI X9.63 format used is from
section 4.3.6 of the standard. It does not allow for the export of private keys.
2018-05-23 07:50:48 +00:00
\subsection { ANSI X9.63 Import (deprecated)}
2006-12-16 18:10:04 +00:00
The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
\index { ecc\_ ansi\_ x963\_ import()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ ansi_ x963_ import(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
ecc_ key *key);
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
\textit { key} . The function will free any allocated memory upon error.
The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
\index { ecc\_ ansi\_ x963\_ import\_ ex()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ ansi_ x963_ import_ ex(const unsigned char *in,
unsigned long inlen,
ecc_ key *key,
2018-05-23 07:50:48 +00:00
ltc_ ecc_ curve *dp);
2006-12-16 18:10:04 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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} .
2006-12-16 18:10:04 +00:00
The imported key is stored in the ECC key pointed to by \textit { key} . The function will free any allocated memory upon error.
2003-03-03 01:01:40 +00:00
2018-05-23 07:50:48 +00:00
\mysection { Signatures (ECDSA)}
2018-07-03 16:58:11 +00:00
There are also functions to sign and verify messages. They use the ANSI X9.62 ECDSA algorithm to generate and verify signatures in the
2014-08-28 12:42:19 +00:00
ANSI X9.62 format.
2006-12-16 18:10:04 +00:00
2018-05-23 07:50:48 +00:00
\subsection { Signature Generation}
2006-12-16 18:10:04 +00:00
To sign a message digest (hash) use the following function:
2005-11-18 05:15:37 +00:00
\index { ecc\_ sign\_ hash()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ sign_ hash(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
int wprng,
2006-11-17 14:21:24 +00:00
ecc_ key *key);
2005-11-18 05:15:37 +00:00
\end { verbatim}
2003-03-03 00:59:24 +00:00
2018-07-03 16:58:11 +00:00
This function will ECDSA sign the message digest stored in the array pointed to by \textit { in} of length \textit { inlen} octets. The signature
2014-08-28 12:42:19 +00:00
will be stored in the array pointed to by \textit { out} of length \textit { outlen} octets. The function requires a properly seeded PRNG, and
2006-11-17 14:21:24 +00:00
the ECC \textit { key} provided must be a private key.
2005-11-18 05:15:37 +00:00
2017-07-17 22:07:47 +00:00
\index { ecc\_ sign\_ hash\_ rfc7518()}
\begin { verbatim}
2017-08-07 10:06:58 +00:00
int ecc_ sign_ hash_ rfc7518(const unsigned char *in,
2017-07-17 22:07:47 +00:00
unsigned long inlen,
unsigned char *out,
unsigned long *outlen,
2017-08-07 10:06:58 +00:00
prng_ state *prng,
int wprng,
2017-07-17 22:07:47 +00:00
ecc_ key *key);
\end { verbatim}
2018-07-03 16:58:11 +00:00
This function creates the same ECDSA signature as \textit { ecc\_ sign\_ hash} only the output format is different.
2017-07-17 22:07:47 +00:00
The format follows \url { https://tools.ietf.org/html/rfc7518#section-3.4} , sometimes it is also called plain signature.
2018-10-06 09:40:16 +00:00
\index { ecc\_ sign\_ hash\_ ex()}
2018-09-15 09:04:53 +00:00
\begin { verbatim}
int ecc_ sign_ hash_ ex(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen,
prng_ state *prng,
int wprng,
ecc_ signature_ type sigformat,
int *recid,
ecc_ key *key);
\end { verbatim}
This function is an extended version of the ECDSA signature in \textit { ecc\_ sign\_ hash} , but with a choice of output formats
and an optional output of the recovery ID for use with \textit { ecc\_ recover\_ key} .
2018-05-23 07:50:48 +00:00
\subsection { Signature Verification}
2005-11-18 05:15:37 +00:00
\index { ecc\_ verify\_ hash()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int ecc_ verify_ hash(const unsigned char *sig,
2006-11-17 14:21:24 +00:00
unsigned long siglen,
2014-08-28 12:42:19 +00:00
const unsigned char *hash,
unsigned long hashlen,
int *stat,
2006-11-17 14:21:24 +00:00
ecc_ key *key);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2018-07-03 16:58:11 +00:00
This function will verify the ECDSA signature in the array pointed to by \textit { sig} of length \textit { siglen} octets, against the message digest
2018-05-23 07:50:48 +00:00
pointed to by the array \textit { hash} of length \textit { hashlen} . It will store a non--zero value in \textit { stat} if the signature is valid. Note:
the function will not return an error if the signature is invalid. It will return an error, if the actual signature payload is an invalid format.
2006-12-16 18:10:04 +00:00
The ECC \textit { key} must be the public (or private) ECC key corresponding to the key that performed the signature.
2018-07-03 16:58:11 +00:00
The function \textit { ecc\_ verify\_ hash} implements signature format according to X9.62 ECDSA, and the output is compliant for GF(p) curves.
2003-03-03 01:01:40 +00:00
2017-07-17 22:07:47 +00:00
\index { ecc\_ verify\_ hash\_ rfc7518()}
\begin { verbatim}
int ecc_ verify_ hash_ rfc7518(const unsigned char *sig,
unsigned long siglen,
const unsigned char *hash,
unsigned long hashlen,
int *stat,
ecc_ key *key);
\end { verbatim}
2018-07-03 16:58:11 +00:00
This function validate the ECDSA signature as \textit { ecc\_ verify\_ hash} only the signature input format
2017-07-17 22:07:47 +00:00
follows \url { https://tools.ietf.org/html/rfc7518#section-3.4} .
2003-03-03 01:01:40 +00:00
2018-10-06 09:40:16 +00:00
\index { ecc\_ verify\_ hash\_ ex()}
2018-09-15 09:04:53 +00:00
\begin { verbatim}
int ecc_ verify_ hash_ ex(const unsigned char *sig,
unsigned long siglen,
const unsigned char *hash,
unsigned long hashlen,
ecc_ signature_ type sigformat,
int *stat,
ecc_ key *key);
\end { verbatim}
This function validates an ECDSA signature as \textit { ecc\_ verify\_ hash} but with a choice of signature formats.
2018-05-23 07:50:48 +00:00
{ \bf BEWARE:} 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
2018-07-03 16:58:11 +00:00
by the size of the hash, or the size of the key, whichever is smaller. For example, if you sign with SHA256 and a
P--192 key, you have in effect 96--bits of security. The library will not warn you if you make this mistake, so it
2018-05-23 07:50:48 +00:00
is important to check yourself before using the signatures.
2018-09-10 07:34:05 +00:00
\subsection { Public Key Recovery}
\index { ecc\_ recover\_ key()}
\begin { verbatim}
int ecc_ recover_ key(const unsigned char *sig,
unsigned long siglen,
const unsigned char *hash,
unsigned long hashlen,
int recid,
2018-09-15 09:04:53 +00:00
ecc_ signature_ type sigformat,
2018-09-10 07:34:05 +00:00
ecc_ key *key);
\end { verbatim}
This function will recover (a) public key from the ECDSA signature in the array pointed to by \textit { sig} of length \textit { siglen} octets, the message digest
pointed to by the array \textit { hash} of length \textit { hashlen} , and the recovery id \textit { recid} . It will store the recovered
2018-09-15 09:04:53 +00:00
key into \textit { key} and return CRYPT\_ OK if recovery succeeds, or an error if recovery fails.
This is for compatibility with the (v,r,s) signatures used in Ethereum, where public keys are not explicitly shared,
only the parity of the public key. For curves like secp256k1, recid will take values of 0 or 1, corresponding to the
parity of the public key's y coordinate. For curves like secp112r2, with a cofactor of 4, values 0..7 are possible,
with the low bit corresponding to the parity and the higher bits specifying the public key's x coordinate's multiple
2018-09-10 07:34:05 +00:00
of the curve's order.
2018-09-15 09:04:53 +00:00
If the signature format contains the recovery id (currently only \textit { LTC\_ ECCSIG\_ ETH27} ), \textit { recid} can be -1
which signals that the recovery id from the signature blob should be used. This means an application does not need to
extract the recovery id from such a signature in order to use this function.
The function \textit { ecc\_ recover\_ key} implements multiple signature formats, and the output is compliant for GF(p) curves.
\subsection { Signature Formats}
The following signature formats are suported:
\begin { figure} [hpbt]
\index { Signature Formats}
\begin { small}
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { sigformat} & \textbf { description} \\
\hline LTC\_ ECCSIG\_ ANSIX962 & ASN.1 encoded, ANSI X9.62 \\
\hline LTC\_ ECCSIG\_ RFC7518 & raw R, S values as defined in RFC7518 \\
\hline LTC\_ ECCSIG\_ ETH27 & raw R, S, V values (V has 27 added) \\
\hline
\end { tabular}
\end { center}
\end { small}
\caption { Signature Formats}
\label { fig:sigformat}
\end { figure}
2018-09-10 07:34:05 +00:00
2018-09-15 09:04:53 +00:00
The \textit { LTC\_ ECCSIG\_ ETH27} format is based on the Ethereum Yellow Paper, see \url { https://github.com/ethereum/yellowpaper}
(Appendix F). However, convention allows the use of v=0,1 as equivalent to v=27,28 and both are accepted by
\textit { ecc\_ recover\_ key} .
2018-09-10 07:34:05 +00:00
2018-05-23 07:50:48 +00:00
\mysection { Shared Secret (ECDH)}
To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
\index { ecc\_ shared\_ secret()}
\begin { verbatim}
int ecc_ shared_ secret( ecc_ key *private_ key,
ecc_ key *public_ key,
unsigned char *out,
unsigned long *outlen);
\end { verbatim}
The \textit { private\_ key} is typically the local private key, and \textit { public\_ key} is the key the remote party has shared.
2018-07-03 16:58:11 +00:00
Note: this function stores only the $ x $ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECDH.
2018-05-23 07:50:48 +00:00
\mysection { Encrypt and Decrypt (ECDH--based)}
2018-07-03 16:58:11 +00:00
ECDH 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
2018-05-23 07:50:48 +00:00
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:
\subsection { Encryption}
\index { ecc\_ encrypt\_ key()}
\begin { verbatim}
int ecc_ encrypt_ key(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen,
prng_ state *prng,
int wprng,
int hash,
ecc_ key *key);
\end { verbatim}
2018-07-03 16:58:11 +00:00
As the name implies this function can be used to encrypt a (symmetric) key, and is not intended for encrypting long messages directly. It will encrypt the
2018-05-23 07:50:48 +00:00
plaintext in the array pointed to by \textit { in} of length \textit { inlen} octets. It uses the public ECC key pointed to by \textit { key} , and
hash algorithm indexed by \textit { hash} to construct a shared secret which may be XOR'ed against the plaintext. The ciphertext is stored in
the output buffer pointed to by \textit { out} of length \textit { outlen} octets.
2018-07-03 16:58:11 +00:00
The data is encrypted through the public ECC \textit { key} such that only the holder of the private key can decrypt the payload.
% This sounds to me like multi-party encryption, but that's not true, isn't it?
To have multiple recipients multiple calls to this function for each public ECC key are required.
2003-03-03 01:01:00 +00:00
2018-05-23 07:50:48 +00:00
\subsection { Decryption}
\index { ecc\_ decrypt\_ key()}
\begin { verbatim}
int ecc_ decrypt_ key(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen,
ecc_ key *key);
\end { verbatim}
This function will decrypt an encrypted payload. The \textit { key} provided must be the private key corresponding to the public key
used during encryption. If the wrong key is provided the function will not specifically return an error code. It is important
to use some form of challenge response in that case (e.g. compute a MAC of a known string).
\subsection { Encryption Format}
The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
\begin { verbatim}
ECCEncrypt ::= SEQUENCE {
hashID OBJECT IDENTIFIER, -- OID of hash used
pubkey OCTET STRING , -- Encapsulated ECCPublicKey
skey OCTET STRING -- xor of plaintext and
--"hash of shared secret"
}
\end { verbatim}
2003-03-03 01:01:00 +00:00
2003-12-24 18:59:57 +00:00
\chapter { Digital Signature Algorithm}
2006-11-17 14:21:24 +00:00
\mysection { Introduction}
2014-08-28 12:42:19 +00:00
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
would require only at least 40 bytes.
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Key Format}
2005-06-09 00:08:13 +00:00
Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
now so that others can interoperate with this library.
\begin { verbatim}
DSAPublicKey ::= SEQUENCE {
2006-11-17 14:21:24 +00:00
publicFlags BIT STRING(0), -- must be 0
g INTEGER , -- base generator
-- check that g^ q mod p == 1
2005-06-09 00:08:13 +00:00
-- and that 1 < g < p - 1
2014-08-28 12:42:19 +00:00
p INTEGER , -- prime modulus
q INTEGER , -- order of sub-group
2006-11-17 14:21:24 +00:00
-- (must be prime)
2014-08-28 12:42:19 +00:00
y INTEGER , -- public key, specifically,
-- g^ x mod p,
2005-06-09 00:08:13 +00:00
-- check that y^ q mod p == 1
-- and that 1 < y < p - 1
}
DSAPrivateKey ::= SEQUENCE {
publicFlags BIT STRING(1), -- must be 1
2006-11-17 14:21:24 +00:00
g INTEGER , -- base generator
-- check that g^ q mod p == 1
2005-06-09 00:08:13 +00:00
-- and that 1 < g < p - 1
2014-08-28 12:42:19 +00:00
p INTEGER , -- prime modulus
q INTEGER , -- order of sub-group
2006-11-17 14:21:24 +00:00
-- (must be prime)
2014-08-28 12:42:19 +00:00
y INTEGER , -- public key, specifically,
-- g^ x mod p,
2005-06-09 00:08:13 +00:00
-- check that y^ q mod p == 1
-- and that 1 < y < p - 1
x INTEGER -- private key
}
\end { verbatim}
2014-08-28 12:42:19 +00:00
The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys. This makes the structure uniquely decodable,
2006-12-16 18:10:04 +00:00
and easy to work with.
2005-06-09 00:08:13 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Key Generation}
2003-12-24 18:59:57 +00:00
To make a DSA key you must call the following function
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ make_ key(prng_ state *prng,
int wprng,
int group_ size,
int modulus_ size,
2006-12-16 18:10:04 +00:00
dsa_ key *key);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
The variable \textit { prng} is an active PRNG state and \textit { wprng} the index to the descriptor. \textit { group\_ size} and
2006-11-17 14:21:24 +00:00
\textit { modulus\_ size} control the difficulty of forging a signature. Both parameters are in bytes. The larger the
2014-08-28 12:42:19 +00:00
\textit { group\_ size} the more difficult a forgery becomes upto a limit. The value of $ group \_ size $ is limited by
2003-12-24 18:59:57 +00:00
$ 15 < group \_ size < 1024 $ and $ modulus \_ size - group \_ size < 512 $ . Suggested values for the pairs are as follows.
2017-09-20 12:33:04 +00:00
\begin { figure} [H]
2003-12-24 18:59:57 +00:00
\begin { center}
\begin { tabular} { |c|c|c|}
\hline \textbf { Bits of Security} & \textbf { group\_ size} & \textbf { modulus\_ size} \\
\hline 80 & 20 & 128 \\
\hline 120 & 30 & 256 \\
\hline 140 & 35 & 384 \\
\hline 160 & 40 & 512 \\
\hline
\end { tabular}
\end { center}
2006-11-17 14:21:24 +00:00
\caption { DSA Key Sizes}
\end { figure}
2003-12-24 18:59:57 +00:00
When you are finished with a DSA key you can call the following function to free the memory used.
2004-05-31 02:36:47 +00:00
\index { dsa\_ free()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
void dsa_ free(dsa_ key *key);
\end { verbatim}
2006-11-17 14:21:24 +00:00
\mysection { Key Verification}
2003-12-24 18:59:57 +00:00
Each DSA key is composed of the following variables.
\begin { enumerate}
2014-08-28 12:42:19 +00:00
\item $ q $ a small prime of magnitude $ 256 ^ { group \_ size } $ .
2003-12-24 18:59:57 +00:00
\item $ p = qr + 1 $ a large prime of magnitude $ 256 ^ { modulus \_ size } $ where $ r $ is a random even integer.
2014-08-28 12:42:19 +00:00
\item $ g = h ^ r \mbox { ( mod } p \mbox { ) } $ a generator of order $ q $ modulo $ p $ . $ h $ can be any non-trivial random
2003-12-24 18:59:57 +00:00
value. For this library they start at $ h = 2 $ and step until $ g $ is not $ 1 $ .
2014-08-28 12:42:19 +00:00
\item $ x $ a random secret (the secret key) in the range $ 1 < x < q $
2003-12-24 18:59:57 +00:00
\item $ y = g ^ x \mbox { ( mod } p \mbox { ) } $ the public key.
\end { enumerate}
A DSA key is considered valid if it passes all of the following tests.
\begin { enumerate}
\item $ q $ must be prime.
\item $ p $ must be prime.
\item $ g $ cannot be one of $ \lbrace - 1 , 0 , 1 \rbrace $ (modulo $ p $ ).
\item $ g $ must be less than $ p $ .
\item $ ( p - 1 ) \equiv 0 \mbox { ( mod } q \mbox { ) } $ .
\item $ g ^ q \equiv 1 \mbox { ( mod } p \mbox { ) } $ .
\item $ 1 < y < p - 1 $
\item $ y ^ q \equiv 1 \mbox { ( mod } p \mbox { ) } $ .
\end { enumerate}
2014-08-28 12:42:19 +00:00
Tests one and two ensure that the values will at least form a field which is required for the signatures to
2003-12-24 18:59:57 +00:00
function. Tests three and four ensure that the generator $ g $ is not set to a trivial value which would make signature
forgery easier. Test five ensures that $ q $ divides the order of multiplicative sub-group of $ \Z / p \Z $ . Test six
ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
is within range and belongs to a group of prime order. Note that test eight does not prove that $ g $ generated $ y $ only
2014-08-28 12:42:19 +00:00
that $ y $ belongs to a multiplicative sub-group of order $ q $ .
2003-12-24 18:59:57 +00:00
The following function will perform these tests.
2004-05-31 02:36:47 +00:00
\index { dsa\_ verify\_ key()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
int dsa_ verify_ key(dsa_ key *key, int *stat);
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will test \textit { key} and store the result in \textit { stat} . If the result is $ stat = 0 $ the DSA key failed one of the tests
2003-12-24 18:59:57 +00:00
and should not be used at all. If the result is $ stat = 1 $ the DSA key is valid (as far as valid mathematics are concerned).
2006-11-17 14:21:24 +00:00
\mysection { Signatures}
2005-11-18 05:15:37 +00:00
\subsection { Signature Generation}
2006-12-16 18:10:04 +00:00
To generate a DSA signature call the following function:
2003-12-24 18:59:57 +00:00
2004-05-31 02:36:47 +00:00
\index { dsa\_ sign\_ hash()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ sign_ hash(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen,
2014-08-28 12:42:19 +00:00
prng_ state *prng,
int wprng,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
Which will sign the data in \textit { in} of length \textit { inlen} bytes. The signature is stored in \textit { out} and the size
of the signature in \textit { outlen} . If the signature is longer than the size you initially specify in \textit { outlen} nothing
is stored and the function returns an error code. The DSA \textit { key} must be of the \textbf { PK\_ PRIVATE} persuasion.
2003-12-24 18:59:57 +00:00
2005-11-18 05:15:37 +00:00
\subsection { Signature Verification}
2006-12-16 18:10:04 +00:00
To verify a hash created with that function use the following function:
2003-12-24 18:59:57 +00:00
2014-08-28 12:42:19 +00:00
\index { dsa\_ verify\_ hash()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ verify_ hash(const unsigned char *sig,
2006-11-17 14:21:24 +00:00
unsigned long siglen,
2014-08-28 12:42:19 +00:00
const unsigned char *hash,
unsigned long inlen,
int *stat,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
Which will verify the data in \textit { hash} of length \textit { inlen} against the signature stored in \textit { sig} of length \textit { siglen} .
It will set \textit { stat} to $ 1 $ if the signature is valid, otherwise it sets \textit { stat} to $ 0 $ .
2003-12-24 18:59:57 +00:00
2006-11-17 14:21:24 +00:00
\mysection { DSA Encrypt and Decrypt}
2006-12-16 18:10:04 +00:00
As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads. It works similar to the ECC encryption where
a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext. The format used is functional port of
the ECC encryption format to the DSA algorithm.
2005-11-18 05:15:37 +00:00
\subsection { DSA Encryption}
This function will encrypt a small payload with a recipients public DSA key.
\index { dsa\_ encrypt\_ key()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ encrypt_ key(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
unsigned long *outlen,
prng_ state *prng,
int wprng,
int hash,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2005-11-18 05:15:37 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will encrypt the payload in \textit { in} of length \textit { inlen} and store the ciphertext in the output buffer \textit { out} . The
2014-08-28 12:42:19 +00:00
length of the ciphertext \textit { outlen} must be originally set to the length of the output buffer. The DSA \textit { key} can be
2005-11-18 05:15:37 +00:00
a public key.
\subsection { DSA Decryption}
\index { dsa\_ decrypt\_ key()}
2014-08-28 12:42:19 +00:00
\begin { verbatim}
int dsa_ decrypt_ key(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
unsigned long *outlen,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2005-11-18 05:15:37 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will decrypt the ciphertext \textit { in} of length \textit { inlen} , and store the original payload in \textit { out} of length \textit { outlen} .
2006-12-16 18:10:04 +00:00
The DSA \textit { key} must be a private key.
2005-11-18 05:15:37 +00:00
2006-12-16 18:10:04 +00:00
\mysection { DSA Key Import and Export}
2003-12-24 18:59:57 +00:00
2006-12-16 18:10:04 +00:00
\subsection { DSA Key Export}
To export a DSA key so that it can be transported use the following function:
2004-05-31 02:36:47 +00:00
\index { dsa\_ export()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ export(unsigned char *out,
unsigned long *outlen,
int type,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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}
2003-12-24 18:59:57 +00:00
depending on whether you want to export a private or public copy of the DSA key.
2006-12-16 18:10:04 +00:00
\subsection { DSA Key Import}
2003-12-24 18:59:57 +00:00
To import an exported DSA key use the following function
2006-12-16 18:10:04 +00:00
:
2004-05-31 02:36:47 +00:00
\index { dsa\_ import()}
2003-12-24 18:59:57 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int dsa_ import(const unsigned char *in,
unsigned long inlen,
2006-11-17 14:21:24 +00:00
dsa_ key *key);
2003-12-24 18:59:57 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
will automatically free all of the heap allocated in the process (you don't have to call dsa\_ free()).
2003-12-24 18:59:57 +00:00
2017-09-20 12:15:28 +00:00
\mysection { Other DSA Functions}
2017-07-20 21:44:30 +00:00
2017-09-20 12:15:28 +00:00
The following functions allow to create a DSA key in 2 steps:
2017-07-20 21:44:30 +00:00
2017-09-20 12:15:28 +00:00
\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()}
2017-07-20 21:44:30 +00:00
\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}
2017-09-20 12:15:28 +00:00
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.
\index { dsa\_ set\_ pqg\_ dsaparam()}
\begin { verbatim}
int dsa_ set_ pqg_ dsaparam(const unsigned char *dsaparam,
unsigned long dsaparamlen,
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 DSA parameters stored as a binary data in a buffer \textit { dsaparam} (with length of \textit { dsaparamlen} ). A simple DSA key validity
check (without primality testing) is performed at the end of this function. The \textit { dsaparam} can be generated via:
\begin { verbatim}
openssl dsaparam 2048 -outform DER -out dsaparam.der
\end { verbatim}
\index { dsa\_ generate\_ pqg()}
\begin { verbatim}
int dsa_ generate_ pqg(prng_ state *prng,
int wprng,
int group_ size,
int modulus_ size,
dsa_ key *key);
\end { verbatim}
This will initialise the \textit { p} , \textit { q} and \textit { g} part of \textit { key} structure with newly generated random values.
As for the parameters they are the same as by \textit { dsa\_ make\_ key} .
\index { dsa\_ set\_ key()}
\begin { verbatim}
int dsa_ set_ key(const unsigned char *in,
unsigned long inlen,
int type,
dsa_ key *key);
\end { verbatim}
This function can be used for setting the actual DSA key. If \textit { type} is \textit { PK\_ PRIVATE} then the buffer \textit { in}
(with length of \textit { inlen} ) contains a binary representation of \textit { x} part of the key (the public part \textit { y} is computed).
If \textit { type} is \textit { PK\_ PUBLIC} then the buffer \textit { in} contains a binary representation of \textit { y} part of the key.
\index { dsa\_ generate\_ key()}
\begin { verbatim}
int dsa_ generate_ key(prng_ state *prng,
int wprng,
dsa_ key *key);
\end { verbatim}
This function generates a private DSA key containing both \textit { x} and \textit { y} parts.
2017-07-20 21:44:30 +00:00
2004-10-30 03:00:26 +00:00
\chapter { Standards Support}
2006-11-17 14:21:24 +00:00
\mysection { ASN.1 Formats}
2005-06-09 00:08:13 +00:00
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
2014-08-28 12:42:19 +00:00
format, and two functions have been dedicated to encoding and decoding the format.
2004-10-30 03:00:26 +00:00
2014-08-28 12:42:19 +00:00
On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types. They are provided
2006-12-16 18:10:04 +00:00
in the same manner as the other data types except they use list of objects known as the \textbf { ltc\_ asn1\_ list} structure. It is defined as the following:
2004-10-30 03:00:26 +00:00
2005-06-09 00:08:13 +00:00
\index { ltc\_ asn1\_ list structure}
\begin { verbatim}
typedef struct {
2017-11-28 09:49:12 +00:00
ltc_ asn1_ type type;
2005-11-18 05:15:37 +00:00
void *data;
unsigned long size;
int used;
2018-01-21 12:19:37 +00:00
int optional;
2018-03-09 15:37:18 +00:00
ltc_ asn1_ class klass;
2018-01-21 12:19:37 +00:00
ltc_ asn1_ pc pc;
ulong64 tag;
2014-08-28 12:42:19 +00:00
struct ltc_ asn1_ list_ *prev, *next,
2005-11-18 05:15:37 +00:00
*child, *parent;
2005-06-09 00:08:13 +00:00
} ltc_ asn1_ list;
\end { verbatim}
2004-10-30 03:00:26 +00:00
2005-11-18 05:15:37 +00:00
\index { LTC\_ SET\_ ASN1 macro}
2014-08-28 12:42:19 +00:00
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
2006-11-17 14:21:24 +00:00
\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
2005-06-27 11:47:35 +00:00
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
2006-11-17 14:21:24 +00:00
\textit { LTC\_ SET\_ ASN1(list, index, Type, Data, Size)} has been provided.
2005-06-09 00:08:13 +00:00
2006-11-17 14:21:24 +00:00
It will assign to the \textit { index} th position in the \textit { list} the triplet (Type, Data, Size). An example usage would be:
2005-06-09 00:08:13 +00:00
\begin { small}
\begin { verbatim}
...
ltc_ asn1_ list sequence[3];
unsigned long three=3;
LTC_ SET_ ASN1(sequence, 0, LTC_ ASN1_ IA5_ STRING, "hello", 5);
LTC_ SET_ ASN1(sequence, 1, LTC_ ASN1_ SHORT_ INTEGER, & three, 1);
LTC_ SET_ ASN1(sequence, 2, LTC_ ASN1_ NULL, NULL, 0);
\end { verbatim}
\end { small}
The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
\begin { small}
\begin { verbatim}
...
ltc_ asn1_ list sequence[3];
unsigned long three=3;
int x=0;
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ IA5_ STRING, "hello", 5);
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ SHORT_ INTEGER, & three, 1);
LTC_ SET_ ASN1(sequence, x++, LTC_ ASN1_ NULL, NULL, 0);
\end { verbatim}
\end { small}
2015-06-28 18:35:13 +00:00
\begin { figure} [h]
2005-06-09 00:08:13 +00:00
\begin { center}
\begin { small}
\begin { tabular} { |l|l|}
\hline \textbf { Definition} & \textbf { ASN.1 Type} \\
\hline LTC\_ ASN1\_ EOL & End of a ASN.1 list structure. \\
2006-05-29 23:12:56 +00:00
\hline LTC\_ ASN1\_ BOOLEAN & BOOLEAN type \\
2005-06-09 00:08:13 +00:00
\hline LTC\_ ASN1\_ INTEGER & INTEGER (uses mp\_ int) \\
\hline LTC\_ ASN1\_ SHORT\_ INTEGER & INTEGER (32--bit using unsigned long) \\
\hline LTC\_ ASN1\_ BIT\_ STRING & BIT STRING (one bit per char) \\
\hline LTC\_ ASN1\_ OCTET\_ STRING & OCTET STRING (one octet per char) \\
\hline LTC\_ ASN1\_ NULL & NULL \\
2006-11-17 14:21:24 +00:00
\hline LTC\_ ASN1\_ OBJECT\_ IDENTIFIER & OBJECT IDENTIFIER \\
2005-06-09 00:08:13 +00:00
\hline LTC\_ ASN1\_ IA5\_ STRING & IA5 STRING (one octet per char) \\
2006-11-17 14:21:24 +00:00
\hline LTC\_ ASN1\_ PRINTABLE\_ STRING & PRINTABLE STRING (one octet per char) \\
2017-04-24 21:53:13 +00:00
\hline LTC\_ ASN1\_ UTF8\_ STRING & UTF8 STRING (one wchar\_ t per char) \\
2005-06-27 11:47:35 +00:00
\hline LTC\_ ASN1\_ UTCTIME & UTCTIME (see ltc\_ utctime structure) \\
2017-04-24 21:53:13 +00:00
\hline LTC\_ ASN1\_ CHOICE & CHOICE \\
2005-11-24 11:57:58 +00:00
\hline LTC\_ ASN1\_ SEQUENCE & SEQUENCE (and SEQUENCE OF) \\
\hline LTC\_ ASN1\_ SET & SET \\
\hline LTC\_ ASN1\_ SETOF & SET OF \\
2014-08-30 15:18:58 +00:00
\hline LTC\_ ASN1\_ RAW\_ BIT\_ STRING & BIT STRING (one octet per char) \\
\hline LTC\_ ASN1\_ TELETEX\_ STRING & TELETEX STRING (one octet per char) \\
2017-04-24 21:53:13 +00:00
\hline LTC\_ ASN1\_ GENERALIZEDTIME & GeneralizedTime (see ltc\_ generalizedtime structure) \\
2018-01-21 12:19:37 +00:00
\hline LTC\_ ASN1\_ CUSTOM\_ TYPE & A custom type (see LTC\_ SET\_ ASN1\_ CUSTOM\_ XXX macros) \\
2005-06-09 00:08:13 +00:00
\hline
\end { tabular}
\caption { List of ASN.1 Supported Types}
2017-11-28 09:49:12 +00:00
\index { ltc\_ asn1\_ type}
2005-06-09 00:08:13 +00:00
\end { small}
\end { center}
\end { figure}
2018-01-21 12:19:37 +00:00
\index { LTC\_ ASN1\_ CUSTOM\_ TYPE}
\index { LTC\_ SET\_ ASN1\_ CUSTOM\_ CONSTRUCTED macro}
\index { LTC\_ SET\_ ASN1\_ CUSTOM\_ PRIMITIVE macro}
To be able to encode and decode all other valid ASN.1 Identifiers, such as Context-Specific types the macros
\textit { LTC\_ SET\_ ASN1\_ CUSTOM\_ CONSTRUCTED(list, index, Class, Tag, Data)} resp.
\textit { LTC\_ SET\_ ASN1\_ CUSTOM\_ PRIMITIVE(list, index, Class, Tag, Type, Data, Size)} have been provided.
They will assign to the \textit { index} th position in the \textit { list} the Identifier-triplet (Class, CONSTRUCTED resp. PRIMITIVE, Tag).
An example usage would be:
\begin { small}
\begin { verbatim}
...
ltc_ asn1_ list sequence[4], custom[1];
unsigned long three=3;
unsigned char buf[128];
LTC_ SET_ ASN1(sequence, 0, LTC_ ASN1_ IA5_ STRING, "hello", 5);
LTC_ SET_ ASN1(sequence, 1, LTC_ ASN1_ SHORT_ INTEGER, & three, 1);
LTC_ SET_ ASN1(sequence, 2, LTC_ ASN1_ NULL, NULL, 0);
LTC_ SET_ ASN1_ CUSTOM_ PRIMITIVE(sequence, 3, LTC_ ASN1_ CL_ CONTEXT_ SPECIFIC, 23, \
LTC_ ASN1_ OCTET_ STRING, buf, sizeof(buf));
LTC_ SET_ ASN1_ CUSTOM_ CONSTRUCTED(custom, 0, LTC_ ASN1_ CL_ CONTEXT_ SPECIFIC, 0, sequence);
\end { verbatim}
\end { small}
This would allow (un)pack'ing the given \textit { sequence} from/in the context-specific tag \textit { [0]} .
2005-06-09 00:08:13 +00:00
\subsection { SEQUENCE Type}
The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.
2006-11-17 14:21:24 +00:00
\subsubsection { SEQUENCE Encoding}
2005-06-09 00:08:13 +00:00
To encode a sequence a \textbf { ltc\_ asn1\_ list} array must be initialized with the members of the sequence and their respective pointers. The encoding is performed
with the following function.
2014-08-30 13:21:40 +00:00
\index { der\_ encode\_ sequence()} \index { LTC\_ ASN1\_ EOL}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ sequence(ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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} .
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
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
2005-06-09 00:08:13 +00:00
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
2006-11-17 14:21:24 +00:00
the \textit { data} pointer is simply a pointer to another \textbf { ltc\_ asn1\_ list} .
2005-06-09 00:08:13 +00:00
\subsubsection { SEQUENCE Decoding}
\index { der\_ decode\_ sequence()}
2018-01-21 12:19:37 +00:00
\index { der\_ decode\_ sequence\_ strict()}
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
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
2006-11-17 14:21:24 +00:00
(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
2014-08-28 12:42:19 +00:00
units of the respective type has been loaded.
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2006-11-17 14:21:24 +00:00
int der_ decode_ sequence(const unsigned char *in,
unsigned long inlen,
2014-08-28 12:42:19 +00:00
ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long outlen);
2018-01-21 12:19:37 +00:00
int der_ decode_ sequence_ strict(const unsigned char *in,
unsigned long inlen,
ltc_ asn1_ list *list,
unsigned long outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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.
2018-01-21 12:19:37 +00:00
The regular variant will return \textbf { CRYPT\_ INPUT\_ TOO\_ LONG} in cases where there was more data to be decoded given through \textit { inlen} than the ASN.1 length-tag specified.
The strict variant \textit { der\_ decode\_ sequence\_ strict()} returns an error in this case.
2005-06-09 00:08:13 +00:00
2006-11-17 14:21:24 +00:00
For the following types the \textit { size} field will be updated to reflect the number of units read of the given type.
2005-06-09 00:08:13 +00:00
\begin { enumerate}
2018-01-21 12:19:37 +00:00
\item (RAW) BIT STRING
2005-06-09 00:08:13 +00:00
\item OCTET STRING
\item OBJECT IDENTIFIER
\item IA5 STRING
\item PRINTABLE STRING
2018-01-21 12:19:37 +00:00
\item TELETEX STRING
\item UTF8 STRING
2005-06-09 00:08:13 +00:00
\end { enumerate}
\subsubsection { SEQUENCE Length}
The length of a SEQUENCE can be determined with the following function.
\index { der\_ length\_ sequence()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ length_ sequence(ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2005-06-09 00:08:13 +00:00
unsigned long *outlen);
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will get the encoding size for the given \textit { list} of length \textit { inlen} and store it in \textit { outlen} .
2005-06-09 00:08:13 +00:00
2014-08-30 13:21:40 +00:00
\subsubsection { SEQUENCE Multiple Argument Lists} \index { LTC\_ ASN1\_ EOL}
2005-06-09 00:08:13 +00:00
For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
\index { der\_ encode\_ sequence\_ multi()}
\index { der\_ decode\_ sequence\_ multi()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ sequence_ multi(unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen, ...);
2014-08-28 12:42:19 +00:00
int der_ decode_ sequence_ multi(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen, ...);
2005-06-09 00:08:13 +00:00
\end { verbatim}
These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
2006-11-17 14:21:24 +00:00
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} .
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
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
2006-11-17 14:21:24 +00:00
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.
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\begin { small}
\begin { verbatim}
unsigned char buf[MAXBUFSIZE];
unsigned long buflen;
int err;
buflen = sizeof(buf);
2014-08-28 12:42:19 +00:00
if ((err =
2006-12-16 18:10:04 +00:00
der_ encode_ sequence_ multi(buf, & buflen,
LTC_ ASN1_ IA5_ STRING, 5UL, "Hello",
LTC_ ASN1_ IA5_ STRING, 7UL, " World!",
LTC_ ASN1_ EOL, 0UL, NULL)) != CRYPT_ OK) {
// error handling
}
\end { verbatim}
\end { small}
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.
2005-11-24 11:57:58 +00:00
\subsection { SET and SET OF}
\index { SET} \index { SET OF}
2006-12-16 18:10:04 +00:00
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
2014-08-28 12:42:19 +00:00
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
2005-11-24 11:57:58 +00:00
a \textbf { single} ASN.1 object sorted in ascending order by the DER their respective encodings.
\subsubsection { SET Encoding}
2006-12-16 18:10:04 +00:00
SETs use the same array structure of ltc\_ asn1\_ list that the SEQUENCE functions use. They are encoded with the following function:
2005-11-24 11:57:58 +00:00
\index { der\_ encode\_ set()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ set(ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2014-08-28 12:42:19 +00:00
\end { verbatim}
2005-11-24 11:57:58 +00:00
2014-08-28 12:42:19 +00:00
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
2005-11-24 11:57:58 +00:00
array (to make the process deterministic).
2006-12-16 18:10:04 +00:00
This function will \textbf { NOT} recognize \textit { DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
2005-11-24 11:57:58 +00:00
\subsubsection { SET Decoding}
The SET type can be decoded with the following function.
\index { der\_ decode\_ set()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ decode_ set(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long outlen);
2005-11-24 11:57:58 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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.
2005-11-24 11:57:58 +00:00
2014-08-28 12:42:19 +00:00
It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.
2005-11-24 11:57:58 +00:00
\subsubsection { SET Length}
The length of a SET can be determined by calling der\_ length\_ sequence() since they have the same encoding length.
\subsubsection { SET OF Encoding}
2014-08-28 12:42:19 +00:00
A \textit { SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object. They are
2005-11-24 11:57:58 +00:00
used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_ asn1\_ list that the SEQUENCE functions
use. They are encoded with the following function.
\index { der\_ encode\_ setof()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ setof(ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-11-24 11:57:58 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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} .
2005-11-24 11:57:58 +00:00
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
2014-08-28 12:42:19 +00:00
means you need at least enough memory to keep an additional copy of the output on the heap.
2005-11-24 11:57:58 +00:00
\subsubsection { SET OF Decoding}
2014-08-28 12:42:19 +00:00
Since the decoding of a \textit { SET OF} object is unambiguous it can be decoded with der\_ decode\_ sequence().
2005-11-24 11:57:58 +00:00
\subsubsection { SET OF Length}
2006-11-17 14:21:24 +00:00
Like the SET type the der\_ length\_ sequence() function can be used to determine the length of a \textit { SET OF} object.
2005-11-24 11:57:58 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 INTEGER}
2005-06-09 00:08:13 +00:00
To encode or decode INTEGER data types use the following functions.
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ integer()} \index { der\_ decode\_ integer()} \index { der\_ length\_ integer()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ integer( void *num,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2014-08-28 12:42:19 +00:00
int der_ decode_ integer(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
void *num);
2006-11-17 14:21:24 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ integer( void *num,
2006-11-17 14:21:24 +00:00
unsigned long *len);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
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.
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ short\_ integer()} \index { der\_ decode\_ short\_ integer()} \index { der\_ length\_ short\_ integer()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ short_ integer(unsigned long num,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ short_ integer(const unsigned char *in,
unsigned long inlen,
2005-06-09 00:08:13 +00:00
unsigned long *num);
2014-08-28 12:42:19 +00:00
int der_ length_ short_ integer(unsigned long num,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
These will encode or decode an unsigned \textbf { unsigned long} type (only reads upto 32--bits). For values in the range $ 0 \dots 2 ^ { 32 } - 1 $ the integer
and short integer functions can encode and decode each others outputs.
2004-10-30 03:00:26 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 BIT STRING}
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ bit\_ string()} \index { der\_ decode\_ bit\_ string()} \index { der\_ length\_ bit\_ string()}
2004-10-30 03:00:26 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ bit_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2004-10-30 03:00:26 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ bit_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2004-10-30 03:00:26 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ bit_ string(unsigned long nbits,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
These will encode or decode a BIT STRING data type. The bits are passed in (or read out) using one \textbf { char} per bit. A non--zero value will be interpreted
2006-12-16 18:10:04 +00:00
as a one bit, and a zero value a zero bit.
2005-06-09 00:08:13 +00:00
2014-08-30 15:18:58 +00:00
\subsection { ASN.1 RAW BIT STRING}
\index { der\_ encode\_ raw\_ bit\_ string()} \index { der\_ decode\_ raw\_ bit\_ string()}
\begin { verbatim}
int der_ encode_ raw_ bit_ string(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen);
int der_ decode_ raw_ bit_ string(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen);
\end { verbatim}
These will encode or decode a BIT STRING data type.
The bits are passed in (or read out) using one \textbf { unsigned char} per 8 bit.
This function differs from the normal BIT STRING, as it can be used to directly
process raw binary data and store it to resp. read it from an ASN.1 BIT STRING
data type.
The length function is the same as for the normal BIT STRING \textit { der\_ length\_ bit\_ string()} .
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 OCTET STRING}
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ octet\_ string()} \index { der\_ decode\_ octet\_ string()} \index { der\_ length\_ octet\_ string()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ octet_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ octet_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ octet_ string(unsigned long noctets,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf { unsigned char} each.
2005-06-09 00:08:13 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 OBJECT IDENTIFIER}
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ object\_ identifier()} \index { der\_ decode\_ object\_ identifier()} \index { der\_ length\_ object\_ identifier()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ object_ identifier(unsigned long *words,
2006-11-17 14:21:24 +00:00
unsigned long nwords,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2006-11-17 14:21:24 +00:00
int der_ decode_ object_ identifier(const unsigned char *in,
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned long *words,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ object_ identifier(unsigned long *words,
unsigned long nwords,
2005-06-09 00:08:13 +00:00
unsigned long *outlen);
2004-10-30 03:00:26 +00:00
\end { verbatim}
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
These will encode or decode an OBJECT IDENTIFIER object. The words of the OID are stored in individual \textbf { unsigned long} elements, and must be in the range
2014-08-28 12:42:19 +00:00
$ 0 \ldots 2 ^ { 32 } - 1 $ .
2005-06-09 00:08:13 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 IA5 STRING}
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ ia5\_ string()} \index { der\_ decode\_ ia5\_ string()} \index { der\_ length\_ ia5\_ string()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ ia5_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ ia5_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ ia5_ string(const unsigned char *octets,
unsigned long noctets,
2005-06-09 00:08:13 +00:00
unsigned long *outlen);
\end { verbatim}
2006-12-16 18:10:04 +00:00
These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf { char} elements. These functions performs internal character
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
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.
2005-06-09 00:08:13 +00:00
2014-08-30 15:18:58 +00:00
\subsection { ASN.1 TELETEX STRING}
\index { der\_ decode\_ teletex\_ string()} \index { der\_ length\_ teletex\_ string()}
\begin { verbatim}
int der_ decode_ teletex_ string(const unsigned char *in,
unsigned long inlen,
unsigned char *out,
unsigned long *outlen);
int der_ length_ teletex_ string(const unsigned char *octets,
unsigned long noctets,
unsigned long *outlen);
\end { verbatim}
These will decode a TELETEX STRING.
The characters are read in individual \textbf { char} elements.
The internal structure is similar to that of the IA5 STRING implementation, to
be able to provide a stable conversion independent of the build-- and run--time
platform.
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 PRINTABLE STRING}
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ printable\_ string()} \index { der\_ decode\_ printable\_ string()} \index { der\_ length\_ printable\_ string()}
2005-06-09 00:08:13 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ printable_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ printable_ string(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ printable_ string(const unsigned char *octets,
unsigned long noctets,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-09 00:08:13 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf { char} elements. These functions performs internal character
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
2006-11-17 14:21:24 +00:00
that the build platform honours the run-time platforms character conventions.
2005-06-09 00:08:13 +00:00
2006-12-16 18:10:04 +00:00
\subsection { ASN.1 UTF8 STRING}
\index { der\_ encode\_ utf8\_ string()} \index { der\_ decode\_ utf8\_ string()} \index { der\_ length\_ utf8\_ string()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ utf8_ string(const wchar_ t *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2014-08-28 12:42:19 +00:00
int der_ decode_ utf8_ string(const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen,
2014-08-28 12:42:19 +00:00
wchar_ t *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2014-08-28 12:42:19 +00:00
int der_ length_ utf8_ string(const wchar_ t *octets,
unsigned long noctets,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
\end { verbatim}
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
2014-08-28 12:42:19 +00:00
mapping and treat the characters as literals.
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_ t has been defined previously.
2005-06-09 00:08:13 +00:00
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 UTCTIME}
The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
2006-12-16 18:10:04 +00:00
\index { ltc\_ utctime structure}
2005-06-27 11:47:35 +00:00
\begin { verbatim}
typedef struct {
unsigned YY, /* year 00--99 */
MM, /* month 01--12 */
DD, /* day 01--31 */
hh, /* hour 00--23 */
mm, /* minute 00--59 */
ss, /* second 00--59 */
off_ dir, /* timezone offset direction 0 == +, 1 == - */
off_ hh, /* timezone offset hours */
off_ mm; /* timezone offset minutes */
} ltc_ utctime;
\end { verbatim}
2014-08-28 12:42:19 +00:00
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 $ \lbrace 5 , 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.
2005-06-27 11:47:35 +00:00
2006-12-16 18:10:04 +00:00
\index { der\_ encode\_ utctime()} \index { der\_ decode\_ utctime()} \index { der\_ length\_ utctime()}
2005-06-27 11:47:35 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ encode_ utctime( ltc_ utctime *utctime,
unsigned char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-27 11:47:35 +00:00
2014-08-28 12:42:19 +00:00
int der_ decode_ utctime(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long *inlen,
ltc_ utctime *out);
2005-06-27 11:47:35 +00:00
2014-08-28 12:42:19 +00:00
int der_ length_ utctime( ltc_ utctime *utctime,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2005-06-27 11:47:35 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2005-06-27 11:47:35 +00:00
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).
2017-04-24 21:53:13 +00:00
\subsection { ASN.1 GeneralizedTime}
The GeneralizedTime type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
\index { ltc\_ utctime structure}
\begin { verbatim}
typedef struct {
unsigned YYYY, /* year 0--9999 */
MM, /* month 1--12 */
DD, /* day 1--31 */
hh, /* hour 0--23 */
mm, /* minute 0--59 */
ss, /* second 0--59 */
fs, /* fractional seconds 1--UINT_ MAX */
off_ dir, /* timezone offset direction 0 == +, 1 == - */
off_ hh, /* timezone offset hours */
off_ mm; /* timezone offset minutes */
} ltc_ generalizedtime;
\end { verbatim}
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 $ \lbrace 2005 , 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.
\index { der\_ encode\_ utctime()} \index { der\_ decode\_ utctime()} \index { der\_ length\_ utctime()}
\begin { verbatim}
int der_ encode_ generalizedtime(ltc_ generalizedtime *gtime,
unsigned char *out,
unsigned long *outlen);
int der_ decode_ generalizedtime(const unsigned char *in,
unsigned long *inlen,
ltc_ generalizedtime *out);
int der_ length_ generalizedtime(ltc_ generalizedtime *gtime,
unsigned long *outlen);
\end { verbatim}
The encoder will store time in one of the following ASN.1 formats, either \textit { YYYYMMDDhhmmssZ} or
\textit { YYYYMMDDhhmmss$ \pm $ hhmm} or\textit { YYYYMMDDhhmmss.fsZ} or \textit { YYYYMMDDhhmmss.fs$ \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.
The fractional seconds are always added in case they are not $ 0 $ .
The implementation of fractional seconds is currently unreliable and you can't detect decoded
resp. encode leading $ 0 $ 's (e.g. \textit { 20170424232717.005Z} would be decoded as
\textit { 22. April 2017, 23:27:17.5} ).
It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
2005-06-27 11:47:35 +00:00
\subsection { ASN.1 CHOICE}
2014-08-28 12:42:19 +00:00
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
2005-06-27 11:47:35 +00:00
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
2014-08-28 12:42:19 +00:00
type\footnote { Except it cannot have LTC\_ ASN1\_ INTEGER and LTC\_ ASN1\_ SHORT\_ INTEGER simultaneously.} except for other CHOICE types.
2005-06-27 11:47:35 +00:00
2014-08-28 12:42:19 +00:00
There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
2005-06-27 11:47:35 +00:00
\index { der\_ decode\_ choice()}
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ decode_ choice(const unsigned char *in,
2006-11-17 14:21:24 +00:00
unsigned long *inlen,
2014-08-28 12:42:19 +00:00
ltc_ asn1_ list *list,
2006-11-17 14:21:24 +00:00
unsigned long outlen);
2005-06-27 11:47:35 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
will have the \textit { used} flag set to non--zero to reflect it was the data type decoded.
2005-06-09 00:08:13 +00:00
2018-01-21 12:19:37 +00:00
\subsection { ASN.1 Custom Types}
To be able to represent all other valid types besides the primitive types having their own decoder, the \textit { custom\_ type} de- and encoders are provided.
\index { der\_ encode\_ custom\_ type()} \index { der\_ decode\_ custom\_ type()} \index { der\_ length\_ custom\_ type()} \index { LTC\_ ASN1\_ CUSTOM\_ TYPE}
\begin { verbatim}
int der_ encode_ custom_ type(const ltc_ asn1_ list *root,
unsigned char *out, unsigned long *outlen);
int der_ decode_ custom_ type(const unsigned char *in, unsigned long inlen,
ltc_ asn1_ list *root);
int der_ length_ custom_ type(const ltc_ asn1_ list *root,
unsigned long *outlen,
unsigned long *payloadlen);
\end { verbatim}
The usage of this de- and encoder is a bit different than the others since the type to be encoded has to be passed to the function.
Therefore the \textit { root} parameter identifies the type that should be encoded which has been set by the \textit { LTC\_ SET\_ ASN1}
and \textit { LTC\_ SET\_ ASN1\_ IDENTIFIER} , resp. \textit { LTC\_ SET\_ ASN1\_ CUSTOM} macros.
The value to de-/encode has to be linked through the \textit { data} argument of the \textit { LTC\_ SET\_ ASN1} macro, as done for sequences.
The value that should be de-/encoded can either be a primitive or a constructed type.
2005-11-18 05:15:37 +00:00
\subsection { ASN.1 Flexi Decoder}
2018-01-21 12:19:37 +00:00
The ASN.1 \textit { flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets without first knowing the structure of the data.
Where der\_ decode\_ sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely free form.
2005-11-18 05:15:37 +00:00
2014-08-28 12:42:19 +00:00
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}
2018-01-21 12:19:37 +00:00
and \textit { child} . The list works as a \textit { doubly-linked list} structure where decoded items at the same level are siblings (using \textit { next} and \textit { prev} ) and items
encoded in a SEQUENCE are stored as a \textit { child} element.
2005-11-18 05:15:37 +00:00
2018-01-21 12:19:37 +00:00
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 \textit { child}
2005-11-24 11:57:58 +00:00
pointer points to a new list of items contained within the object.
2005-11-18 05:15:37 +00:00
2014-10-09 20:39:39 +00:00
\index { der\_ decode\_ sequence\_ flexi()}
2005-11-18 05:15:37 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int der_ decode_ sequence_ flexi(const unsigned char *in,
unsigned long *inlen,
2018-01-21 12:19:37 +00:00
ltc_ asn1_ list **out);
2005-11-18 05:15:37 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
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} .
2005-11-18 05:15:37 +00:00
2006-12-16 18:10:04 +00:00
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
2018-01-21 12:19:37 +00:00
normally. The decoded list \textit { out} will point to the very first element of the list (i.e. both parent and prev pointers will be \textbf { NULL} ).
2005-11-18 05:15:37 +00:00
2014-08-28 12:42:19 +00:00
An invalid decoding will terminate the process, and free the allocated memory automatically.
2005-11-18 05:15:37 +00:00
2014-10-09 20:43:30 +00:00
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.
2018-01-21 12:19:37 +00:00
The v1.18.0 of the library had support for decoding two new types, \textbf { LTC\_ ASN1\_ CONSTRUCTED} and \textbf { LTC\_ ASN1\_ CONTEXT\_ SPECIFIC} ,
which has been replaced in FIXME-version-next by a more complete approach.
As of FIXME-version-next all ASN.1 Identifiers which don't have a decoder implemented (and thereby their own type) will be marked as
\textbf { LTC\_ ASN1\_ CUSTOM\_ TYPE} .
2014-10-09 20:39:39 +00:00
\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}
pointer. Currently no function in LibTomCrypt provides this ability.
2006-12-16 18:10:04 +00:00
\subsubsection { Sample Decoding}
Suppose we decode the following structure:
\begin { small}
\begin { verbatim}
User ::= SEQUENCE {
Name IA5 STRING
LoginToken SEQUENCE {
passwdHash OCTET STRING
pubkey ECCPublicKey
}
LastOn UTCTIME
}
\end { verbatim}
\end { small}
\begin { flushleft} and we decoded it with the following code:\end { flushleft}
\begin { small}
\begin { verbatim}
unsigned char inbuf[MAXSIZE];
unsigned long inbuflen;
ltc_ asn1_ list *list;
int err;
/* somehow fill inbuf/inbuflen */
if ((err = der_ decode_ sequence_ flexi(inbuf, inbuflen, & list)) != CRYPT_ OK) {
printf("Error decoding: %s\n", error_to_string(err));
exit(EXIT_ FAILURE);
}
\end { verbatim}
\end { small}
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:
\begin { small}
\begin { verbatim}
list = list->parent->next;
\end { verbatim}
\end { small}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
can walk up and down the nodes without keeping pointers lying around.
2017-08-09 13:56:13 +00:00
\subsubsection { Shrink'ing a Flexi List}
While decoding the flexi decoder will recursively decode an ASN.1 \textit { constructed} type it will store the decoded list
as well as the plain data that was decoded.
To free up this additional data a shrink function is provided.
2006-12-16 18:10:04 +00:00
2017-08-09 13:56:13 +00:00
\index { der\_ sequence\_ shrink()}
\begin { verbatim}
void der_ sequence_ shrink(ltc_ asn1_ list *in);
\end { verbatim}
2006-12-16 18:10:04 +00:00
2017-08-09 13:56:13 +00:00
This will free all the plain constructed data, but keep the decoded list intact.
2006-12-16 18:10:04 +00:00
\subsubsection { Free'ing a Flexi List}
2005-11-18 05:15:37 +00:00
To free the list use the following function.
\index { der\_ sequence\_ free()}
\begin { verbatim}
void der_ sequence_ free(ltc_ asn1_ list *in);
\end { verbatim}
This will free all of the memory allocated by der\_ decode\_ sequence\_ flexi().
2006-11-17 14:21:24 +00:00
\mysection { Password Based Cryptography}
2004-10-30 03:00:26 +00:00
\subsection { PKCS \# 5}
2005-06-09 00:08:13 +00:00
\index { PKCS \# 5}
2004-10-30 03:00:26 +00:00
In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \# 5 was drafted. PKCS \# 5
is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
for completeness. Algorithm Two is a bit more modern and more flexible to work with.
2015-12-03 00:54:09 +00:00
The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.
2004-10-30 03:00:26 +00:00
\subsection { Algorithm One}
2006-12-16 18:10:04 +00:00
Algorithm One accepts as input a password, an 8--byte salt, and an iteration counter. The iteration counter is meant to act as delay for
2014-08-28 12:42:19 +00:00
people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
algorithm and produces an output no longer than the output of the hash.
2004-10-30 03:00:26 +00:00
\index { pkcs\_ 5\_ alg1()}
\begin { alltt}
2014-08-28 12:42:19 +00:00
int pkcs_ 5_ alg1(const unsigned char *password,
unsigned long password_ len,
const unsigned char *salt,
int iteration_ count,
2006-11-17 14:21:24 +00:00
int hash_ idx,
unsigned char *out,
unsigned long *outlen)
2004-10-30 03:00:26 +00:00
\end { alltt}
2014-08-28 12:42:19 +00:00
Where \textit { password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit { password\_ len} .
2006-11-17 14:21:24 +00:00
The \textit { salt} is a fixed size 8--byte array which should be random for each user and session. The \textit { iteration\_ count} is the delay desired
2014-08-28 12:42:19 +00:00
on the password. The \textit { hash\_ idx} is the index of the hash you wish to use in the descriptor table.
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
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
2006-11-17 14:21:24 +00:00
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} .
2004-10-30 03:00:26 +00:00
2015-12-03 00:54:09 +00:00
\index { pkcs\_ 5\_ alg1\_ openssl()}
\begin { alltt}
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!!).
2004-10-30 03:00:26 +00:00
\subsection { Algorithm Two}
2014-08-28 12:42:19 +00:00
Algorithm Two is the recommended algorithm for this task. It allows variable length salts, and can produce outputs larger than the
2017-09-20 11:54:42 +00:00
hash functions output. As such, it can easily be used to derive session keys for ciphers and MACs as well initialization vectors as required
2006-11-17 14:21:24 +00:00
from a single password and invocation of this algorithm.
2004-10-30 03:00:26 +00:00
\index { pkcs\_ 5\_ alg2()}
\begin { alltt}
2006-11-17 14:21:24 +00:00
int pkcs_ 5_ alg2(const unsigned char *password,
2014-08-28 12:42:19 +00:00
unsigned long password_ len,
2006-11-17 14:21:24 +00:00
const unsigned char *salt,
unsigned long salt_ len,
2014-08-28 12:42:19 +00:00
int iteration_ count,
2006-11-17 14:21:24 +00:00
int hash_ idx,
unsigned char *out,
unsigned long *outlen)
2004-10-30 03:00:26 +00:00
\end { alltt}
2014-08-28 12:42:19 +00:00
Where \textit { password} is the users password. Since the algorithm allows binary passwords you must also specify the length in \textit { password\_ len} .
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
on the password. The \textit { hash\_ idx} is the index of the hash you wish to use in the descriptor table. The output of length up to
2006-11-17 14:21:24 +00:00
\textit { outlen} is stored in \textit { out} .
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
/* demo to show how to make session state material
2006-12-16 18:10:04 +00:00
* from a password */
2004-12-30 23:55:53 +00:00
#include <tomcrypt.h>
2004-10-30 03:00:26 +00:00
int main(void)
2006-11-17 14:21:24 +00:00
{
2004-10-30 03:00:26 +00:00
unsigned char password[100], salt[100],
cipher_ key[16], cipher_ iv[16],
mac_ key[16], outbuf[48];
int err, hash_ idx;
unsigned long outlen, password_ len, salt_ len;
/* register hash and get it's idx .... */
/* get users password and make up a salt ... */
/* create the material (100 iterations in algorithm) */
outlen = sizeof(outbuf);
2014-08-28 12:42:19 +00:00
if ((err = pkcs_ 5_ alg2(password, password_ len, salt,
salt_ len, 100, hash_ idx, outbuf,
& outlen))
2006-11-17 14:21:24 +00:00
!= CRYPT_ OK) {
2004-10-30 03:00:26 +00:00
/* error handle */
2006-11-17 14:21:24 +00:00
}
2004-10-30 03:00:26 +00:00
/* now extract it */
memcpy(cipher_ key, outbuf, 16);
memcpy(cipher_ iv, outbuf+16, 16);
memcpy(mac_ key, outbuf+32, 16);
/* use material (recall to store the salt in the output) */
2006-11-17 14:21:24 +00:00
}
\end { verbatim}
2004-10-30 03:00:26 +00:00
2018-10-06 11:17:44 +00:00
\mysection { PKCS \# 8}
\index { PKCS \# 8}
The library has built-in support for PKCS \# 8 decoding as specified in RFC 5208.
Encoding of private keys into PKCS \# 8 is not supported.
The library supports the following encryption algorithms:
\begin { table} [H]
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { Scheme} & \textbf { Algorithm} \\
\hline PBES1 & pbeWithMD2AndDES-CBC \\
\hline PBES1 & pbeWithMD2AndRC2-CBC \\
\hline PBES1 & pbeWithMD5AndDES-CBC \\
\hline PBES1 & pbeWithMD5AndRC2-CBC \\
\hline PBES1 & pbeWithSHA1AndDES-CBC \\
\hline PBES1 & pbeWithSHA1AndRC2-CBC \\
\hline PBES1 & pbeWithSHAAnd3-KeyTripleDES-CBC \\
\hline PBES2 + PBKDF2 & desCBC \\
\hline PBES2 + PBKDF2 & rc2CBC \\
\hline PBES2 + PBKDF2 & des-EDE3-CBC \\
\hline PBES2 + PBKDF2 & aes128-CBC \\
\hline PBES2 + PBKDF2 & aes192-CBC \\
\hline PBES2 + PBKDF2 & aes256-CBC \\
\hline
\end { tabular}
\caption { Supported PKCS\# 8 encryption algorithms}
\end { center}
\label { fig:pkcs8}
\end { table}
The PKCS \# 8 import has no direct API endpoints, but it is available through Public Key Algorithm-specific
\textit { pkaX\_ import\_ pkcs8()} functions.
2012-11-13 17:30:26 +00:00
\mysection { Key Derviation Functions}
\subsection { HKDF}
\index { HKDF}
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}
2013-03-14 22:25:17 +00:00
The \textit { hash\_ idx} parameter is the index into the descriptor table of the hash you want to use.
2012-11-13 17:30:26 +00:00
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}
2013-03-14 22:25:17 +00:00
The \textit { hash\_ idx} parameter is the index into the descriptor table of the hash you want to use.
2012-11-13 17:30:26 +00:00
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} .
2013-03-14 22:25:17 +00:00
\subsection { HKDF Extract-and-Expand}
2012-11-13 17:30:26 +00:00
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()} .
2003-03-03 00:59:24 +00:00
\chapter { Miscellaneous}
2006-11-17 14:21:24 +00:00
\mysection { Base64 Encoding and Decoding}
2017-08-07 10:06:58 +00:00
The library provides functions to encode and decode a RFC 4648 Base64 coding scheme.
2017-07-17 22:07:47 +00:00
\subsection { Standard 'base64' encoding}
The characters used in the mappings are:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
\end { verbatim}
2006-12-16 18:10:04 +00:00
Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
2003-03-03 00:59:24 +00:00
common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
2014-08-28 12:42:19 +00:00
where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
2003-03-03 00:59:24 +00:00
original input. After the first four characters is the rest of the message.
2006-12-16 18:10:04 +00:00
Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
2003-03-03 00:59:24 +00:00
put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
break up the first four characters.
To encode a binary string in base64 call:
2017-07-17 22:07:47 +00:00
\index { base64\_ encode()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int base64_ encode(const unsigned char *in,
unsigned long len,
2018-03-25 18:00:05 +00:00
char *out,
2006-11-17 14:21:24 +00:00
unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
Where \textit { in} is the binary string and \textit { out} is where the ASCII output is placed. You must set the value of \textit { outlen} prior
2014-08-28 12:42:19 +00:00
to calling this function and it sets the length of the base64 output in \textit { outlen} when it is done. To decode a base64
2003-03-03 00:59:24 +00:00
string call:
2017-07-17 22:07:47 +00:00
\index { base64\_ decode()}
2003-03-03 00:59:24 +00:00
\begin { verbatim}
2018-03-25 18:00:05 +00:00
int base64_ decode( const char *in,
unsigned long len,
unsigned char *out,
unsigned long *outlen);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2018-03-27 07:54:33 +00:00
The function \textit { base64\_ decode} works in a dangerously relaxed way which allows decoding some inputs that do not strictly follow the standard.
2017-07-17 22:07:47 +00:00
If you want to be strict during decoding you can use:
\index { base64\_ strict\_ decode()}
\begin { verbatim}
2018-03-25 18:00:05 +00:00
int base64_ strict_ decode( const char *in,
unsigned long len,
unsigned char *out,
unsigned long *outlen);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2018-03-27 07:54:33 +00:00
There is also so called sane mode that ignores white-spaces (\textit { CR} , \textit { LF} , \textit { TAB} , \textit { space} ),
does not care about trailing \textit { =} and also ignores the last input byte in case it is \textit { NUL} .
\index { base64\_ sane\_ decode()}
\begin { verbatim}
int base64_ sane_ decode( const char *in,
unsigned long len,
unsigned char *out,
unsigned long *outlen);
\end { verbatim}
2017-07-17 22:07:47 +00:00
\subsection { URL--safe 'base64url' encoding}
The characters used in the mappings are:
\begin { verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
\end { verbatim}
Those characters are sometimes also called URL and filename safe alphabet.
2017-09-20 12:15:28 +00:00
The interface is analogous to \textit { base64\_ xxxx} functions in previous chapter.
2017-07-17 22:07:47 +00:00
2018-03-27 11:57:06 +00:00
\index { base64url\_ encode()}
\index { base64url\_ strict\_ encode()}
\index { base64url\_ decode()}
\index { base64url\_ strict\_ decode()}
\index { base64url\_ sane\_ decode()}
2017-07-17 22:07:47 +00:00
\begin { verbatim}
int base64url_ encode(const unsigned char *in, unsigned long len,
2018-03-25 18:00:05 +00:00
char *out, unsigned long *outlen);
2017-09-20 12:15:28 +00:00
2017-07-17 22:07:47 +00:00
int base64url_ strict_ encode(const unsigned char *in, unsigned long inlen,
2018-03-25 18:00:05 +00:00
char *out, unsigned long *outlen);
2017-09-20 12:15:28 +00:00
2018-03-25 18:00:05 +00:00
int base64url_ decode( const char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
2017-09-20 12:15:28 +00:00
2018-03-25 18:00:05 +00:00
int base64url_ strict_ decode( const char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
2018-03-27 07:54:33 +00:00
int base64url_ sane_ decode( const char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
2017-07-17 22:07:47 +00:00
\end { verbatim}
2017-10-19 15:27:08 +00:00
\mysection { Base32 Encoding and Decoding}
The library provides functions to encode and decode a Base32 coding scheme. The supported mappings are:
2018-03-22 15:01:25 +00:00
\begin { figure} [H]
2017-10-19 15:27:08 +00:00
\begin { center}
2017-10-20 15:28:50 +00:00
\begin { tabular} { |l|l|l|}
2017-10-20 18:00:46 +00:00
\hline \textbf { id} & \textbf { Mapping} & \textbf { Name} \\
2017-10-20 15:28:50 +00:00
\hline BASE32\_ RFC4648 & ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 & RFC-4648 \\
\hline BASE32\_ BASE32HEX & 0123456789ABCDEFGHIJKLMNOPQRSTUV & Base32hex \\
\hline BASE32\_ ZBASE32 & YBNDRFG8EJKMCPQXOT1UWISZA345H769 & ZBase32 \\
\hline BASE32\_ CROCKFORD & 0123456789ABCDEFGHJKMNPQRSTVWXYZ & Crockford \\
2017-10-19 15:27:08 +00:00
\hline
\end { tabular}
\end { center}
2018-03-22 15:01:25 +00:00
\caption { Base32 coding schemes}
\end { figure}
2017-10-19 15:27:08 +00:00
To encode a binary string in base32 call:
\index { base32\_ encode()}
\begin { verbatim}
int base32_ encode(const unsigned char *in,
unsigned long len,
2018-03-22 15:01:25 +00:00
char *out,
2017-10-19 15:27:08 +00:00
unsigned long *outlen,
2017-10-20 18:00:46 +00:00
base32_ alphabet id);
2017-10-19 15:27:08 +00:00
\end { verbatim}
2017-10-20 18:00:46 +00:00
Where \textit { in} is the binary string, \textit { out} is where the ASCII output is placed and \textit { id} is
2017-10-20 15:28:50 +00:00
\textit { BASE32\_ RFC4648} , \textit { BASE32\_ BASE32HEX} , \textit { BASE32\_ ZBASE32} or \textit { BASE32\_ CROCKFORD} according the table above.
2017-10-19 15:27:08 +00:00
To decode a base32 string call:
\index { base32\_ decode()}
\begin { verbatim}
2018-03-22 15:01:25 +00:00
int base32_ decode(const char *in,
2017-10-19 15:27:08 +00:00
unsigned long len,
unsigned char *out,
unsigned long *outlen,
2017-10-20 18:00:46 +00:00
base32_ alphabet id);
2017-10-19 15:27:08 +00:00
\end { verbatim}
2018-03-22 15:01:25 +00:00
\mysection { Base16 Encoding and Decoding}
The library provides functions to encode and decode a Base16 a.k.a Hex string.
To encode a binary string in base16 call:
2018-03-26 13:45:37 +00:00
\index { base16\_ encode()}
2018-03-22 15:01:25 +00:00
\begin { verbatim}
int base16_ encode(const unsigned char *in, unsigned long inlen,
char *out, unsigned long *outlen,
2018-06-03 17:22:30 +00:00
unsigned int options);
2018-03-22 15:01:25 +00:00
\end { verbatim}
Where \textit { in} is the binary string,
\textit { out} is where the ASCII output is placed
2018-06-03 17:22:30 +00:00
and \textit { options} is either $ 0 $ to use lower-letter \textit { a..f} or else to use caps \textit { A..F} .
2018-03-22 15:01:25 +00:00
To decode a base16 string call:
2018-03-26 13:45:37 +00:00
\index { base16\_ decode()}
2018-03-22 15:01:25 +00:00
\begin { verbatim}
2018-03-26 13:45:37 +00:00
int base16_ decode(const char *in, unsigned long inlen,
2018-03-22 15:01:25 +00:00
unsigned char *out, unsigned long *outlen);
\end { verbatim}
2018-01-24 10:51:29 +00:00
\mysection { Padding data}
The library provides functions to pad and depad according to several standards, please refer to Figure \ref { fig:paddingmodes} for details about the supported standards.
\subsection { Padding mode argument}
All functions have a \textit { mode} argument which must be set to the bit-wise OR of the desired blocksize and one of the modes as shown in the following table:
\begin { figure} [H]
\begin { minipage} { \textwidth }
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { mode} & \textbf { Standard} \\
\hline LTC\_ PAD\_ PKCS7 & RFC-5652 / PKCS \# 7 \\
\hline LTC\_ PAD\_ ISO\_ 10126 & ISO/IEC 10126 \footnote { \textit { ISO/IEC 10126} support is only available when the library is built with \textit { rng\_ get\_ bytes()} support} \\
\hline LTC\_ PAD\_ ANSI\_ X923 & ANSI X.923 \\
\hline LTC\_ PAD\_ ONE\_ AND\_ ZERO & ISO/IEC 7816-4 \\
\hline LTC\_ PAD\_ ZERO & ISO/IEC 10118-1 \\
\hline LTC\_ PAD\_ ZERO\_ ALWAYS & ISO/IEC 10118-1 \footnote { \textit { LTC\_ PAD\_ ZERO\_ ALWAYS} adds an entire block of padding if the plaintext length is divisible by the blocksize} \\
\hline
\end { tabular}
\end { center}
\end { minipage}
\caption { Padding modes}
\label { fig:paddingmodes}
\end { figure}
\textit { ISO/IEC 10126} has been withdrawn as an ISO/IEC standard in 2007 and is only provided for historical reasons (it was used e.g. in early versions of TLS/SSL).
Therefore it should not be used for new designs.
\subsection { Padding}
To pad data call:
\index { padding\_ pad()}
\begin { verbatim}
int padding_ pad(unsigned char *data,
unsigned long length,
unsigned long *padded_ length,
unsigned long mode);
\end { verbatim}
Where \textit { data} is a pointer to a buffer containing the data to pad,
\textit { length} is the original length of the data to pad and
\textit { padded\_ length} is a pointer that should contain the length of buffer available and will contain the padded data-length.
It is possible to call this function with \textit { padded\_ length} set to $ 0 $ which will then return with the error-code \textit { CRYPT\_ BUFFER\_ OVERFLOW}
and \textit { padded\_ length} set to the required size of the buffer.
\subsection { Depadding}
To depad data call:
\index { padding\_ depad()}
\begin { verbatim}
int pkcs7_ depad(unsigned char *data,
unsigned long *length,
unsigned long mode);
\end { verbatim}
Where \textit { data} is a pointer to the data to depad,
\textit { length} is a pointer that should contain the length of the padded data and will be updated to contain the length of the data after depadding.
2006-11-17 14:21:24 +00:00
\mysection { Primality Testing}
2003-03-03 00:59:24 +00:00
\index { Primality Testing}
The library includes primality testing and random prime functions as well. The primality tester will perform the test in
2017-07-09 11:12:01 +00:00
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
2003-03-03 00:59:24 +00:00
Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
2014-08-28 12:42:19 +00:00
the probability of a pseudo-prime by $ 1 \over 4 $ therefore after sixteen rounds the probability is no more than
2003-03-03 01:01:00 +00:00
$ \left ( { 1 \over 4 } \right ) ^ { 8 } = 2 ^ { - 16 } $ . In practice the probability of error is in fact much lower than that.
2006-11-17 14:21:24 +00:00
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
2003-03-03 01:01:00 +00:00
is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
math operations. As a result the routine can scan ahead to the next number required for testing with very little work
involved.
2014-08-28 12:42:19 +00:00
In the event that a composite did make it through it would most likely cause the the algorithm trying to use it to fail. For
instance, in RSA two primes $ p $ and $ q $ are required. The order of the multiplicative sub-group (modulo $ pq $ ) is given
2003-03-03 01:01:00 +00:00
as $ \phi ( pq ) $ or $ ( p - 1 ) ( q - 1 ) $ . The decryption exponent $ d $ is found as $ de \equiv 1 \mbox { } ( \mbox { mod } \phi ( pq ) ) $ . If either $ p $ or $ q $ is composite the value of $ d $ will be incorrect and the user
2014-08-28 12:42:19 +00:00
will not be able to sign or decrypt messages at all. Suppose $ p $ was prime and $ q $ was composite this is just a variation of
the multi-prime RSA. Suppose $ q = rs $ for two primes $ r $ and $ s $ then $ \phi ( pq ) = ( p - 1 ) ( r - 1 ) ( s - 1 ) $ which clearly is
2003-03-03 00:59:24 +00:00
not equal to $ ( p - 1 ) ( rs - 1 ) $ .
2014-08-28 12:42:19 +00:00
These are not technically part of the LibTomMath library but this is the best place to document them.
2006-11-17 14:21:24 +00:00
To test if a \textit { mp\_ int} is prime call:
2003-03-03 00:59:24 +00:00
\begin { verbatim}
int is_ prime(mp_ int *N, int *result);
\end { verbatim}
2014-08-28 12:42:19 +00:00
This puts a one in \textit { result} if the number is probably prime, otherwise it places a zero in it. It is assumed that if
it returns an error that the value in \textit { result} is undefined. To make
2003-03-03 00:59:24 +00:00
a random prime call:
\begin { verbatim}
2014-08-28 12:42:19 +00:00
int rand_ prime( mp_ int *N,
unsigned long len,
prng_ state *prng,
2006-11-17 14:21:24 +00:00
int wprng);
2003-03-03 00:59:24 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
Where \textit { len} is the size of the prime in bytes ($ 2 \le len \le 256 $ ). You can set \textit { len} to the negative size you want
2014-08-28 12:42:19 +00:00
to get a prime of the form $ p \equiv 3 \mbox { } ( \mbox { mod } 4 ) $ . So if you want a 1024-bit prime of this sort pass
2006-11-17 14:21:24 +00:00
\textit { len = -128} to the function. Upon success it will return { \bf CRYPT\_ OK} and \textit { N} will contain an integer which
2003-03-03 00:59:24 +00:00
is very likely prime.
2017-07-09 10:46:15 +00:00
\mysection { Random MPI Generation}
\index { Random MPI Generation}
Several Public Key Cryptography algorithms require random MPI's for operations like signature generation.
The library provides two API functions to generate random MPI's which allow the utilisation of a user-defined PRNG to aquire the random data.
\index { rand\_ bn\_ bits()}
\begin { verbatim}
int rand_ bn_ bits( void *N,
int bits,
prng_ state *prng,
int wprng);
\end { verbatim}
This sets \textit { N} to a \textit { bits} -long random MPI.
\index { rand\_ bn\_ upto()}
\begin { verbatim}
int rand_ bn_ upto( void *N,
void *limit,
prng_ state *prng,
int wprng);
\end { verbatim}
This ensures that \textit { N} is set to a random MPI in the range $ 1 \le N < limit $ .
2017-08-09 13:56:13 +00:00
\mysection { Helper functions}
\subsection { Zero'ing data}
2017-12-06 06:12:50 +00:00
Optimizing compilers are sometimes allowed to remove an invocation of \textit { memset(out, 0, outlen)} ,
which could result in sensitive data not being zero'ed out. LibTomCrypt, therefore, implements a variant
of this routine, \textit { zeromem(out, outlen)} , which won't be optimized away.
2017-08-09 13:56:13 +00:00
\index { zeromem()}
\begin { verbatim}
void zeromem(volatile void *out, size_ t outlen);
\end { verbatim}
2017-08-14 09:48:05 +00:00
This zero's the buffer \textit { out} of size \textit { outlen} .
2017-08-09 13:56:13 +00:00
\subsection { Constant-time memory compare}
2017-08-14 09:48:05 +00:00
Some symmetric-key cryptographic operation-modes are vulnerable to timing attacks in case non-contant-time memory comparison functions
are used to compare results. Therefore LibTomCrypt implements a constant-time memory compare function.
2017-08-09 13:56:13 +00:00
\index { mem\_ neq()}
\begin { verbatim}
int mem_ neq(const void *a, const void *b, size_ t len);
\end { verbatim}
2017-08-14 09:48:05 +00:00
This will compare the buffer \textit { a} against the buffer \textit { b} for \textit { len} bytes.
The return value is either \textit { 0} when the content of \textit { a} and \textit { b} is equal or \textit { 1} when it differs.
2017-08-09 13:56:13 +00:00
2017-08-14 11:27:55 +00:00
\subsection { Radix to binary conversion}
All public-key cryptographic algorithms provide a way to import and/or export their key parameters in binary format.
In order to be able to import keys stored in different formats, e.g. hexadecimal strings, the \textit { radix\_ to\_ bin()} function is provided.
\index { radix\_ to\_ bin()}
\begin { verbatim}
int radix_ to_ bin(const void *in, int radix, void *out, unsigned long *len);
\end { verbatim}
This will convert the MPI \textit { in} of radix \textit { radix} to the buffer pointed to by \textit { out} .
The field \textit { len} is a pointer to the length of the buffer on input and the length stored on output.
In case you don't know the length of the buffer you can use \textit { radix\_ to\_ bin()} to determine the length for you.
\begin { verbatim}
#include <tomcrypt.h>
int main(void)
{
const char *mpi = "AABBCCDD";
unsigned long l = 0;
void* buf;
int ret;
ltc_ mp = ltm_ desc;
if (radix_ to_ bin(mpi, 16, NULL, & l) != CRYPT_ BUFFER_ OVERFLOW)
return EXIT_ FAILURE;
buf = malloc(l);
ret = EXIT_ SUCCESS;
if (radix_ to_ bin(mpi, 16, buf, & l) != CRYPT_ OK)
ret = EXIT_ FAILURE;
free(buf);
return ret;
}
\end { verbatim}
2014-08-31 06:50:42 +00:00
\mysection { Dynamic Language Support}
\index { Dynamic Language Support}
Various LibTomCrypt functions require that their callers define a struct
(or a union) and provide a pointer to it, or allocate sufficient memory and
provide its pointer. Programs written in C or C++ can obtain the necessary
information by simply including the appropriate header files, but dynamic
languages like Python don't understand C header files, and without assistance,
have no way to know how much memory to allocate. A similar story can be told
for certain LTC constant values.
LTC's Dynamic Language Support provides functions that return the size of
a named struct or union, the value of a named constant, a list of all sizes
supported, and a list of all named constants supported. Two additional
functions can initialize LTM and TFM.
To get the size of a named struct or union:
\begin { verbatim}
2014-09-29 21:42:40 +00:00
int crypt_ get_ size( const char *namein,
unsigned int *sizeout);
2014-08-31 06:50:42 +00:00
\end { verbatim}
2014-09-29 21:42:40 +00:00
$ namein $ is spelled exactly as found in the C header files. This function will
return -1 if $ namein $ is not found.
2014-08-31 06:50:42 +00:00
To get the value of a named constant:
\begin { verbatim}
int crypt_ get_ constant(const char *namein,
int *valueout);
\end { verbatim}
$ namein $ is spelled exactly as found in the C header files. Again, -1 is
returned if $ namein $ is not found.
To get the names of all the supported structs, unions and constants:
\begin { verbatim}
2014-09-29 21:42:40 +00:00
int crypt_ list_ all_ sizes( char *names_ list,
unsigned int *names_ list_ size);
2014-08-31 06:50:42 +00:00
2014-09-29 21:42:40 +00:00
int crypt_ list_ all_ constants( char *names_ list,
unsigned int *names_ list_ size);
2014-08-31 06:50:42 +00:00
\end { verbatim}
You may want to call these functions twice, first to get the amount
2017-10-16 20:05:24 +00:00
of memory to be allocated for the $ names \_ list $ , and a final time to
actually populate $ names \_ list $ . If $ names \_ list $ is NULL,
$ names \_ list \_ size $ will be the minimum size needed to receive the
complete $ names \_ list $ . If $ names \_ list $ is NOT NULL, $ names \_ list $ must
be a pointer to sufficient memory into which the $ names \_ list $ will be
written. Also, the value in $ names \_ list \_ size $ sets the upper bound of
2014-08-31 06:50:42 +00:00
the number of characters to be written. A -1 return value signifies
insufficient space.
2017-10-16 20:05:24 +00:00
The format of the $ names \_ list $ string is a series of $ name,value $ pairs
2014-08-31 06:50:42 +00:00
where each name and value is separated by a comma, the pairs are separated
by newlines, and the list is null terminated.
2017-10-16 20:05:24 +00:00
\index { crypt\_ mp\_ init()}
2014-08-31 06:50:42 +00:00
\begin { verbatim}
2017-10-16 20:05:24 +00:00
int crypt_ mp_ init(const char* mpi);
2014-08-31 06:50:42 +00:00
\end { verbatim}
2017-10-16 20:05:24 +00:00
To ease the setup of a specific math descriptor, in cases where the library was compiled with support for multiple MPI libraries,
the function \textit { crypt\_ mp\_ init()} is provided.
It takes a string to the desired MPI library to use as an argument.
The three default MPI libraries are identified as follows, \textit { LibTomMath} as \texttt { "ltm"} , \textit { TomsFastmath} as \texttt { "tfm"}
and the \textit { GNU Multi Precision Arithmetic Library} as \texttt { "gmp"} .
The identification happens case-insensitive and only on the first character.
2014-08-31 06:50:42 +00:00
Here is a Python program demonstrating how to call various LTC dynamic
language support functions.
2017-10-16 20:05:24 +00:00
A more detailed example is given in the library source in \texttt { demos/demo\_ dynamic.py} .
2014-08-31 06:50:42 +00:00
\begin { verbatim}
from ctypes import *
# load the OSX shared/dynamic library
LIB = CDLL('libtomcrypt.dylib')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print info about this library
little = c_ int() # assume False is big
word32 = c_ int() # assume False is 64-bit
LIB.crypt_ get_ constant('ENDIAN_ LITTLE', byref(little))
LIB.crypt_ get_ constant('ENDIAN_ 32BITWORD', byref(word32))
print('this lib was compiled for a %s endian %d-bit processor'
% ('little' if little else 'big', 32 if word32 else 64))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print the size of the struct named "sha256_ state"
struct_ size = c_ int()
# don't forget to add the '_ struct' or '_ union' suffix
LIB.crypt_ get_ size('sha256_ state_ struct', byref(struct_ size))
print('allocate %d bytes for sha256_state' % struct_size.value)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print a list of all supported named constants
list_ size = c_ int()
# call with NULL to calc the min size needed for the list
LIB.crypt_ list_ all_ constants(None, byref(list_ size))
# allocate required space
names_ list = c_ buffer(list_ size.value)
# call again providing a pointer to where to write the list
LIB.crypt_ list_ all_ constants(names_ list, byref(list_ size))
print(names_ list.value)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print a list of all supported named structs and unions
list_ size = c_ int()
# call with NULL to calc the min size needed for the list
LIB.crypt_ list_ all_ sizes(None, byref(list_ size))
# allocate required space
names_ list = c_ buffer(list_ size.value)
# call again providing a pointer to where to write the list
LIB.crypt_ list_ all_ sizes(names_ list, byref(list_ size))
print(names_ list.value)
\end { verbatim}
2003-03-03 00:59:24 +00:00
\chapter { Programming Guidelines}
2006-11-17 14:21:24 +00:00
\mysection { Secure Pseudo Random Number Generators}
2006-12-16 18:10:04 +00:00
Probably the single most vulnerable point of any cryptosystem is the PRNG. Without one, generating and protecting secrets
would be impossible. The requirement that one be setup correctly is vitally important, and to address this point the library
2014-08-28 12:42:19 +00:00
does provide two RNG sources that will address the largest amount of end users as possible. The \textit { sprng} PRNG provides an easy to
access source of entropy for any application on a UNIX (and the like) or Windows computer.
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
However, when the end user is not on one of these platforms, the application developer must address the issue of finding
2003-03-03 00:59:24 +00:00
entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
2014-08-28 12:42:19 +00:00
a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Preventing Trivial Errors}
2006-12-16 18:10:04 +00:00
Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values. All of the functions
2003-03-03 00:59:24 +00:00
which output variable length strings will require you to pass the length of the destination. If the size of your output
buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
2014-08-28 12:42:19 +00:00
Also, virtually all of the functions return an error code or { \bf CRYPT\_ OK} . You should detect all errors, as simple
2006-12-16 18:10:04 +00:00
typos can cause algorithms to fail to work as desired.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Registering Your Algorithms}
2014-08-28 12:42:19 +00:00
To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
2003-03-03 00:59:24 +00:00
before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
2014-08-28 12:42:19 +00:00
A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
write the few functions required plus a descriptor. After registering your PRNG, all of the library functions that
2006-12-16 18:10:04 +00:00
need a PRNG can instantly take advantage of it. The same applies for ciphers, hashes, and bignum math routines.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Key Sizes}
2003-03-03 00:59:24 +00:00
\subsection { Symmetric Ciphers}
2006-12-16 18:10:04 +00:00
For symmetric ciphers, use as large as of a key as possible. For the most part \textit { bits are cheap} so using a 256--bit key
is not a hard thing to do. As a good rule of thumb do not use a key smaller than 128 bits.
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
\subsection { Asymmetric Ciphers}
2003-03-03 00:59:24 +00:00
The following chart gives the work factor for solving a DH/RSA public key using the NFS. The work factor for a key of order
$ n $ is estimated to be
\begin { equation}
2014-08-28 12:42:19 +00:00
e^ { 1.923 \cdot ln(n)^ { 1 \over 3} \cdot ln(ln(n))^ { 2 \over 3} }
2003-03-03 00:59:24 +00:00
\end { equation}
2014-08-28 12:42:19 +00:00
Note that $ n $ is not the bit-length but the magnitude. For example, for a 1024-bit key $ n = 2 ^ { 1024 } $ . The work required
2003-03-03 00:59:24 +00:00
is:
2017-09-20 12:33:04 +00:00
\begin { figure} [H]
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|}
\hline RSA/DH Key Size (bits) & Work Factor ($ log _ 2 $ ) \\
\hline 512 & 63.92 \\
\hline 768 & 76.50 \\
\hline 1024 & 86.76 \\
\hline 1536 & 103.37 \\
\hline 2048 & 116.88 \\
\hline 2560 & 128.47 \\
\hline 3072 & 138.73 \\
\hline 4096 & 156.49 \\
2014-08-28 12:42:19 +00:00
\hline
2003-03-03 00:59:24 +00:00
\end { tabular}
\end { center}
2006-12-16 18:10:04 +00:00
\caption { RSA/DH Key Strength}
\end { figure}
2003-03-03 00:59:24 +00:00
2006-11-17 14:21:24 +00:00
The work factor for ECC keys is much higher since the best attack is still fully exponential. Given a key of magnitude
$ n $ it requires $ \sqrt n $ work. The following table summarizes the work required:
2017-09-20 12:33:04 +00:00
\begin { figure} [H]
2003-03-03 00:59:24 +00:00
\begin { center}
\begin { tabular} { |c|c|}
\hline ECC Key Size (bits) & Work Factor ($ log _ 2 $ ) \\
2006-12-16 18:10:04 +00:00
\hline 112 & 56 \\
\hline 128 & 64 \\
\hline 160 & 80 \\
2003-03-03 00:59:24 +00:00
\hline 192 & 96 \\
\hline 224 & 112 \\
\hline 256 & 128 \\
\hline 384 & 192 \\
\hline 521 & 260.5 \\
\hline
\end { tabular}
\end { center}
2006-12-16 18:10:04 +00:00
\caption { ECC Key Strength}
\end { figure}
2003-03-03 00:59:24 +00:00
Using the above tables the following suggestions for key sizes seems appropriate:
\begin { center}
\begin { tabular} { |c|c|c|}
\hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
2006-12-16 18:10:04 +00:00
\hline Near term & 1024 & 160 \\
\hline Short term & 1536 & 192 \\
\hline Long Term & 2560 & 384 \\
2014-08-28 12:42:19 +00:00
\hline
2003-03-03 00:59:24 +00:00
\end { tabular}
\end { center}
2006-11-17 14:21:24 +00:00
\mysection { Thread Safety}
2006-12-16 18:10:04 +00:00
The library is not fully thread safe but several simple precautions can be taken to avoid any problems. The registry functions
such as register\_ cipher() are not thread safe no matter what you do. It is best to call them from your programs initialization
2003-03-03 00:59:24 +00:00
code before threads are initiated.
The rest of the code uses state variables you must pass it such as hash\_ state, hmac\_ state, etc. This means that if each
2006-12-16 18:10:04 +00:00
thread has its own state variables then they will not affect each other, and are fully thread safe. This is fairly simple with symmetric ciphers
2014-08-28 12:42:19 +00:00
and hashes.
2003-03-03 00:59:24 +00:00
2006-12-16 18:10:04 +00:00
\index { LTC\_ PTHREAD}
The only sticky issue is a shared PRNG which can be alleviated with the careful use of mutex devices. Defining LTC\_ PTHREAD for instance, enables
pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.
2003-03-03 00:59:24 +00:00
2004-10-30 03:00:26 +00:00
\chapter { Configuring and Building the Library}
2006-11-17 14:21:24 +00:00
\mysection { Introduction}
2006-12-16 18:10:04 +00:00
The library is fairly flexible about how it can be built, used, and generally distributed. Additions are being made with
2004-10-30 03:00:26 +00:00
each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
the build process to make a smaller library. This is particularly useful for shared libraries.
2006-12-16 18:10:04 +00:00
As of v1.06 of the library, the build process has been moved to two steps for the typical LibTomCrypt application. This is because
LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath, GnuMP, or TomsFastMath).
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
2005-08-01 16:36:47 +00:00
configured. Note that LibTomCrypt can be built with no internal math descriptors. This means that one must be provided at either
2014-08-28 12:42:19 +00:00
build, or run time for the application. LibTomCrypt comes with three math descriptors that provide a standard interface to math
2006-12-16 18:10:04 +00:00
libraries.
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Makefile variables}
2003-03-03 00:59:24 +00:00
2014-08-28 12:42:19 +00:00
All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process. Most of the
2005-08-01 16:36:47 +00:00
settings can be overwritten from the command line which makes custom installation a breeze.
2004-10-30 03:00:26 +00:00
2017-08-14 10:58:03 +00:00
\subsection { MAKE, CC, AR and CROSS\_ COMPILE}
\index { MAKE} \index { CC} \index { AR} \index { CROSS\_ COMPILE}
2014-08-28 12:42:19 +00:00
The MAKE, CC and AR flags can all be overwritten. They default to \textit { make} , \textit { \$ CC} and \textit { \$ AR} respectively.
2006-12-16 18:10:04 +00:00
Changing MAKE allows you to change what program will be invoked to handle sub--directories. For example, this
2005-11-18 05:15:37 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
gmake install MAKE=gmake
2005-11-18 05:15:37 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
\begin { flushleft} will build and install the libraries with the \textit { gmake} tool. Similarly, \end { flushleft}
2005-11-18 05:15:37 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make CC=arm-gcc AR=arm-ar
2005-11-18 05:15:37 +00:00
\end { verbatim}
2006-12-16 18:10:04 +00:00
\begin { flushleft} will build the library using \textit { arm--gcc} as the compiler and \textit { arm--ar} as the archiver. \end { flushleft}
2005-11-18 05:15:37 +00:00
2017-08-14 10:58:03 +00:00
\begin { verbatim}
make CROSS_ COMPILE=arm-none-eabi-
\end { verbatim}
\begin { flushleft} will build the library using the \textit { arm--none--eabi--} prefix'ed toolchain. \end { flushleft}
\subsection { IGNORE\_ SPEED and LTC\_ DEBUG}
\index { IGNORE\_ SPEED} \index { LTC\_ DEBUG}
2005-08-01 16:36:47 +00:00
When \textbf { IGNORE\_ SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
CFLAGS on the command line. E.g. to add debugging
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make IGNORE_ SPEED=1 CFLAGS="-g3"
2005-08-01 16:36:47 +00:00
\end { verbatim}
2004-10-30 03:00:26 +00:00
2014-08-28 12:42:19 +00:00
This will turn off optimizations and add \textit { -g3} to the CFLAGS which enables debugging.
2004-10-30 03:00:26 +00:00
2017-08-14 10:58:03 +00:00
Alternatively one can define \textbf { LTC\_ DEBUG} instead, which additionally defines \textit { LTC\_ NO\_ ASM} and enables debug output on test failures.
Defining \textit { LTC\_ DEBUG=2} has the effect to enable verbose output in some of the tests.
\begin { verbatim}
make LTC_ DEBUG=2
\end { verbatim}
\begin { flushleft} will build the library without compiler-optimisation or architecture specific code and will enable debugging
and verbose debug output. \end { flushleft}
2004-10-30 03:00:26 +00:00
2017-08-14 10:58:03 +00:00
\subsection { LIBNAME}
\index { LIBNAME}
\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} .
2004-10-30 03:00:26 +00:00
2005-08-01 16:36:47 +00:00
\subsection { Installation Directories}
2017-08-14 10:58:03 +00:00
\index { DESTDIR} \index { PREFIX} \index { LIBPATH} \index { INCPATH} \index { DATAPATH} \index { BINPATH}
\textbf { DESTDIR} is the location where the output will be stored. It default to an empty string.
\textbf { PREFIX} is the prefix for the installation directories. It defaults to \textit { /usr/local} .
\textbf { LIBPATH} is the location of the library directory which defaults to \textit { \$ PREFIX/lib} .
\textbf { INCPATH} is the location of the header file directory which defaults to \textit { \$ PREFIX/include} .
\textbf { DATAPATH} is the location of the data (documentation) directory which defaults to \textit { \$ PREFIX/share/doc/libtomcrypt/pdf} .
\textbf { BINPATH} is the location of the binary file directory which defaults to \textit { \$ PREFIX/bin} .
2005-08-01 16:36:47 +00:00
2017-08-14 10:58:03 +00:00
They allow to configure the installation locations of the libary.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make PREFIX=/home/tom/project DATAPATH=/home/tom/project/docs install
2005-08-01 16:36:47 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will build the library and install it to the directories under \textit { /home/tom/project/} . e.g.
2005-08-01 16:36:47 +00:00
\begin { small}
\begin { verbatim}
/home/tom/project/:
total 1
drwxr-xr-x 2 tom users 80 Jul 30 16:02 docs
drwxr-xr-x 2 tom users 528 Jul 30 16:02 include
drwxr-xr-x 2 tom users 80 Jul 30 16:02 lib
/home/tom/project/docs:
total 452
-rwxr-xr-x 1 tom users 459009 Jul 30 16:02 crypt.pdf
/home/tom/project/include:
total 132
-rwxr-xr-x 1 tom users 2482 Jul 30 16:02 tomcrypt.h
-rwxr-xr-x 1 tom users 702 Jul 30 16:02 tomcrypt_ argchk.h
-rwxr-xr-x 1 tom users 2945 Jul 30 16:02 tomcrypt_ cfg.h
-rwxr-xr-x 1 tom users 22763 Jul 30 16:02 tomcrypt_ cipher.h
-rwxr-xr-x 1 tom users 5174 Jul 30 16:02 tomcrypt_ custom.h
-rwxr-xr-x 1 tom users 11314 Jul 30 16:02 tomcrypt_ hash.h
-rwxr-xr-x 1 tom users 11571 Jul 30 16:02 tomcrypt_ mac.h
-rwxr-xr-x 1 tom users 13614 Jul 30 16:02 tomcrypt_ macros.h
-rwxr-xr-x 1 tom users 14714 Jul 30 16:02 tomcrypt_ math.h
-rwxr-xr-x 1 tom users 632 Jul 30 16:02 tomcrypt_ misc.h
-rwxr-xr-x 1 tom users 10934 Jul 30 16:02 tomcrypt_ pk.h
-rwxr-xr-x 1 tom users 2634 Jul 30 16:02 tomcrypt_ pkcs.h
-rwxr-xr-x 1 tom users 7067 Jul 30 16:02 tomcrypt_ prng.h
-rwxr-xr-x 1 tom users 1467 Jul 30 16:02 tomcrypt_ test.h
/home/tom/project/lib:
total 1073
-rwxr-xr-x 1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
\end { verbatim}
\end { small}
2017-08-14 10:58:03 +00:00
For further information see: \url { https://www.gnu.org/prep/standards/html_ node/DESTDIR.html}
and \url { https://www.freebsd.org/doc/en/books/porters-handbook/porting-prefix.html} .
2006-11-17 14:21:24 +00:00
\mysection { Extra libraries}
2005-08-01 16:36:47 +00:00
\index { EXTRALIBS}
\textbf { EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
that GCC expects for global archives.
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make install test timing CFLAGS="-DTFM_ DESC -DUSE_ TFM" EXTRALIBS=-ltfm
2005-08-01 16:36:47 +00:00
\end { verbatim}
2006-11-17 14:21:24 +00:00
This will install the library using the TomsFastMath library and link the \textit { libtfm.a} library out of the default library search path. The two
2014-08-28 12:42:19 +00:00
defines are explained below. You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
2005-08-01 16:36:47 +00:00
the \textbf { EXTRALIBS} variable by separating them by a space.
2014-08-28 12:42:19 +00:00
Note that \textbf { EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
2005-08-01 16:36:47 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Building a Static Library}
2004-10-30 03:00:26 +00:00
2014-08-28 12:42:19 +00:00
Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make install CFLAGS="-DTFM_ DESC"
2005-08-01 16:36:47 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously. You can enable
the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly, you can build the library with no built--in
math descriptors.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
make install
\end { verbatim}
2014-08-28 12:42:19 +00:00
In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
public key functions.
2005-08-01 16:36:47 +00:00
2014-08-28 12:42:19 +00:00
Note that even if you include the built--in descriptors you must link against the source library as well.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
gcc -DTFM_ DESC myprogram.c -ltomcrypt -ltfm -o myprogram
\end { verbatim}
2014-08-28 12:42:19 +00:00
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
2005-08-01 16:36:47 +00:00
giving warnings.
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Building a Shared Library}
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
LibTomCrypt can also be built as a shared library through the \textit { makefile.shared} make script. It is similar to use as the static script except
2014-08-28 12:42:19 +00:00
that you \textbf { must} specify the \textbf { EXTRALIBS} variable at install time.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make -f makefile.shared install CFLAGS="-DTFM_ DESC" EXTRALIBS=-ltfm
2005-08-01 16:36:47 +00:00
\end { verbatim}
2014-08-28 12:42:19 +00:00
This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well). The
2005-11-18 05:15:37 +00:00
shared build process requires libtool to be installed.
2004-10-30 03:00:26 +00:00
2006-12-16 18:10:04 +00:00
\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.
2003-03-03 00:59:24 +00:00
\subsubsection { ARGTYPE}
2006-12-16 18:10:04 +00:00
This lets you control how the LTC\_ ARGCHK macro will behave. The macro is used to check pointers inside the functions against
2014-08-28 12:42:19 +00:00
NULL. There are four settings for ARGTYPE. When set to 0, it will have the default behaviour of printing a message to
2006-12-16 18:10:04 +00:00
stderr and raising a SIGABRT signal. This is provided so all platforms that use LibTomCrypt can have an error that functions
similarly. When set to 1, it will simply pass on to the assert() macro. When set to 2, the macro will display the error to
2005-08-01 16:36:47 +00:00
stderr then return execution to the caller. This could lead to a segmentation fault (e.g. when a pointer is \textbf { NULL} ) but is useful
2006-12-16 18:10:04 +00:00
if you handle signals on your own. When set to 3, it will resolve to a empty macro and no error checking will be performed. Finally, when set
2014-08-28 12:42:19 +00:00
to 4, it will return CRYPT\_ INVALID\_ ARG to the caller.
2003-03-03 00:59:24 +00:00
2014-01-02 05:33:16 +00:00
\subsubsection { Endianness}
2014-04-29 13:15:54 +00:00
There are five macros related to endianness issues. For little endian platforms define, \textbf { ENDIAN\_ LITTLE} . For big endian
2006-11-17 14:21:24 +00:00
platforms define \textbf { ENDIAN\_ BIG} . Similarly when the default word size of an \textit { unsigned long} is 32-bits define \textbf { ENDIAN\_ 32BITWORD}
2005-08-01 16:36:47 +00:00
or define \textbf { ENDIAN\_ 64BITWORD} when its 64-bits. If you do not define any of them the library will automatically use \textbf { ENDIAN\_ NEUTRAL}
2004-10-30 03:00:26 +00:00
which will work on all platforms.
2014-08-28 12:42:19 +00:00
Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.
2003-03-03 00:59:24 +00:00
2014-04-29 13:15:54 +00:00
\mysection { Customisation}
2006-12-16 18:10:04 +00:00
There are also options you can specify from the \textit { tomcrypt\_ custom.h} header file.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { X memory routines}
2017-08-14 10:58:03 +00:00
\index { XMALLOC} \index { XREALLOC} \index { XCALLOC} \index { XFREE} \index { XMEMSET} \index { XMEMCPY} \index { XMEMMOVE} \index { XMEMCMP} \index { XSTRCMP}
2014-08-28 12:42:19 +00:00
At the top of tomcrypt\_ custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on. They resolve to
the name of the respective functions from the standard C library by default. This lets you substitute in your own memory routines.
If you substitute in your own functions they must behave like the standard C library functions in terms of what they expect as input and
2006-12-16 18:10:04 +00:00
output.
2017-08-14 10:58:03 +00:00
These macros are handy for working with platforms which do not have a standard C library.
For instance, the OLPC\footnote { See \url { http://dev.laptop.org/git?p=bios-crypto;a=summary} }
2006-12-16 18:10:04 +00:00
bios code uses these macros to redirect to very compact heap and string operations.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { X clock routines}
2003-03-03 00:59:24 +00:00
The rng\_ get\_ bytes() function can call a function that requires the clock() function. These macros let you override
the default clock() used with a replacement. By default the standard C library clock() function is used.
2006-12-16 18:10:04 +00:00
\subsection { LTC\_ NO\_ FILE}
2014-08-28 12:42:19 +00:00
During the build if LTC\_ NO\_ FILE is defined then any function in the library that uses file I/O will not call the file I/O
2004-10-30 03:00:26 +00:00
functions and instead simply return CRYPT\_ NOP. This should help resolve any linker errors stemming from a lack of
2003-03-03 00:59:24 +00:00
file I/O on embedded platforms.
2006-12-16 18:10:04 +00:00
\subsection { LTC\_ CLEAN\_ STACK}
2014-08-28 12:42:19 +00:00
When this functions is defined the functions that store key material on the stack will clean up afterwards.
2004-10-30 03:00:26 +00:00
Assumes that you have no memory paging with the stack.
2005-04-17 11:37:13 +00:00
\subsection { LTC\_ TEST}
2006-12-16 18:10:04 +00:00
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.
2005-04-17 11:37:13 +00:00
2006-12-16 18:10:04 +00:00
\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.
2003-03-03 00:59:24 +00:00
2005-04-17 11:37:13 +00:00
\subsection { LTC\_ FAST}
2014-08-28 12:42:19 +00:00
This mode (auto-detected with x86\_ 32, x86\_ 64 platforms with GCC or CLANG) configures various routines such as ctr\_ encrypt() or
cbc\_ encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
cutting down the overhead of the respective functions.
2005-04-17 11:37:13 +00:00
This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_ FAST
2006-11-17 14:21:24 +00:00
is not \textit { portable} since unaligned accesses are not covered by the ISO C specifications.
2005-04-17 11:37:13 +00:00
In practice however, you can use it on pretty much any platform (even MIPS) with care.
2006-11-17 14:21:24 +00:00
By design the \textit { fast} mode functions won't get unaligned on their own. For instance, if you call ctr\_ encrypt() right after calling
2014-08-28 12:42:19 +00:00
ctr\_ start() and all the inputs you gave are aligned than ctr\_ encrypt() will perform aligned memory operations only. However, if you
2005-04-17 11:37:13 +00:00
call ctr\_ encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
2014-08-28 12:42:19 +00:00
cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
2005-04-17 11:37:13 +00:00
whole word XOR operations. These operations will be unaligned.
2014-08-28 12:42:19 +00:00
The simplest precaution is to make sure you process all data in power of two blocks and handle \textit { remainder} at the end. e.g. If you are
CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.
2005-04-17 11:37:13 +00:00
2006-12-16 18:10:04 +00:00
\index { LTC\_ FAST\_ TYPE}
2014-04-29 13:15:54 +00:00
If you do plan on using the \textit { LTC\_ FAST} mode, a \textit { LTC\_ FAST\_ TYPE} type which resolves to an optimal sized
2014-08-28 12:42:19 +00:00
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
2005-04-17 11:37:13 +00:00
use this mode. So sad.
2006-12-16 18:10:04 +00:00
\subsection { LTC\_ NO\_ ASM}
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
2014-08-28 12:42:19 +00:00
cannot handle all of the assembler functions.
2006-12-16 18:10:04 +00:00
\subsection { Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
2014-08-28 12:42:19 +00:00
There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
2006-12-16 18:10:04 +00:00
cipher and a hash function.
Also see technical note number five for more details.
\subsection { LTC\_ EASY}
2014-08-28 12:42:19 +00:00
When defined the library is configured to build fewer algorithms and modes. Mostly it sticks to NIST and ANSI approved algorithms. See
the header file \textit { tomcrypt\_ custom.h} for more details. It is meant to provide literally an easy method of trimming the library
2006-12-16 18:10:04 +00:00
build to the most minimum of useful functionality.
\subsection { TWOFISH\_ SMALL and TWOFISH\_ TABLES}
Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
2014-08-28 12:42:19 +00:00
to allow some trade-offs in the implementation. When TWOFISH\_ SMALL is defined the scheduled symmetric key for Twofish
requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
tables at a cost of 4KB of memory. The cipher will be much faster as a result.
2006-12-16 18:10:04 +00:00
When TWOFISH\_ TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
useful when TWOFISH\_ SMALL is defined as the table values are computed on the fly. When this is defined the code size
will increase by approximately 500 bytes. If this is defined but TWOFISH\_ SMALL is not the cipher will still work but
it will not speed up the encryption or decryption functions.
\subsection { GCM\_ TABLES}
2014-08-28 12:42:19 +00:00
When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
It also increases the initialization time and is not suitable when you are going to use a key a few times only.
2006-12-16 18:10:04 +00:00
\subsection { GCM\_ TABLES\_ SSE2}
\index { SSE2}
When defined GCM will use the SSE2 instructions to perform the $ GF ( 2 ^ x ) $ multiply using 16 128--bit XOR operations. It shaves a few cycles per byte
of GCM output on both the AMD64 and Intel Pentium 4 platforms. Requires GCC and an SSE2 equipped platform.
\subsection { LTC\_ SMALL\_ CODE}
When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
These variants are slower but can save quite a bit of code space.
2005-06-27 11:47:35 +00:00
\subsection { LTC\_ PTHREAD}
2014-08-28 12:42:19 +00:00
When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
2005-06-27 11:47:35 +00:00
it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
Generally the rule of thumb is to setup the tables once at startup and then leave them be. This added build flag simply makes updating
the tables safer.
2005-08-01 16:36:47 +00:00
\subsection { LTC\_ ECC\_ TIMING\_ RESISTANT}
2006-11-17 14:21:24 +00:00
When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
2005-08-01 16:36:47 +00:00
algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
where timing side channels pose a significant threat.
2004-10-30 03:00:26 +00:00
2017-08-14 10:58:03 +00:00
This is enabled by default and can be disabled by defining \textbf { LTC\_ NO\_ ECC\_ TIMING\_ RESISTANT} .
\subsection { LTC\_ RSA\_ BLINDING}
When this has been defined the RSA modular exponentiation will use a blinding algorithm to improve timing resistance.
This is enabled by default and can be disabled by defining \textbf { LTC\_ NO\_ RSA\_ BLINDING} .
\subsection { LTC\_ RSA\_ CRT\_ HARDENING}
When this has been defined the RSA modular exponentiation will do some sanity checks regarding the CRT parameters and the operations' results.
This is enabled by default and can be disabled by defining \textbf { LTC\_ NO\_ RSA\_ CRT\_ HARDENING} .
2005-08-01 16:36:47 +00:00
\subsection { Math Descriptors}
2006-12-16 18:10:04 +00:00
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.
2005-08-01 16:36:47 +00:00
2006-12-16 18:10:04 +00:00
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.
2005-08-01 16:36:47 +00:00
2006-12-16 18:10:04 +00:00
\index { GMP\_ DESC} \index { USE\_ GMP} \index { LTM\_ DESC} \index { TFM\_ DESC} \index { USE\_ LTM} \index { USE\_ TFM}
2005-08-01 16:36:47 +00:00
\begin { small}
\begin { verbatim}
2017-08-14 10:58:03 +00:00
make -f makefile.shared install timing CFLAGS="-DGMP_ DESC -DLTM_ DESC -DTFM_ DESC -DUSE_ TFM" \
EXTRALIBS="-lgmp -ltommath -ltfm"
2005-08-01 16:36:47 +00:00
\end { verbatim}
\end { small}
2014-08-28 12:42:19 +00:00
That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.
2004-10-30 03:00:26 +00:00
2005-04-17 11:37:13 +00:00
\chapter { Optimizations}
2006-11-17 14:21:24 +00:00
\mysection { Introduction}
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
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
2005-04-17 11:37:13 +00:00
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...
2006-12-16 18:10:04 +00:00
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
2005-04-17 11:37:13 +00:00
the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
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
2006-12-16 18:10:04 +00:00
development simple. In most dependent routines all an end developer has to do is register\_ XXX() the descriptor and they are set.
2005-04-17 11:37:13 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Ciphers}
2005-04-17 11:37:13 +00:00
The ciphers in LibTomCrypt are accessed through the ltc\_ cipher\_ descriptor structure.
2006-12-16 18:10:04 +00:00
\label { sec:cipherdesc}
2005-04-17 11:37:13 +00:00
\begin { small}
\begin { verbatim}
struct ltc_ cipher_ descriptor {
/** name of cipher */
char *name;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** internal ID */
unsigned char ID;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** min keysize (octets) */
2014-08-28 12:42:19 +00:00
int min_ key_ length,
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** max keysize (octets) */
2014-08-28 12:42:19 +00:00
max_ key_ length,
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** block size (octets) */
2014-08-28 12:42:19 +00:00
block_ length,
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** default number of rounds */
default_ rounds;
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
/** Setup the cipher
2005-04-17 11:37:13 +00:00
@param key The input symmetric key
@param keylen The length of the input key (octets)
@param num_ rounds The requested number of rounds (0==default)
@param skey [out] The destination of the scheduled key
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*setup)(const unsigned char *key,
int keylen,
int num_ rounds,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Encrypt a block
@param pt The plaintext
@param ct [out] The ciphertext
@param skey The scheduled key
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*ecb_ encrypt)(const unsigned char *pt,
unsigned char *ct,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Decrypt a block
@param ct The ciphertext
@param pt [out] The plaintext
@param skey The scheduled key
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*ecb_ decrypt)(const unsigned char *ct,
unsigned char *pt,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
/** Test the block cipher
2014-08-28 12:42:19 +00:00
@return CRYPT_ OK if successful,
2006-12-16 18:10:04 +00:00
CRYPT_ NOP if self-testing has been disabled
2005-04-17 11:37:13 +00:00
*/
int (*test)(void);
2005-11-18 05:15:37 +00:00
2014-08-28 12:42:19 +00:00
/** Terminate the context
2005-11-18 05:15:37 +00:00
@param skey The scheduled key
*/
2014-08-28 12:42:19 +00:00
void (*done)(symmetric_ key *skey);
2005-11-18 05:15:37 +00:00
2005-04-17 11:37:13 +00:00
/** Determine a key size
2014-08-28 12:42:19 +00:00
@param keysize [in/out] The size of the key desired
2006-12-16 18:10:04 +00:00
The suggested size
2005-04-17 11:37:13 +00:00
@return CRYPT_ OK if successful
*/
int (*keysize)(int *keysize);
/** Accelerators **/
2014-08-28 12:42:19 +00:00
/** Accelerated ECB encryption
2005-04-17 11:37:13 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*accel_ ecb_ encrypt)(const unsigned char *pt,
unsigned char *ct,
unsigned long blocks,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated ECB decryption
2005-04-17 11:37:13 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*accel_ ecb_ decrypt)(const unsigned char *ct,
unsigned char *pt,
unsigned long blocks,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated CBC encryption
2005-04-17 11:37:13 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*accel_ cbc_ encrypt)(const unsigned char *pt,
unsigned char *ct,
unsigned long blocks,
unsigned char *IV,
2005-11-18 05:15:37 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated CBC decryption
2005-04-17 11:37:13 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*accel_ cbc_ decrypt)(const unsigned char *ct,
unsigned char *pt,
unsigned long blocks,
unsigned char *IV,
2005-11-18 05:15:37 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated CTR encryption
2005-04-17 11:37:13 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param mode little or big endian counter (mode=0 or mode=1)
@param skey The scheduled key context
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK if successful
2005-04-17 11:37:13 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*accel_ ctr_ encrypt)(const unsigned char *pt,
unsigned char *ct,
unsigned long blocks,
unsigned char *IV,
int mode,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated LRW
2006-01-26 18:11:56 +00:00
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*accel_ lrw_ encrypt)(const unsigned char *pt,
unsigned char *ct,
unsigned long blocks,
unsigned char *IV,
const unsigned char *tweak,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2006-01-26 18:11:56 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated LRW
2006-01-26 18:11:56 +00:00
@param ct Ciphertext
@param pt Plaintext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*accel_ lrw_ decrypt)(const unsigned char *ct,
unsigned char *pt,
unsigned long blocks,
unsigned char *IV,
const unsigned char *tweak,
2006-12-16 18:10:04 +00:00
symmetric_ key *skey);
2006-01-26 18:11:56 +00:00
2005-04-17 11:37:13 +00:00
/** Accelerated CCM packet (one-shot)
@param key The secret key to use
@param keylen The length of the secret key (octets)
2006-12-16 18:10:04 +00:00
@param uskey A previously scheduled key [can be NULL]
2005-04-17 11:37:13 +00:00
@param nonce The session nonce [use once]
@param noncelen The length of the nonce
@param header The header for the session
@param headerlen The length of the header (octets)
@param pt [out] The plaintext
@param ptlen The length of the plaintext (octets)
@param ct [out] The ciphertext
@param tag [out] The destination tag
2014-08-28 12:42:19 +00:00
@param taglen [in/out] The max size and resulting size
2006-12-16 18:10:04 +00:00
of the authentication tag
2005-04-17 11:37:13 +00:00
@param direction Encrypt or Decrypt direction (0 or 1)
@return CRYPT_ OK if successful
*/
2005-11-18 05:15:37 +00:00
int (*accel_ ccm_ memory)(
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
2005-11-18 05:15:37 +00:00
symmetric_ key *uskey,
2005-04-17 11:37:13 +00:00
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated GCM packet (one shot)
2006-12-16 18:10:04 +00:00
@param key The secret key
@param keylen The length of the secret key
2017-09-20 11:54:42 +00:00
@param IV The initialization vector
@param IVlen The length of the initialization vector
2006-12-16 18:10:04 +00:00
@param adata The additional authentication data (header)
@param adatalen The length of the adata
@param pt The plaintext
@param ptlen The length of the plaintext/ciphertext
@param ct The ciphertext
@param tag [out] The MAC tag
@param taglen [in/out] The MAC tag length
@param direction Encrypt or Decrypt mode (GCM_ ENCRYPT or GCM_ DECRYPT)
2005-11-18 05:15:37 +00:00
@return CRYPT_ OK on success
2005-04-17 11:37:13 +00:00
*/
2005-11-18 05:15:37 +00:00
int (*accel_ gcm_ memory)(
2005-04-17 11:37:13 +00:00
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
2014-08-28 12:42:19 +00:00
unsigned char *ct,
2005-04-17 11:37:13 +00:00
unsigned char *tag, unsigned long *taglen,
int direction);
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
/** Accelerated one shot OMAC
2006-12-16 18:10:04 +00:00
@param key The secret key
2014-08-28 12:42:19 +00:00
@param keylen The key length (octets)
@param in The message
2006-12-16 18:10:04 +00:00
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_ OK on success
*/
int (*omac_ memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2014-08-28 12:42:19 +00:00
/** Accelerated one shot XCBC
2006-12-16 18:10:04 +00:00
@param key The secret key
2014-08-28 12:42:19 +00:00
@param keylen The key length (octets)
@param in The message
2006-12-16 18:10:04 +00:00
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_ OK on success
*/
int (*xcbc_ memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
2014-08-28 12:42:19 +00:00
/** Accelerated one shot F9
2006-12-16 18:10:04 +00:00
@param key The secret key
2014-08-28 12:42:19 +00:00
@param keylen The key length (octets)
@param in The message
2006-12-16 18:10:04 +00:00
@param inlen Length of message (octets)
@param out [out] Destination for tag
@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);
2005-04-17 11:37:13 +00:00
} ;
\end { verbatim}
\end { small}
\subsection { Name}
2005-08-01 16:36:47 +00:00
\index { find\_ cipher()}
2006-11-17 14:21:24 +00:00
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
2005-04-17 11:37:13 +00:00
tables.
\subsection { Internal ID}
2006-11-17 14:21:24 +00:00
This is a single byte Internal ID you can use to distinguish ciphers from each other.
2005-04-17 11:37:13 +00:00
\subsection { Key Lengths}
2006-11-17 14:21:24 +00:00
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
2005-04-17 11:37:13 +00:00
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}
2006-11-17 14:21:24 +00:00
The size of the ciphers plaintext or ciphertext is \textit { block\_ length} and is measured in octets.
2005-04-17 11:37:13 +00:00
\subsection { Rounds}
2006-11-17 14:21:24 +00:00
Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit { default\_ rounds} .
2005-04-17 11:37:13 +00:00
\subsection { Setup}
2006-11-17 14:21:24 +00:00
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} .
2005-04-17 11:37:13 +00:00
2006-12-16 18:10:04 +00:00
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
2006-11-17 14:21:24 +00:00
ones provided. Just make sure in your \textit { done()} function that you free the allocated memory.
2005-04-17 11:37:13 +00:00
\subsection { Single block ECB}
2014-08-28 12:42:19 +00:00
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
2005-04-17 11:37:13 +00:00
must make sure you do not overwrite the output before you are finished with the input.
\subsection { Testing}
2006-12-16 18:10:04 +00:00
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.
2005-04-17 11:37:13 +00:00
\subsection { Key Sizing}
2014-08-28 12:42:19 +00:00
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
2005-04-17 11:37:13 +00:00
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
2006-11-17 14:21:24 +00:00
it is not supported. In those cases the software defaults are used (using the single ECB block routines).
2005-04-17 11:37:13 +00:00
\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
2006-11-17 14:21:24 +00:00
through the accel\_ ecb\_ encrypt and accel\_ ecb\_ decrypt pointers. The \textit { blocks} count is the number of complete blocks to process.
2005-04-17 11:37:13 +00:00
2014-08-28 12:42:19 +00:00
\subsubsection { Accelerated CBC}
2005-04-17 11:37:13 +00:00
These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_ cbc\_ encrypt and accel\_ cbc\_ decrypt pointers.
2017-09-20 11:54:42 +00:00
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
2014-08-28 12:42:19 +00:00
updated by the function before returning.
2005-04-17 11:37:13 +00:00
\subsubsection { Accelerated CTR}
This function is meant for accelerated CTR encryption. It is accessible through the accel\_ ctr\_ encrypt pointer.
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
updated by the function before returning. The \textit { mode} value indicates whether the counter is big (mode = CTR\_ COUNTER\_ BIG\_ ENDIAN) or
2005-06-09 00:08:13 +00:00
little (mode = CTR\_ COUNTER\_ LITTLE\_ ENDIAN) endian.
2005-04-17 11:37:13 +00:00
This function (and the way it's called) differs from the other two since ctr\_ encrypt() allows any size input plaintext. The accelerator will only be
called if the following conditions are met.
\begin { enumerate}
\item The accelerator is present
\item The CTR pad is empty
\item The remaining length of the input to process is greater than or equal to the block size.
\end { enumerate}
2014-08-28 12:42:19 +00:00
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.
2005-04-17 11:37:13 +00:00
The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
2006-01-26 18:11:56 +00:00
\subsubsection { Accelerated LRW}
2006-11-17 14:21:24 +00:00
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
2006-01-26 18:11:56 +00:00
to use accelerators for LRW.
While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_ setiv() more efficient.
2014-08-28 12:42:19 +00:00
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
2006-01-26 18:11:56 +00:00
if your device requires any (LRW specific) resources you should free them in your ciphers() done function. The simplest way to think of it is to write
the plugin solely to do LRW with the cipher. That way cipher\_ descriptor[].setup() means to init LRW resources and cipher\_ descriptor[].done() means to
free them.
2005-04-17 11:37:13 +00:00
\subsubsection { Accelerated CCM}
2005-11-18 05:15:37 +00:00
This function is meant for accelerated CCM encryption or decryption. It processes the entire packet in one call. You can optimize the work flow somewhat
2014-08-28 12:42:19 +00:00
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
2005-11-18 05:15:37 +00:00
function MUST support both key passing methods.
\begin { center}
\begin { small}
\begin { tabular} { |r|r|l|}
\hline \textbf { key} & \textbf { uskey} & \textbf { Source of key} \\
\hline NULL & NULL & Error, not supported \\
\hline non-NULL & NULL & Use key, do a key schedule \\
\hline NULL & non-NULL & Use uskey, key schedule not required \\
\hline non-NULL & non-NULL & Use uskey, key schedule not required \\
\hline
\end { tabular}
\end { small}
\end { center}
2005-04-17 11:37:13 +00:00
2006-12-16 18:10:04 +00:00
\index { ccm\_ memory()} This function is called when the user calls ccm\_ memory().
2005-04-17 11:37:13 +00:00
\subsubsection { Accelerated GCM}
2006-12-16 18:10:04 +00:00
\index { gcm\_ memory()}
2005-04-17 11:37:13 +00:00
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
2006-12-16 18:10:04 +00:00
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().
\subsubsection { Accelerated OMAC}
\index { omac\_ memory()}
2014-08-28 12:42:19 +00:00
This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_ memory().
2006-12-16 18:10:04 +00:00
\subsubsection { Accelerated XCBC-MAC}
\index { xcbc\_ memory()}
2014-08-28 12:42:19 +00:00
This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_ memory().
2006-12-16 18:10:04 +00:00
\subsubsection { Accelerated F9}
\index { f9\_ 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.
2005-04-17 11:37:13 +00:00
2006-11-17 14:21:24 +00:00
\mysection { One--Way Hashes}
2005-04-17 11:37:13 +00:00
The hash functions are accessed through the ltc\_ hash\_ descriptor structure.
\begin { small}
\begin { verbatim}
struct ltc_ hash_ descriptor {
/** name of hash */
char *name;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** internal ID */
unsigned char ID;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Size of digest in octets */
unsigned long hashsize;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Input block size in octets */
unsigned long blocksize;
2006-12-16 18:10:04 +00:00
2005-06-09 00:08:13 +00:00
/** ASN.1 OID */
unsigned long OID[16];
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Length of DER encoding */
2005-06-09 00:08:13 +00:00
unsigned long OIDlen;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Init a hash state
@param hash The hash to initialize
@return CRYPT_ OK if successful
*/
int (*init)(hash_ state *hash);
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
/** Process a block of data
2005-04-17 11:37:13 +00:00
@param hash The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*process)( hash_ state *hash,
const unsigned char *in,
2006-12-16 18:10:04 +00:00
unsigned long inlen);
2005-04-17 11:37:13 +00:00
/** Produce the digest and store it
@param hash The hash state
@param out [out] The destination of the digest
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*done)( hash_ state *hash,
2006-12-16 18:10:04 +00:00
unsigned char *out);
2005-04-17 11:37:13 +00:00
/** Self-test
2014-08-28 12:42:19 +00:00
@return CRYPT_ OK if successful,
2006-12-16 18:10:04 +00:00
CRYPT_ NOP if self-tests have been disabled
2005-04-17 11:37:13 +00:00
*/
int (*test)(void);
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
/* accelerated hmac callback: if you need to-do
multiple packets just use the generic hmac_ memory
and provide a hash callback
2006-12-16 18:10:04 +00:00
*/
2014-08-28 12:42:19 +00:00
int (*hmac_ block)(const unsigned char *key,
2006-12-16 18:10:04 +00:00
unsigned long keylen,
2014-08-28 12:42:19 +00:00
const unsigned char *in,
unsigned long inlen,
unsigned char *out,
2006-12-16 18:10:04 +00:00
unsigned long *outlen);
2005-04-17 11:37:13 +00:00
} ;
\end { verbatim}
\end { small}
\subsection { Name}
This is the name the hash is known by and what find\_ hash() will look for.
\subsection { Internal ID}
This is the internal ID byte used to distinguish the hash from other hashes.
\subsection { Digest Size}
2006-11-17 14:21:24 +00:00
The \textit { hashsize} variable indicates the length of the output in octets.
2005-04-17 11:37:13 +00:00
\subsection { Block Size}
2006-11-17 14:21:24 +00:00
The \textit { blocksize} variable indicates the length of input (in octets) that the hash processes in a given
invocation.
2005-04-17 11:37:13 +00:00
2005-06-09 00:08:13 +00:00
\subsection { OID Identifier}
This is the universal ASN.1 Object Identifier for the hash.
2005-04-17 11:37:13 +00:00
\subsection { Initialization}
The init function initializes the hash and prepares it to process message bytes.
\subsection { Process}
This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
guaranteed to be a multiple of the block size in length.
\subsection { Done}
The done function terminates the hash and returns the message digest.
\subsection { Acceleration}
2005-08-01 16:36:47 +00:00
A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
\subsection { HMAC Acceleration}
The hmac\_ block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_ memory() if present. If you need
to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_ memory() as provided in LibTomCrypt.
2005-04-17 11:37:13 +00:00
2006-11-17 14:21:24 +00:00
\mysection { Pseudo--Random Number Generators}
2005-04-17 11:37:13 +00:00
The pseudo--random number generators are accessible through the ltc\_ prng\_ descriptor structure.
\begin { small}
\begin { verbatim}
struct ltc_ prng_ descriptor {
/** Name of the PRNG */
char *name;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** size in bytes of exported state */
int export_ size;
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Start a PRNG state
@param prng [out] The state to initialize
@return CRYPT_ OK if successful
*/
int (*start)(prng_ state *prng);
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Add entropy to the PRNG
@param in The entropy
2006-12-16 18:10:04 +00:00
@param inlen Length of the entropy (octets)
2005-04-17 11:37:13 +00:00
@param prng The PRNG state
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*add_ entropy)(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2005-04-17 11:37:13 +00:00
/** Ready a PRNG state to read from
@param prng The PRNG state to ready
@return CRYPT_ OK if successful
*/
int (*ready)(prng_ state *prng);
2006-12-16 18:10:04 +00:00
2005-04-17 11:37:13 +00:00
/** Read from the PRNG
@param out [out] Where to store the data
@param outlen Length of data desired (octets)
@param prng The PRNG state to read from
@return Number of octets read
*/
2014-08-28 12:42:19 +00:00
unsigned long (*read)(unsigned char *out,
unsigned long outlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2005-04-17 11:37:13 +00:00
/** Terminate a PRNG state
@param prng The PRNG state to terminate
@return CRYPT_ OK if successful
*/
int (*done)(prng_ state *prng);
2006-12-16 18:10:04 +00:00
2014-08-28 12:42:19 +00:00
/** Export a PRNG state
2005-04-17 11:37:13 +00:00
@param out [out] The destination for the state
2006-12-16 18:10:04 +00:00
@param outlen [in/out] The max size and resulting size
2005-04-17 11:37:13 +00:00
@param prng The PRNG to export
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*pexport)(unsigned char *out,
unsigned long *outlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2005-04-17 11:37:13 +00:00
/** Import a PRNG state
@param in The data to import
@param inlen The length of the data to import (octets)
@param prng The PRNG to initialize/import
@return CRYPT_ OK if successful
*/
2014-08-28 12:42:19 +00:00
int (*pimport)(const unsigned char *in,
unsigned long inlen,
2006-12-16 18:10:04 +00:00
prng_ state *prng);
2005-04-17 11:37:13 +00:00
/** Self-test the PRNG
2014-08-28 12:42:19 +00:00
@return CRYPT_ OK if successful,
2006-12-16 18:10:04 +00:00
CRYPT_ NOP if self-testing has been disabled
2005-04-17 11:37:13 +00:00
*/
int (*test)(void);
} ;
\end { verbatim}
\end { small}
\subsection { Name}
The name by which find\_ prng() will find the PRNG.
\subsection { Export Size}
When an PRNG state is to be exported for future use you specify the space required in this variable.
\subsection { Start}
Initialize the PRNG and make it ready to accept entropy.
\subsection { Entropy Addition}
Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
\subsection { Ready}
This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
on the specific PRNG used.
\subsection { Read}
2014-08-28 12:42:19 +00:00
Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
2005-04-17 11:37:13 +00:00
if it does as many protocols do not retry reads and will fail on the first try.
\subsection { Done}
Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
2004-10-30 03:00:26 +00:00
2005-04-17 11:37:13 +00:00
\subsection { Exporting and Importing}
2006-11-17 14:21:24 +00:00
An exported PRNG state is data that the PRNG can later import to resume activity. They're not meant to resume \textit { the same session}
2005-04-17 11:37:13 +00:00
but should at least maintain the same level of state entropy.
2004-10-30 03:00:26 +00:00
2006-11-17 14:21:24 +00:00
\mysection { BigNum Math Descriptors}
2005-08-01 16:36:47 +00:00
The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
2006-11-17 14:21:24 +00:00
it hasn't proven hard to write \textit { glue} to use math libraries so far. The basic descriptor looks like.
2005-08-01 16:36:47 +00:00
\begin { small}
\begin { verbatim}
/** math descriptor */
typedef struct {
/** Name of the math provider */
char *name;
/** Bits per digit, amount of bits must fit in an unsigned long */
int bits_ per_ digit;
/* ---- init/deinit functions ---- */
/** initialize a bignum
@param a The number to initialize
@return CRYPT_ OK on success
*/
int (*init)(void **a);
2014-08-28 12:42:19 +00:00
/** init copy
2005-08-01 16:36:47 +00:00
@param dst The number to initialize and write to
@param src The number to copy from
@return CRYPT_ OK on success
*/
int (*init_ copy)(void **dst, void *src);
2014-08-28 12:42:19 +00:00
/** deinit
2005-08-01 16:36:47 +00:00
@param a The number to free
@return CRYPT_ OK on success
*/
void (*deinit)(void *a);
/* ---- data movement ---- */
2017-06-12 10:41:55 +00:00
/** negate
@param src The number to negate
@param dst The destination
@return CRYPT_ OK on success
*/
int (*neg)(void *src, void *dst);
2014-08-28 12:42:19 +00:00
/** copy
2005-08-01 16:36:47 +00:00
@param src The number to copy from
2014-08-28 12:42:19 +00:00
@param dst The number to write to
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
int (*copy)(void *src, void *dst);
/* ---- trivial low level functions ---- */
2014-08-28 12:42:19 +00:00
/** set small constant
2005-08-01 16:36:47 +00:00
@param a Number to write to
2017-06-12 10:41:55 +00:00
@param n Source upto bits_ per_ digit (actually meant for very small constants)
2006-11-17 14:21:24 +00:00
@return CRYPT_ OK on success
2005-08-01 16:36:47 +00:00
*/
int (*set_ int)(void *a, unsigned long n);
2014-08-28 12:42:19 +00:00
/** get small constant
2017-06-12 10:41:55 +00:00
@param a Small number to read,
only fetches up to bits_ per_ digit from the number
2006-12-16 18:10:04 +00:00
@return The lower bits_ per_ digit of the integer (unsigned)
2005-08-01 16:36:47 +00:00
*/
unsigned long (*get_ int)(void *a);
2014-08-28 12:42:19 +00:00
/** get digit n
2005-08-01 16:36:47 +00:00
@param a The number to read from
@param n The number of the digit to fetch
@return The bits_ per_ digit sized n'th digit of a
*/
2017-06-12 10:41:55 +00:00
ltc_ mp_ digit (*get_ digit)(void *a, int n);
2005-08-01 16:36:47 +00:00
/** Get the number of digits that represent the number
@param a The number to count
@return The number of digits used to represent the number
*/
int (*get_ digit_ count)(void *a);
/** compare two integers
@param a The left side integer
@param b The right side integer
2014-08-28 12:42:19 +00:00
@return LTC_ MP_ LT if a < b,
LTC_ MP_ GT if a > b and
2005-08-01 16:36:47 +00:00
LTC_ MP_ EQ otherwise. (signed comparison)
*/
int (*compare)(void *a, void *b);
2014-08-28 12:42:19 +00:00
/** compare against int
2005-08-01 16:36:47 +00:00
@param a The left side integer
@param b The right side integer (upto bits_ per_ digit)
2014-08-28 12:42:19 +00:00
@return LTC_ MP_ LT if a < b,
LTC_ MP_ GT if a > b and
2005-08-01 16:36:47 +00:00
LTC_ MP_ EQ otherwise. (signed comparison)
*/
int (*compare_ d)(void *a, unsigned long n);
/** Count the number of bits used to represent the integer
@param a The integer to count
@return The number of bits required to represent the integer
*/
int (*count_ bits)(void * a);
2014-08-28 12:42:19 +00:00
/** Count the number of LSB bits which are zero
2006-05-29 23:12:56 +00:00
@param a The integer to count
@return The number of contiguous zero LSB bits
*/
int (*count_ lsb_ bits)(void *a);
2005-08-01 16:36:47 +00:00
/** Compute a power of two
@param a The integer to store the power in
@param n The power of two you want to store (a = 2^ n)
@return CRYPT_ OK on success
*/
int (*twoexpt)(void *a , int n);
/* ---- radix conversions ---- */
2014-08-28 12:42:19 +00:00
/** read ascii string
2005-08-01 16:36:47 +00:00
@param a The integer to store into
@param str The string to read
@param radix The radix the integer has been represented in (2-64)
@return CRYPT_ OK on success
*/
int (*read_ radix)(void *a, const char *str, int radix);
/** write number to string
@param a The integer to store
@param str The destination for the string
@param radix The radix the integer is to be represented in (2-64)
@return CRYPT_ OK on success
*/
int (*write_ radix)(void *a, char *str, int radix);
2014-08-28 12:42:19 +00:00
/** get size as unsigned char string
2017-06-12 10:41:55 +00:00
@param a The integer to get the size (when stored in array of octets)
2006-12-16 18:10:04 +00:00
@return The length of the integer in octets
2005-08-01 16:36:47 +00:00
*/
unsigned long (*unsigned_ size)(void *a);
2014-08-28 12:42:19 +00:00
/** store an integer as an array of octets
2005-08-01 16:36:47 +00:00
@param src The integer to store
@param dst The buffer to store the integer in
@return CRYPT_ OK on success
*/
int (*unsigned_ write)(void *src, unsigned char *dst);
/** read an array of octets and store as integer
@param dst The integer to load
2014-08-28 12:42:19 +00:00
@param src The array of octets
@param len The number of octets
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
2014-08-28 12:42:19 +00:00
int (*unsigned_ read)( void *dst,
unsigned char *src,
2006-12-16 18:10:04 +00:00
unsigned long len);
2005-08-01 16:36:47 +00:00
/* ---- basic math ---- */
2014-08-28 12:42:19 +00:00
/** add two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
@param b The second source integer
@param c The destination of "a + b"
@return CRYPT_ OK on success
*/
int (*add)(void *a, void *b, void *c);
2014-08-28 12:42:19 +00:00
/** add two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
2014-08-28 12:42:19 +00:00
@param b The second source integer
2017-06-12 10:41:55 +00:00
(single digit of upto bits_ per_ digit in length)
2005-08-01 16:36:47 +00:00
@param c The destination of "a + b"
@return CRYPT_ OK on success
*/
int (*addi)(void *a, unsigned long b, void *c);
2014-08-28 12:42:19 +00:00
/** subtract two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
@param b The second source integer
@param c The destination of "a - b"
@return CRYPT_ OK on success
*/
int (*sub)(void *a, void *b, void *c);
2014-08-28 12:42:19 +00:00
/** subtract two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
2014-08-28 12:42:19 +00:00
@param b The second source integer
2006-12-16 18:10:04 +00:00
(single digit of upto bits_ per_ digit in length)
2005-08-01 16:36:47 +00:00
@param c The destination of "a - b"
@return CRYPT_ OK on success
*/
int (*subi)(void *a, unsigned long b, void *c);
2014-08-28 12:42:19 +00:00
/** multiply two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
2014-08-28 12:42:19 +00:00
@param b The second source integer
2006-12-16 18:10:04 +00:00
(single digit of upto bits_ per_ digit in length)
2005-08-01 16:36:47 +00:00
@param c The destination of "a * b"
@return CRYPT_ OK on success
*/
int (*mul)(void *a, void *b, void *c);
2014-08-28 12:42:19 +00:00
/** multiply two integers
2005-08-01 16:36:47 +00:00
@param a The first source integer
2014-08-28 12:42:19 +00:00
@param b The second source integer
2006-12-16 18:10:04 +00:00
(single digit of upto bits_ per_ digit in length)
2005-08-01 16:36:47 +00:00
@param c The destination of "a * b"
@return CRYPT_ OK on success
*/
int (*muli)(void *a, unsigned long b, void *c);
/** Square an integer
@param a The integer to square
@param b The destination
@return CRYPT_ OK on success
*/
int (*sqr)(void *a, void *b);
/** Divide an integer
@param a The dividend
@param b The divisor
@param c The quotient (can be NULL to signify don't care)
@param d The remainder (can be NULL to signify don't care)
@return CRYPT_ OK on success
*/
2017-06-12 10:41:55 +00:00
int (*mpdiv)(void *a, void *b, void *c, void *d);
2005-08-01 16:36:47 +00:00
2014-08-28 12:42:19 +00:00
/** divide by two
2005-08-01 16:36:47 +00:00
@param a The integer to divide (shift right)
2014-08-28 12:42:19 +00:00
@param b The destination
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
int (*div_ 2)(void *a, void *b);
/** Get remainder (small value)
@param a The integer to reduce
@param b The modulus (upto bits_ per_ digit in length)
@param c The destination for the residue
@return CRYPT_ OK on success
*/
int (*modi)(void *a, unsigned long b, unsigned long *c);
2014-08-28 12:42:19 +00:00
/** gcd
2005-08-01 16:36:47 +00:00
@param a The first integer
@param b The second integer
@param c The destination for (a, b)
@return CRYPT_ OK on success
*/
int (*gcd)(void *a, void *b, void *c);
2014-08-28 12:42:19 +00:00
/** lcm
2005-08-01 16:36:47 +00:00
@param a The first integer
@param b The second integer
@param c The destination for [a, b]
@return CRYPT_ OK on success
*/
int (*lcm)(void *a, void *b, void *c);
/** Modular multiplication
@param a The first source
2014-08-28 12:42:19 +00:00
@param b The second source
2005-08-01 16:36:47 +00:00
@param c The modulus
@param d The destination (a*b mod c)
@return CRYPT_ OK on success
*/
int (*mulmod)(void *a, void *b, void *c, void *d);
2006-06-18 01:37:50 +00:00
/** Modular squaring
@param a The first source
@param b The modulus
@param c The destination (a*a mod b)
@return CRYPT_ OK on success
*/
int (*sqrmod)(void *a, void *b, void *c);
2005-08-01 16:36:47 +00:00
/** Modular inversion
@param a The value to invert
2014-08-28 12:42:19 +00:00
@param b The modulus
2005-08-01 16:36:47 +00:00
@param c The destination (1/a mod b)
@return CRYPT_ OK on success
*/
int (*invmod)(void *, void *, void *);
/* ---- reduction ---- */
2006-11-17 14:21:24 +00:00
/** setup Montgomery
2014-08-28 12:42:19 +00:00
@param a The modulus
@param b The destination for the reduction digit
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
int (*montgomery_ setup)(void *a, void **b);
2014-08-28 12:42:19 +00:00
/** get normalization value
2005-08-01 16:36:47 +00:00
@param a The destination for the normalization value
@param b The modulus
@return CRYPT_ OK on success
*/
int (*montgomery_ normalization)(void *a, void *b);
/** reduce a number
@param a The number [and dest] to reduce
@param b The modulus
@param c The value "b" from montgomery_ setup()
@return CRYPT_ OK on success
*/
int (*montgomery_ reduce)(void *a, void *b, void *c);
/** clean up (frees memory)
@param a The value "b" from montgomery_ setup()
@return CRYPT_ OK on success
2014-08-28 12:42:19 +00:00
*/
2005-08-01 16:36:47 +00:00
void (*montgomery_ deinit)(void *a);
/* ---- exponentiation ---- */
/** Modular exponentiation
@param a The base integer
@param b The power (can be negative) integer
@param c The modulus integer
@param d The destination
@return CRYPT_ OK on success
*/
int (*exptmod)(void *a, void *b, void *c, void *d);
/** Primality testing
@param a The integer to test
2017-06-12 10:41:55 +00:00
@param b The number of Miller-Rabin tests that shall be executed
@param c The destination of the result (FP_ YES if prime)
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
2017-06-12 10:41:55 +00:00
int (*isprime)(void *a, int b, int *c);
2005-08-01 16:36:47 +00:00
/* ---- (optional) ecc point math ---- */
/** ECC GF(p) point multiplication (from the NIST curves)
@param k The integer to multiply the point by
@param G The point to multiply
2014-08-28 12:42:19 +00:00
@param R The destination for kG
2005-08-01 16:36:47 +00:00
@param modulus The modulus for the field
2014-08-28 12:42:19 +00:00
@param map Boolean indicated whether to map back to affine or not
2006-12-16 18:10:04 +00:00
(can be ignored if you work in affine only)
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
2014-08-28 12:42:19 +00:00
int (*ecc_ ptmul)( void *k,
ecc_ point *G,
ecc_ point *R,
void *modulus,
2006-12-16 18:10:04 +00:00
int map);
2005-08-01 16:36:47 +00:00
2014-08-28 12:42:19 +00:00
/** ECC GF(p) point addition
2005-08-01 16:36:47 +00:00
@param P The first point
@param Q The second point
@param R The destination of P + Q
@param modulus The modulus
@param mp The "b" value from montgomery_ setup()
@return CRYPT_ OK on success
*/
2014-08-28 12:42:19 +00:00
int (*ecc_ ptadd)(ecc_ point *P,
ecc_ point *Q,
ecc_ point *R,
void *modulus,
2006-12-16 18:10:04 +00:00
void *mp);
2005-08-01 16:36:47 +00:00
2014-08-28 12:42:19 +00:00
/** ECC GF(p) point double
2006-04-06 19:48:32 +00:00
@param P The first point
@param R The destination of 2P
@param modulus The modulus
@param mp The "b" value from montgomery_ setup()
@return CRYPT_ OK on success
*/
2014-08-28 12:42:19 +00:00
int (*ecc_ ptdbl)(ecc_ point *P,
ecc_ point *R,
void *modulus,
2006-12-16 18:10:04 +00:00
void *mp);
2006-04-06 19:48:32 +00:00
2014-08-28 12:42:19 +00:00
/** ECC mapping from projective to affine,
2006-12-16 18:10:04 +00:00
currently uses (x,y,z) => (x/z^ 2, y/z^ 3, 1)
2005-08-01 16:36:47 +00:00
@param P The point to map
@param modulus The modulus
@param mp The "b" value from montgomery_ setup()
@return CRYPT_ OK on success
2014-08-28 12:42:19 +00:00
@remark The mapping can be different but keep in mind a
ecc_ point only has three integers (x,y,z) so if
2006-12-16 18:10:04 +00:00
you use a different mapping you have to make it fit.
2005-08-01 16:36:47 +00:00
*/
int (*ecc_ map)(ecc_ point *P, void *modulus, void *mp);
2006-12-16 18:10:04 +00:00
/** Computes kA*A + kB*B = C using Shamir's Trick
@param A First point to multiply
@param kA What to multiple A by
@param B Second point to multiply
@param kB What to multiple B by
@param C [out] Destination point (can overlap with A or B)
2014-08-28 12:42:19 +00:00
@param modulus Modulus for curve
2006-12-16 18:10:04 +00:00
@return CRYPT_ OK on success
2014-08-28 12:42:19 +00:00
*/
2006-12-16 18:10:04 +00:00
int (*ecc_ mul2add)(ecc_ point *A, void *kA,
ecc_ point *B, void *kB,
ecc_ point *C,
void *modulus);
2005-08-01 16:36:47 +00:00
/* ---- (optional) rsa optimized math (for internal CRT) ---- */
2014-08-28 12:42:19 +00:00
/** RSA Key Generation
2005-11-18 05:15:37 +00:00
@param prng An active PRNG state
@param wprng The index of the PRNG desired
2006-12-16 18:10:04 +00:00
@param size The size of the key in octets
2014-08-28 12:42:19 +00:00
@param e The "e" value (public key).
2006-12-16 18:10:04 +00:00
e==65537 is a good choice
2005-11-18 05:15:37 +00:00
@param key [out] Destination of a newly created private key pair
@return CRYPT_ OK if successful, upon error all allocated ram is freed
*/
2014-08-28 12:42:19 +00:00
int (*rsa_ keygen)(prng_ state *prng,
int wprng,
int size,
long e,
2006-12-16 18:10:04 +00:00
rsa_ key *key);
2005-11-18 05:15:37 +00:00
2005-08-01 16:36:47 +00:00
/** RSA exponentiation
@param in The octet array representing the base
@param inlen The length of the input
@param out The destination (to be stored in an octet array format)
2014-08-28 12:42:19 +00:00
@param outlen The length of the output buffer and the resulting size
2006-12-16 18:10:04 +00:00
(zero padded to the size of the modulus)
2005-08-01 16:36:47 +00:00
@param which PK_ PUBLIC for public RSA and PK_ PRIVATE for private RSA
2014-08-28 12:42:19 +00:00
@param key The RSA key to use
2005-08-01 16:36:47 +00:00
@return CRYPT_ OK on success
*/
int (*rsa_ me)(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_ key *key);
2017-06-12 10:41:55 +00:00
/* ---- basic math continued ---- */
/** Modular addition
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a + b mod c)
@return CRYPT_ OK on success
*/
int (*addmod)(void *a, void *b, void *c, void *d);
/** Modular substraction
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a - b mod c)
@return CRYPT_ OK on success
*/
int (*submod)(void *a, void *b, void *c, void *d);
/* ---- misc stuff ---- */
/** Make a pseudo-random mpi
@param a The mpi to make random
@param size The desired length
@return CRYPT_ OK on success
*/
int (*rand)(void *a, int size);
2005-08-01 16:36:47 +00:00
} ltc_ math_ descriptor;
\end { verbatim}
\end { small}
2006-11-17 14:21:24 +00:00
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.
2005-08-01 16:36:47 +00:00
\subsection { Conventions}
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
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
2005-08-01 16:36:47 +00:00
free the bignum as well as the structure you allocated to place it in.
2014-08-28 12:42:19 +00:00
All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $ c \leftarrow ab $ .
2005-08-01 16:36:47 +00:00
All functions (except where noted otherwise) return \textbf { CRYPT\_ OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
2017-07-09 11:12:21 +00:00
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.
2005-08-01 16:36:47 +00:00
\subsection { ECC Functions}
2018-07-03 16:58:11 +00:00
The ECC system in LibTomCrypt is based off the NIST recommended curves over $ GF ( p ) $ and is used to implement ECDSA and ECDH. The ECC functions work with
the \textbf { ecc\_ point} structure and assumes the points are stored in Jacobian projective format.
2005-08-01 16:36:47 +00:00
\begin { verbatim}
2014-08-28 12:42:19 +00:00
/** A point on a ECC curve, stored in Jacobian format such
2006-11-17 14:21:24 +00:00
that (x,y,z) => (x/z^ 2, y/z^ 3, 1) when interpreted as affine */
2005-08-01 16:36:47 +00:00
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_ point;
\end { verbatim}
2006-12-16 18:10:04 +00:00
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
2018-07-03 16:58:11 +00:00
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.
2005-08-01 16:36:47 +00:00
\subsubsection { Point Multiply}
2014-08-28 12:42:19 +00:00
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.
2005-08-01 16:36:47 +00:00
\subsubsection { Point Addition}
2006-11-17 14:21:24 +00:00
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
2014-08-28 12:42:19 +00:00
may be in either affine (with $ z = 1 $ ) or projective format and the output point is always projective.
2005-08-01 16:36:47 +00:00
\subsubsection { Point Mapping}
2014-08-28 12:42:19 +00:00
This will map the point $ P $ back from projective to affine. The output point $ P $ must be of the form $ ( x, y, 1 ) $ .
2005-08-01 16:36:47 +00:00
2006-12-16 18:10:04 +00:00
\subsubsection { Shamir's Trick}
\index { Shamir's Trick}
\index { ltc\_ ecc\_ mul2add()}
2018-07-03 16:58:11 +00:00
To accelerate ECDSA verification the library provides a built--in function called ltc\_ ecc\_ mul2add(). This performs two point multiplications and an addition in
2006-12-16 18:10:04 +00:00
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
2014-08-28 12:42:19 +00:00
overlap (e.g., $ A \leftarrow k _ 1 A + k _ 2 B $ ) and must return the final point in affine format.
2006-12-16 18:10:04 +00:00
2005-08-01 16:36:47 +00:00
\subsection { RSA Functions}
The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
\begin { verbatim}
/** RSA PKCS style key */
typedef struct Rsa_ key {
/** Type of key, PK_ PRIVATE or PK_ PUBLIC */
int type;
/** The public exponent */
2014-08-28 12:42:19 +00:00
void *e;
2005-08-01 16:36:47 +00:00
/** The private exponent */
2014-08-28 12:42:19 +00:00
void *d;
2005-08-01 16:36:47 +00:00
/** The modulus */
2014-08-28 12:42:19 +00:00
void *N;
2005-08-01 16:36:47 +00:00
/** The p factor of N */
2014-08-28 12:42:19 +00:00
void *p;
2005-08-01 16:36:47 +00:00
/** The q factor of N */
2014-08-28 12:42:19 +00:00
void *q;
2005-08-01 16:36:47 +00:00
/** The 1/q mod p CRT param */
2014-08-28 12:42:19 +00:00
void *qP;
2005-08-01 16:36:47 +00:00
/** The d mod (p - 1) CRT param */
2014-08-28 12:42:19 +00:00
void *dP;
2005-08-01 16:36:47 +00:00
/** The d mod (q - 1) CRT param */
void *dQ;
} rsa_ key;
\end { verbatim}
2006-11-17 14:21:24 +00:00
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,
2005-08-01 16:36:47 +00:00
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.
2017-10-16 20:05:24 +00:00
\mysection { Deprecated API functions}
\subsection { After v1.18.0}
\index { init\_ LTM()} \index { init\_ TFM()} \index { init\_ GMP()}
\begin { verbatim}
void init_ LTM(void);
void init_ TFM(void);
void init_ GMP(void);
\end { verbatim}
These three MPI init functions have been introduced in version 1.18.0 and have been deprecated in the same version in favor of \textit { crypt\_ mp\_ init()} .
2006-11-17 14:21:24 +00:00
\newpage
\markboth { Index} { Index}
2004-05-31 02:36:47 +00:00
\input { crypt.ind}
2003-03-03 00:59:24 +00:00
\end { document}
2005-06-09 00:08:13 +00:00
2017-06-19 11:43:49 +00:00
% ref: $Format:%D$
% git commit: $Format:%H$
% commit time: $Format:%ai$