comparison libtomcrypt/doc/crypt.tex @ 1471:6dba84798cd5

Update to libtomcrypt 1.18.1, merged with Dropbear changes
author Matt Johnston <matt@ucc.asn.au>
date Fri, 09 Feb 2018 21:44:05 +0800
parents libtomcrypt/crypt.tex@f849a5ca2efc
children e9dba7abd939
comparison
equal deleted inserted replaced
1470:8bba51a55704 1471:6dba84798cd5
1 \documentclass[synpaper]{book}
2 \usepackage{geometry}
3 \usepackage{hyperref}
4 \usepackage{makeidx}
5 \usepackage{amssymb}
6 \usepackage{color}
7 \usepackage{alltt}
8 \usepackage{graphicx}
9 \usepackage{layout}
10 \usepackage{fancyhdr}
11 \usepackage{float}
12 \def\union{\cup}
13 \def\intersect{\cap}
14 \def\getsrandom{\stackrel{\rm R}{\gets}}
15 \def\cross{\times}
16 \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
17 \def\catn{$\|$}
18 \def\divides{\hspace{0.3em} | \hspace{0.3em}}
19 \def\nequiv{\not\equiv}
20 \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
21 \def\lcm{{\rm lcm}}
22 \def\gcd{{\rm gcd}}
23 \def\log{{\rm log}}
24 \def\ord{{\rm ord}}
25 \def\abs{{\mathit abs}}
26 \def\rep{{\mathit rep}}
27 \def\mod{{\mathit\ mod\ }}
28 \renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
29 \newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
30 \newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
31 \def\Or{{\rm\ or\ }}
32 \def\And{{\rm\ and\ }}
33 \def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
34 \def\implies{\Rightarrow}
35 \def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
36 \let\oldphi\phi
37 \def\phi{\varphi}
38 \def\Pr{{\rm Pr}}
39 \newcommand{\str}[1]{{\mathbf{#1}}}
40 \def\F{{\mathbb F}}
41 \def\N{{\mathbb N}}
42 \def\Z{{\mathbb Z}}
43 \def\R{{\mathbb R}}
44 \def\C{{\mathbb C}}
45 \def\Q{{\mathbb Q}}
46 \definecolor{DGray}{gray}{0.5}
47 \newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
48 \def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
49 \def\gap{\vspace{0.5ex}}
50 \makeindex
51 \newcommand{\mysection}[1] % Re-define the chaptering command to use
52 { % THESE headers.
53 \section{#1}
54 \markboth{\textsf{www.libtom.net}}{\thesection ~ {#1}}
55 }
56
57 \newcommand{\mystarsection}[1] % Re-define the chaptering command to use
58 { % THESE headers.
59 \section*{#1}
60 \markboth{\textsf{www.libtom.net}}{{#1}}
61 }
62 \pagestyle{empty}
63 \begin{document}
64 \frontmatter
65 \pagestyle{empty}
66
67 ~
68
69 \vspace{2in}
70
71 ~
72
73 \begin{center}
74 \begin{Huge}LibTomCrypt\end{Huge}
75
76 ~
77
78 \begin{large}Developer Manual\end{large}
79
80 ~
81
82 \vspace{15mm}
83
84
85 \begin{tabular}{c}
86 LibTom Projects
87 \end{tabular}
88 \end{center}
89 \vfil
90 \newpage
91 This document is part of the LibTomCrypt package and is hereby released into the public domain.
92
93 ~
94
95 Open Source. Open Academia. Open Minds.
96
97 ~
98
99 \begin{flushright}
100 LibTom Projects
101 ~
102
103 \& originally
104 ~
105
106 Tom St Denis
107 ~
108
109 Ottawa, Ontario
110 ~
111
112 Canada
113 ~
114 \vfil
115 \end{flushright}
116 \newpage
117
118 \tableofcontents
119 \listoffigures
120 \pagestyle{myheadings}
121 \mainmatter
122 \chapter{Introduction}
123 \mysection{What is the LibTomCrypt?}
124 LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
125 designing cryptosystems. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
126 public key cryptography (via PKCS \#1 RSA, DH or ECCDH), and a plethora of support routines.
127
128 The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
129 (and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
130 block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
131 also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
132
133 \mysection{Why did I write it?}
134 You may be wondering, \textit{Tom, why did you write a crypto library. I already have one.} Well the reason falls into
135 two categories:
136 \begin{enumerate}
137 \item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
138 \item It was (still is) good coding practice.
139 \end{enumerate}
140
141 The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
142 {\bf own} crypto library and hopefully along the way others will appreciate the work.
143
144 With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
145 and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
146 on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
147 know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
148 that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time. That means your
149 application can support all ciphers/hashes/prngs/bignum without changing the source code.
150
151 Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
152 configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
153 without having to use configure scripts. This means that the library will work with platforms where development
154 tools may be limited (e.g. no autoconf).
155
156 On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
157 robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
158 arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
159 with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
160 Crypto++.
161
162 \subsection{Modular}
163 The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
164 pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
165 are essentially structures with pointers to functions. While you can still call particular functions
166 directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
167 usage of the library.
168
169 For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
170 that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
171 is write a descriptor and the few support routines required for the device. After that the rest of the
172 API can make use of it without change. Similarly imagine a few years down the road when AES2
173 (\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
174 with zero modifications to the end applications provided they are written properly.
175
176 This flexibility within the library means it can be used with any combination of primitive algorithms and
177 unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
178 mode routines for every single cipher. That means every time you add or remove a cipher from the library
179 you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
180 are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
181 the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
182 can make use of the cipher right away.
183
184 \mysection{License}
185
186 The project is hereby released as public domain.
187
188 \mysection{Patent Disclosure}
189
190 The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
191 of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
192 They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}. The rest
193 of the ciphers and hashes are patent free or under patents that have since expired.
194
195 The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
196 the ciphers you just can't advertise that you are doing so.
197
198 \mysection{Thanks}
199 I would like to give thanks to the following people (in no particular order) for helping me develop this project from
200 early on:
201 \begin{enumerate}
202 \item Richard van de Laarschot
203 \item Richard Heathfield
204 \item Ajay K. Agrawal
205 \item Brian Gladman
206 \item Svante Seleborg
207 \item Clay Culver
208 \item Jason Klapste
209 \item Dobes Vandermeer
210 \item Daniel Richards
211 \item Wayne Scott
212 \item Andrew Tyler
213 \item Sky Schulz
214 \item Christopher Imes
215 \end{enumerate}
216
217 There have been quite a few other people as well. Please check the change log to see who else has contributed from
218 time to time.
219
220 \chapter{The Application Programming Interface (API)}
221 \mysection{Introduction}
222 \index{CRYPT\_ERROR} \index{CRYPT\_OK}
223
224 In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
225 that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
226 if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
227 commented upon. When a function does return a CRYPT error code it can be translated into a string with
228
229 \index{error\_to\_string()}
230 \begin{verbatim}
231 const char *error_to_string(int err);
232 \end{verbatim}
233
234 An example of handling an error is:
235 \begin{small}
236 \begin{verbatim}
237 void somefunc(void)
238 {
239 int err;
240
241 /* call a cryptographic function */
242 if ((err = some_crypto_function(...)) != CRYPT_OK) {
243 printf("A crypto error occurred, %s\n", error_to_string(err));
244 /* perform error handling */
245 }
246 /* continue on if no error occurred */
247 }
248 \end{verbatim}
249 \end{small}
250
251 There is no initialization routine for the library and for the most part the code is thread safe. The only thread
252 related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
253 that is not an issue.
254
255 To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
256 \begin{small}
257 \begin{verbatim}
258 #include <tomcrypt.h>
259 int main(void) {
260 return 0;
261 }
262 \end{verbatim}
263 \end{small}
264
265 The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
266
267 \mysection{Macros}
268
269 There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
270 32/64-bit words in little/big endian format. The macros are:
271
272 \index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
273 \newpage
274 \begin{figure}[hpbt]
275 \begin{small}
276 \begin{center}
277 \begin{tabular}{|c|c|c|}
278 \hline STORE32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
279 \hline STORE64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
280 \hline LOAD32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
281 \hline LOAD64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
282 \hline STORE32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
283 \hline STORE64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
284 \hline LOAD32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
285 \hline LOAD64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
286 \hline BSWAP(x) & {\bf ulong32} x & Swap bytes \\
287 \hline
288 \end{tabular}
289 \caption{Load And Store Macros}
290 \end{center}
291 \end{small}
292 \end{figure}
293
294 There are 32 and 64-bit cyclic rotations as well:
295 \index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
296 \begin{figure}[hpbt]
297 \begin{small}
298 \begin{center}
299 \begin{tabular}{|c|c|c|}
300 \hline ROL(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x << y, 0 \le y \le 31$ \\
301 \hline ROLc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x << y, 0 \le y \le 31$ \\
302 \hline ROR(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x >> y, 0 \le y \le 31$ \\
303 \hline RORc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x >> y, 0 \le y \le 31$ \\
304 \hline && \\
305 \hline ROL64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x << y, 0 \le y \le 63$ \\
306 \hline ROL64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x << y, 0 \le y \le 63$ \\
307 \hline ROR64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x >> y, 0 \le y \le 63$ \\
308 \hline ROR64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x >> y, 0 \le y \le 63$ \\
309 \hline
310 \end{tabular}
311 \caption{Rotate Macros}
312 \end{center}
313 \end{small}
314 \end{figure}
315
316 \mysection{Functions with Variable Length Output}
317 Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length. To prevent buffer overflows you
318 must pass it the length of the buffer where the output will be stored. For example:
319 \index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
320 \begin{small}
321 \begin{verbatim}
322 #include <tomcrypt.h>
323 int main(void) {
324 rsa_key key;
325 unsigned char buffer[1024];
326 unsigned long x;
327 int err;
328
329 /* ... Make up the RSA key somehow ... */
330
331 /* lets export the key, set x to the size of the
332 * output buffer */
333 x = sizeof(buffer);
334 if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
335 printf("Export error: %s\n", error_to_string(err));
336 return -1;
337 }
338
339 /* if rsa_export() was successful then x will have
340 * the size of the output */
341 printf("RSA exported key takes %d bytes\n", x);
342
343 /* ... do something with the buffer */
344
345 return 0;
346 }
347 \end{verbatim}
348 \end{small}
349 In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
350 indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
351 \textit{x} so that the calling application will know how many bytes were used.
352
353 As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
354 support this so please check the source before you rely on it doing that.
355
356 \mysection{Functions that need a PRNG}
357 \index{Pseudo Random Number Generator} \index{PRNG}
358 Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG). These functions do not setup
359 the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
360
361 Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example). The \textit{prng\_state} argument
362 may be passed as \textbf{NULL} in such situations.
363
364 \index{register\_prng()} \index{rsa\_make\_key()}
365 \begin{small}
366 \begin{verbatim}
367 #include <tomcrypt.h>
368 int main(void) {
369 rsa_key key;
370 int err;
371
372 /* register the system RNG */
373 register_prng(&sprng_desc)
374
375 /* make a 1024-bit RSA key with the system RNG */
376 if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key))
377 != CRYPT_OK) {
378 printf("make_key error: %s\n", error_to_string(err));
379 return -1;
380 }
381
382 /* use the key ... */
383
384 return 0;
385 }
386 \end{verbatim}
387 \end{small}
388
389 \mysection{Functions that use Arrays of Octets}
390 Most functions require inputs that are arrays of the data type \textit{unsigned char}. Whether it is a symmetric key, IV
391 for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
392 lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
393 must pass in (a pointer to) an array of 32 \textit{unsigned char} variables. Certain routines (such as SAFER+) take
394 special care to work properly on platforms where an \textit{unsigned char} is not eight bits.
395
396 For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word. Typically an array of
397 type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}
398
399 \chapter{Symmetric Block Ciphers}
400 \mysection{Core Functions}
401 LibTomCrypt provides several block ciphers with an ECB block mode interface. It is important to first note that you
402 should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
403 or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
404 the API to grow in a modular fashion.
405
406 \subsection{Key Scheduling}
407 All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}. This allows all ciphers to
408 have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
409 allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers must provide six visible
410 functions which are (given that XXX is the name of the cipher) the following:
411 \index{Cipher Setup}
412 \begin{verbatim}
413 int XXX_setup(const unsigned char *key,
414 int keylen,
415 int rounds,
416 symmetric_key *skey);
417 \end{verbatim}
418
419 The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
420 The number of rounds can be set to zero to use the default, which is generally a good idea.
421
422 If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it. It's important to note
423 that you should only used this scheduled key with the intended cipher. For example, if you call \textit{blowfish\_setup()} do not
424 pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}. All built--in setup functions do not allocate memory off the heap so
425 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
426 practices you should always call the respective XXX\_done() function. This allows for quicker porting to applications with
427 externally supplied plugins.
428
429 \subsection{ECB Encryption and Decryption}
430 To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
431 \index{Cipher Encrypt} \index{Cipher Decrypt}
432 \begin{verbatim}
433 int XXX_ecb_encrypt(const unsigned char *pt,
434 unsigned char *ct,
435 symmetric_key *skey);
436
437 int XXX_ecb_decrypt(const unsigned char *ct,
438 unsigned char *pt,
439 symmetric_key *skey);
440 \end{verbatim}
441 These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
442 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
443 the same buffer. For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
444 \textit{ct}\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
445 return \textbf{CRYPT\_OK} on success. To test a particular cipher against test vectors\footnote{As published in their design papers.}
446 call the following self-test function.
447
448 \subsection{Self--Testing}
449 \index{Cipher Testing}
450 \begin{verbatim}
451 int XXX_test(void);
452 \end{verbatim}
453 This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
454 based upon.
455
456 \subsection{Key Sizing}
457 For each cipher there is a function which will help find a desired key size. It is specified as follows:
458 \index{Key Sizing}
459 \begin{verbatim}
460 int XXX_keysize(int *keysize);
461 \end{verbatim}
462 Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size. This function
463 will return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
464 \begin{small}
465 \begin{verbatim}
466 #include <tomcrypt.h>
467 int main(void)
468 {
469 int keysize, err;
470
471 /* now given a 20 byte key what keysize does Twofish want to use? */
472 keysize = 20;
473 if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
474 printf("Error getting key size: %s\n", error_to_string(err));
475 return -1;
476 }
477 printf("Twofish suggested a key size of %d\n", keysize);
478 return 0;
479 }
480 \end{verbatim}
481 \end{small}
482 This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}
483
484 \subsection{Cipher Termination}
485 When you are finished with a cipher you can de--initialize it with the done function.
486 \begin{verbatim}
487 void XXX_done(symmetric_key *skey);
488 \end{verbatim}
489 For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
490 cipher descriptors may require to be called for resource management purposes. To be compliant, all functions which call a cipher
491 setup function must also call the respective cipher done function when finished.
492
493 \subsection{Simple Encryption Demonstration}
494 An example snippet that encodes a block with Blowfish in ECB mode.
495
496 \index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
497 \begin{small}
498 \begin{verbatim}
499 #include <tomcrypt.h>
500 int main(void)
501 {
502 unsigned char pt[8], ct[8], key[8];
503 symmetric_key skey;
504 int err;
505
506 /* ... key is loaded appropriately in key ... */
507 /* ... load a block of plaintext in pt ... */
508
509 /* schedule the key */
510 if ((err = blowfish_setup(key, /* the key we will use */
511 8, /* key is 8 bytes (64-bits) long */
512 0, /* 0 == use default # of rounds */
513 &skey) /* where to put the scheduled key */
514 ) != CRYPT_OK) {
515 printf("Setup error: %s\n", error_to_string(err));
516 return -1;
517 }
518
519 /* encrypt the block */
520 blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
521 ct, /* store encrypted data here */
522 &skey); /* our previously scheduled key */
523
524 /* now ct holds the encrypted version of pt */
525
526 /* decrypt the block */
527 blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
528 pt, /* store decrypted data here */
529 &skey); /* our previously scheduled key */
530
531 /* now we have decrypted ct to the original plaintext in pt */
532
533 /* Terminate the cipher context */
534 blowfish_done(&skey);
535
536 return 0;
537 }
538 \end{verbatim}
539 \end{small}
540
541 \mysection{Key Sizes and Number of Rounds}
542 \index{Symmetric Keys}
543 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
544 keys (mainly for test vectors anyways). Ideally, your application should be making at least 256 bit keys. This is not
545 because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
546 example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
547 total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
548 were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
549 only 53 bits of entropy.
550
551 The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
552 rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
553 ciphers are configured such that the default number of rounds provide adequate security for the given block and key
554 size.
555
556 \mysection{The Cipher Descriptors}
557 \index{Cipher Descriptor}
558 To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}. An element
559 of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
560
561 \begin{small}
562 \begin{verbatim}
563 struct _cipher_descriptor {
564 /** name of cipher */
565 char *name;
566
567 /** internal ID */
568 unsigned char ID;
569
570 /** min keysize (octets) */
571 int min_key_length,
572
573 /** max keysize (octets) */
574 max_key_length,
575
576 /** block size (octets) */
577 block_length,
578
579 /** default number of rounds */
580 default_rounds;
581 ...<snip>...
582 };
583 \end{verbatim}
584 \end{small}
585
586 Where \textit{name} is the lower case ASCII version of the name. The fields \textit{min\_key\_length} and \textit{max\_key\_length}
587 are the minimum and maximum key sizes in bytes. The \textit{block\_length} member is the block size of the cipher
588 in bytes. As a good rule of thumb it is assumed that the cipher supports
589 the min and max key lengths but not always everything in between. The \textit{default\_rounds} field is the default number
590 of rounds that will be used.
591
592 For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
593 and if missing will be emulated in software.
594
595 The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
596 marked when \textit{name} equals {\bf NULL}.
597
598 As of this release the current cipher\_descriptors elements are the following:
599 \vfil
600 \index{Cipher descriptor table}
601 \index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
602 \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}
603 \begin{figure}[hpbt]
604 \begin{small}
605 \begin{center}
606 \begin{tabular}{|c|c|c|c|c|c|}
607 \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} \\
608 \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
609 \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
610 \hline RC2 & rc2\_desc & 8 & 5 $\ldots$ 128 & 16 \\
611 \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
612 \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
613 \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
614 \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
615 & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
616 \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
617 \hline DES & des\_desc & 8 & 8 & 16 \\
618 \hline 3DES (EDE mode) & des3\_desc & 8 & 16, 24 & 16 \\
619 \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
620 \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
621 \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
622 \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
623 \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
624 \hline SEED & kseed\_desc & 16 & 16 & 16 \\
625 \hline KASUMI & kasumi\_desc & 8 & 16 & 8 \\
626 \hline Camellia & camellia\_desc & 16 & 16, 24, 32 & 18, 24 \\
627 \hline
628 \end{tabular}
629 \end{center}
630 \end{small}
631 \caption{Built--In Software Ciphers}
632 \end{figure}
633
634 \subsection{Notes}
635 \begin{small}
636 \begin{enumerate}
637 \item
638 For AES, (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
639 rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}. The descriptors aes\_desc and
640 aes\_enc\_desc provide the cipher name \textit{aes}. Functionally both \textit{rijndael} and \textit{aes} are the same cipher. The
641 only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with \textit{enc}
642 in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
643 and tables. The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
644 should not be called.
645
646 The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
647 as EAX, PMAC and OMAC only require the encryption function. So far this \textit{encrypt only} functionality has only been implemented for
648 Rijndael as it makes the most sense for this cipher.
649
650 \item
651 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
652 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
653 byte string from the real 7/21 byte key.
654
655 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.
656
657 \item
658 Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time. These options are found in
659 the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
660 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
661 key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
662 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
663 by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
664 speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
665 Twofish round function.
666
667 \begin{figure}[hpbt]
668 \index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
669 \begin{small}
670 \begin{center}
671 \begin{tabular}{|l|l|l|}
672 \hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
673 \hline undefined & undefined & Very fast, 4.2KB of ram. \\
674 \hline undefined & defined & Faster key setup, larger code. \\
675 \hline defined & undefined & Very slow, 0.2KB of ram. \\
676 \hline defined & defined & Faster, 0.2KB of ram, larger code. \\
677 \hline
678 \end{tabular}
679 \end{center}
680 \end{small}
681 \caption{Twofish Build Options}
682 \label{fig:twofishopts}
683 \end{figure}
684
685 \item
686 As of v1.18.0 of the library RC2 got an extended setup function (which didn't fit in the regular API):
687
688 \index{rc2\_setup\_ex()}
689 \begin{verbatim}
690 int rc2_setup_ex(const unsigned char *key,
691 int keylen,
692 int bits,
693 int num_rounds,
694 symmetric_key *skey);
695 \end{verbatim}
696
697 This setup function also allows to configure the effective key length in bits of the RC2 cipher as in its original specification.
698
699 \end{enumerate}
700 \end{small}
701
702
703 To work with the cipher\_descriptor array there is a function:
704 \index{find\_cipher()}
705 \begin{verbatim}
706 int find_cipher(char *name)
707 \end{verbatim}
708 Which will search for a given name in the array. It returns $-1$ if the cipher is not found, otherwise it returns
709 the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
710 \begin{small}
711 \index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
712 \begin{verbatim}
713 #include <tomcrypt.h>
714 int main(void)
715 {
716 unsigned char key[8];
717 symmetric_key skey;
718 int err;
719
720 /* you must register a cipher before you use it */
721 if (register_cipher(&blowfish_desc)) == -1) {
722 printf("Unable to register Blowfish cipher.");
723 return -1;
724 }
725
726 /* generic call to function (assuming the key
727 * in key[] was already setup) */
728 if ((err =
729 cipher_descriptor[find_cipher("blowfish")].
730 setup(key, 8, 0, &skey)) != CRYPT_OK) {
731 printf("Error setting up Blowfish: %s\n", error_to_string(err));
732 return -1;
733 }
734
735 /* ... use cipher ... */
736 }
737 \end{verbatim}
738 \end{small}
739
740 A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function. In order
741 to use a cipher with the descriptor table you must register it first using:
742 \index{register\_cipher()}
743 \begin{verbatim}
744 int register_cipher(const struct _cipher_descriptor *cipher);
745 \end{verbatim}
746 Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
747 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
748 than once it will just return the index of the first copy. To remove a cipher call:
749 \index{unregister\_cipher()}
750 \begin{verbatim}
751 int unregister_cipher(const struct _cipher_descriptor *cipher);
752 \end{verbatim}
753 Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
754 \begin{small}
755 \begin{verbatim}
756 #include <tomcrypt.h>
757 int main(void)
758 {
759 int err;
760
761 /* register the cipher */
762 if (register_cipher(&rijndael_desc) == -1) {
763 printf("Error registering Rijndael\n");
764 return -1;
765 }
766
767 /* use Rijndael */
768
769 /* remove it */
770 if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
771 printf("Error removing Rijndael: %s\n", error_to_string(err));
772 return -1;
773 }
774
775 return 0;
776 }
777 \end{verbatim}
778 \end{small}
779 This snippet is a small program that registers Rijndael.
780
781 \mysection{Symmetric Modes of Operations}
782 \subsection{Background}
783 A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
784 size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
785 $P$ under the key $k$ as $E_k(P)$. In some modes there exists an initialization vector denoted as $C_{-1}$.
786
787 \subsubsection{ECB Mode}
788 \index{ECB mode}
789 ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
790 \begin{equation}
791 C_i = E_k(P_i)
792 \end{equation}
793 This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
794 than once.
795
796 \subsubsection{CBC Mode}
797 \index{CBC mode}
798 CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
799 It is given as:
800 \begin{equation}
801 C_i = E_k(P_i \oplus C_{i - 1})
802 \end{equation}
803 It is important that the initialization vector be unique and preferably random for each message encrypted under the same key.
804
805 \subsubsection{CTR Mode}
806 \index{CTR mode}
807 CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initialization vector which is
808 treated as a large binary counter the CTR mode is given as:
809 \begin{eqnarray}
810 C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
811 C_i = P_i \oplus E_k(C_{-1})
812 \end{eqnarray}
813 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
814 encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
815 as the block cipher is under a chosen plaintext attack (provided the initialization vector is unique).
816
817 \subsubsection{CFB Mode}
818 \index{CFB mode}
819 CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
820 \begin{eqnarray}
821 C_i = P_i \oplus C_{-1} \nonumber \\
822 C_{-1} = E_k(C_i)
823 \end{eqnarray}
824 Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
825 to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
826 blocks without a delay. When this mode is first setup it will initially encrypt the initialization vector as required.
827
828 \subsubsection{OFB Mode}
829 \index{OFB mode}
830 OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
831 \begin{eqnarray}
832 C_{-1} = E_k(C_{-1}) \nonumber \\
833 C_i = P_i \oplus C_{-1}
834 \end{eqnarray}
835 Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
836 buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
837
838 \subsection{Choice of Mode}
839 My personal preference is for the CTR mode since it has several key benefits:
840 \begin{enumerate}
841 \item No short cycles which is possible in the OFB and CFB modes.
842 \item Provably as secure as the block cipher being used under a chosen plaintext attack.
843 \item Technically does not require the decryption routine of the cipher.
844 \item Allows random access to the plaintext.
845 \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
846 \end{enumerate}
847 The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
848 accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
849 block of memory with either of the three modes.
850
851 The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
852 other modes.
853
854 \subsection{Ciphertext Stealing}
855 \index{Ciphertext stealing}
856 Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
857 by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
858 support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.
859
860 The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
861
862 \subsection{Initialization}
863 \index{CBC Mode} \index{CTR Mode}
864 \index{OFB Mode} \index{CFB Mode}
865 The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
866 you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
867 use that mode. They have identical setup routines (except CTR and ECB mode):
868 \index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
869 \begin{verbatim}
870 int XXX_start( int cipher,
871 const unsigned char *IV,
872 const unsigned char *key,
873 int keylen,
874 int num_rounds,
875 symmetric_XXX *XXX);
876
877 int ctr_start( int cipher,
878 const unsigned char *IV,
879 const unsigned char *key,
880 int keylen,
881 int num_rounds,
882 int ctr_mode,
883 symmetric_CTR *ctr);
884
885 int ecb_start( int cipher,
886 const unsigned char *key,
887 int keylen,
888 int num_rounds,
889 symmetric_ECB *ecb);
890 \end{verbatim}
891
892 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
893 the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
894 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.}
895 of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
896 parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call. The final parameter
897 is a pointer to the structure you want to hold the information for the mode of operation.
898
899 The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.
900
901 \subsubsection{CTR Mode}
902 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.
903 If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
904 \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
905 increment then encrypt is also supported. By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
906 the counter before encrypting it for the first time.
907
908 As of V1.17, the library supports variable length counters for CTR mode. The (optional) counter length is specified by OR'ing the octet
909 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
910 ensures backwards compatibility with software that uses older versions of the library.
911
912 \begin{small}
913 \begin{verbatim}
914 symmetric_CTR ctr;
915 int err;
916 unsigned char IV[16], key[16];
917
918 /* use a 32-bit little endian counter */
919 if ((err = ctr_start(find_cipher("aes"),
920 IV, key, 16, 0,
921 CTR_COUNTER_LITTLE_ENDIAN | 4,
922 &ctr)) != CRYPT_OK) {
923 handle_error(err);
924 }
925 \end{verbatim}
926 \end{small}
927
928 Changing the counter size has little (really no) effect on the performance of the CTR chaining mode. It is provided for compatibility
929 with other software (and hardware) which have smaller fixed sized counters.
930
931 \subsection{Encryption and Decryption}
932 To actually encrypt or decrypt the following routines are provided:
933 \index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
934 \index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
935 \begin{verbatim}
936 int XXX_encrypt(const unsigned char *pt,
937 unsigned char *ct,
938 unsigned long len,
939 symmetric_YYY *YYY);
940
941 int XXX_decrypt(const unsigned char *ct,
942 unsigned char *pt,
943 unsigned long len,
944 symmetric_YYY *YYY);
945 \end{verbatim}
946 Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.
947
948 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
949 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}
950 and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
951 five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
952
953 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
954 zeroes or with whatever your protocol requires).
955
956 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.
957
958 \subsection{IV Manipulation}
959 To change or read the IV of a previously initialized chaining mode use the following two functions.
960 \index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
961 \index{ctr\_setiv()} \index{ctr\_getiv()}
962 \begin{verbatim}
963 int XXX_getiv(unsigned char *IV,
964 unsigned long *len,
965 symmetric_XXX *XXX);
966
967 int XXX_setiv(const unsigned char *IV,
968 unsigned long len,
969 symmetric_XXX *XXX);
970 \end{verbatim}
971
972 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
973 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
974 of the IV passed in must be the size of the ciphers block size.
975
976 The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
977
978 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
979 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
980 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
981 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
982 seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
983
984 \subsection{Stream Termination}
985 To terminate an open stream call the done function.
986
987 \index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
988 \begin{verbatim}
989 int XXX_done(symmetric_XXX *XXX);
990 \end{verbatim}
991
992 This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
993
994 \newpage
995 \subsection{Examples}
996 \begin{small}
997 \begin{verbatim}
998 #include <tomcrypt.h>
999 int main(void)
1000 {
1001 unsigned char key[16], IV[16], buffer[512];
1002 symmetric_CTR ctr;
1003 int x, err;
1004
1005 /* register twofish first */
1006 if (register_cipher(&twofish_desc) == -1) {
1007 printf("Error registering cipher.\n");
1008 return -1;
1009 }
1010
1011 /* somehow fill out key and IV */
1012
1013 /* start up CTR mode */
1014 if ((err = ctr_start(
1015 find_cipher("twofish"), /* index of desired cipher */
1016 IV, /* the initialization vector */
1017 key, /* the secret key */
1018 16, /* length of secret key (16 bytes) */
1019 0, /* 0 == default # of rounds */
1020 CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
1021 &ctr) /* where to store the CTR state */
1022 ) != CRYPT_OK) {
1023 printf("ctr_start error: %s\n", error_to_string(err));
1024 return -1;
1025 }
1026
1027 /* somehow fill buffer than encrypt it */
1028 if ((err = ctr_encrypt( buffer, /* plaintext */
1029 buffer, /* ciphertext */
1030 sizeof(buffer), /* length of plaintext pt */
1031 &ctr) /* CTR state */
1032 ) != CRYPT_OK) {
1033 printf("ctr_encrypt error: %s\n", error_to_string(err));
1034 return -1;
1035 }
1036
1037 /* make use of ciphertext... */
1038
1039 /* now we want to decrypt so let's use ctr_setiv */
1040 if ((err = ctr_setiv( IV, /* the initial IV we gave to ctr_start */
1041 16, /* the IV is 16 bytes long */
1042 &ctr) /* the ctr state we wish to modify */
1043 ) != CRYPT_OK) {
1044 printf("ctr_setiv error: %s\n", error_to_string(err));
1045 return -1;
1046 }
1047
1048 if ((err = ctr_decrypt( buffer, /* ciphertext */
1049 buffer, /* plaintext */
1050 sizeof(buffer), /* length of plaintext */
1051 &ctr) /* CTR state */
1052 ) != CRYPT_OK) {
1053 printf("ctr_decrypt error: %s\n", error_to_string(err));
1054 return -1;
1055 }
1056
1057 /* terminate the stream */
1058 if ((err = ctr_done(&ctr)) != CRYPT_OK) {
1059 printf("ctr_done error: %s\n", error_to_string(err));
1060 return -1;
1061 }
1062
1063 /* clear up and return */
1064 zeromem(key, sizeof(key));
1065 zeromem(&ctr, sizeof(ctr));
1066
1067 return 0;
1068 }
1069 \end{verbatim}
1070 \end{small}
1071
1072 \subsection{LRW Mode}
1073 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
1074 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.
1075
1076 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
1077 $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.
1078
1079 To initialize LRW mode use:
1080
1081 \index{lrw\_start()}
1082 \begin{verbatim}
1083 int lrw_start( int cipher,
1084 const unsigned char *IV,
1085 const unsigned char *key,
1086 int keylen,
1087 const unsigned char *tweak,
1088 int num_rounds,
1089 symmetric_LRW *lrw);
1090 \end{verbatim}
1091
1092 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}.
1093 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
1094 number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.
1095
1096 To process data use the following functions:
1097
1098 \index{lrw\_encrypt()} \index{lrw\_decrypt()}
1099 \begin{verbatim}
1100 int lrw_encrypt(const unsigned char *pt,
1101 unsigned char *ct,
1102 unsigned long len,
1103 symmetric_LRW *lrw);
1104
1105 int lrw_decrypt(const unsigned char *ct,
1106 unsigned char *pt,
1107 unsigned long len,
1108 symmetric_LRW *lrw);
1109 \end{verbatim}
1110
1111 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
1112 of 16. The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.
1113
1114 To manipulate the IV use the following functions:
1115
1116 \index{lrw\_getiv()} \index{lrw\_setiv()}
1117 \begin{verbatim}
1118 int lrw_getiv(unsigned char *IV,
1119 unsigned long *len,
1120 symmetric_LRW *lrw);
1121
1122 int lrw_setiv(const unsigned char *IV,
1123 unsigned long len,
1124 symmetric_LRW *lrw);
1125 \end{verbatim}
1126 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
1127 updating the entire tweak which is slower than sequential use. Avoid seeking excessively in performance constrained code.
1128
1129 To terminate the LRW state use the following:
1130
1131 \index{lrw\_done()}
1132 \begin{verbatim}
1133 int lrw_done(symmetric_LRW *lrw);
1134 \end{verbatim}
1135
1136 \subsection{XTS Mode}
1137 As of v1.17, LibTomCrypt supports XTS mode with code donated by Elliptic Semiconductor Inc.\footnote{www.ellipticsemi.com}.
1138 XTS is a chaining mode for 128--bit block ciphers, recommended by IEEE (P1619)
1139 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
1140 length) to perform the encryption process. Each encryption invocation includes a sector number or unique identifier specified as a 128--bit string.
1141
1142 To initialize XTS mode use the following function call:
1143
1144 \index{xts\_start()}
1145 \begin{verbatim}
1146 int xts_start( int cipher,
1147 const unsigned char *key1,
1148 const unsigned char *key2,
1149 unsigned long keylen,
1150 int num_rounds,
1151 symmetric_xts *xts)
1152 \end{verbatim}
1153 This will start the XTS mode with the two keys pointed to by \textit{key1} and \textit{key2} of length \textit{keylen} octets each.
1154
1155 To encrypt or decrypt a sector use the following calls:
1156
1157 \index{xts\_encrypt()} \index{xts\_decrypt()}
1158 \begin{verbatim}
1159 int xts_encrypt(
1160 const unsigned char *pt, unsigned long ptlen,
1161 unsigned char *ct,
1162 const unsigned char *tweak,
1163 symmetric_xts *xts);
1164
1165 int xts_decrypt(
1166 const unsigned char *ct, unsigned long ptlen,
1167 unsigned char *pt,
1168 const unsigned char *tweak,
1169 symmetric_xts *xts);
1170 \end{verbatim}
1171 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
1172 \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
1173 functions support ciphertext stealing (blocks that are not multiples of 16 bytes).
1174
1175 The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.
1176
1177 To terminate the XTS state call the following function:
1178
1179 \index{xts\_done()}
1180 \begin{verbatim}
1181 void xts_done(symmetric_xts *xts);
1182 \end{verbatim}
1183
1184
1185 \subsection{F8 Mode}
1186 \index{F8 Mode}
1187 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
1188 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
1189 initialize F8 mode with the following function call:
1190
1191 \index{f8\_start()}
1192 \begin{verbatim}
1193 int f8_start( int cipher,
1194 const unsigned char *IV,
1195 const unsigned char *key,
1196 int keylen,
1197 const unsigned char *salt_key,
1198 int skeylen,
1199 int num_rounds,
1200 symmetric_F8 *f8);
1201 \end{verbatim}
1202 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
1203 (\textit{m} in the RFC 3711). The salt\_key can be shorter than the secret key but it should not be longer.
1204
1205 To encrypt or decrypt data we use the following two functions:
1206
1207 \index{f8\_encrypt()} \index{f8\_decrypt()}
1208 \begin{verbatim}
1209 int f8_encrypt(const unsigned char *pt,
1210 unsigned char *ct,
1211 unsigned long len,
1212 symmetric_F8 *f8);
1213
1214 int f8_decrypt(const unsigned char *ct,
1215 unsigned char *pt,
1216 unsigned long len,
1217 symmetric_F8 *f8);
1218 \end{verbatim}
1219 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
1220 of the ciphers block size.
1221
1222 To change or retrieve the current counter IV value use the following functions:
1223 \index{f8\_getiv()} \index{f8\_setiv()}
1224 \begin{verbatim}
1225 int f8_getiv(unsigned char *IV,
1226 unsigned long *len,
1227 symmetric_F8 *f8);
1228
1229 int f8_setiv(const unsigned char *IV,
1230 unsigned long len,
1231 symmetric_F8 *f8);
1232 \end{verbatim}
1233 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
1234 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
1235 f8\_start().
1236
1237 To terminate an F8 state call the following function:
1238
1239 \index{f8\_done()}
1240 \begin{verbatim}
1241 int f8_done(symmetric_F8 *f8);
1242 \end{verbatim}
1243
1244 \chapter{Stream Ciphers}
1245
1246 Stream ciphers are symmetric key ciphers which operate on a stream of bytes (in theory on a stream of bits
1247 however LibTomCrypt's implementation works with bytes).
1248
1249 The API for all stream ciphers operates in mode: \textit{setup} -- \textit{crypt} -- \textit{crypt} -- ... -- \textit{done}.
1250 Please note that both encryption and decryption are implemented via \textit{crypt}.
1251
1252 Another useful feature of the stream ciphers API is generation of a random stream of bytes which works like:
1253 \textit{setup} -- \textit{keystream} -- \textit{keystream} -- ... -- \textit{done}. The random stream generation is
1254 implemented like encryption of a stream of \textit{0x00} bytes.
1255
1256 Note: You shouldn't use the keystream interface as a PRNG, as it doesn't allow to re-seed the internal state.
1257
1258 \mysection{ChaCha}
1259
1260 \textit{ChaCha} is currently the most modern stream cipher included in LibTomCrypt, so use this one unless you
1261 have a reason for using some of the older algorithms.
1262
1263 For more information about ChaCha see \url{https://en.wikipedia.org/wiki/ChaCha_(cipher)}.
1264
1265 Supported key size: 16 or 32 bytes (128 or 256 bits).
1266
1267 You can initialize ChaCha with 96bit \textit{nonce} + 32bit \textit{counter}:
1268 \begin{verbatim}
1269 chacha_state st;
1270 err = chacha_setup(&st, key, key_len, rounds);
1271 err = chacha_ivctr32(&st, nonce, 12, initial_32bit_ctr);
1272 \end{verbatim}
1273
1274 Or with 64bit \textit{nonce} + 64bit \textit{counter}:
1275 \begin{verbatim}
1276 chacha_state st;
1277 err = chacha_setup(&st, key, key_len, rounds);
1278 err = chacha_ivctr64(&st, nonce, 8, initial_64bit_ctr);
1279 \end{verbatim}
1280
1281 The \textit{chacha\_setup} takes the number of rounds as a parameter -- choose 20 if you are not sure.
1282 As always never ever use the same key + nonce pair more than once.
1283
1284 For the actual encryption or decryption you have to call:
1285 \begin{verbatim}
1286 err = chacha_crypt(&st, in_buffer, in_len, out_buffer);
1287 \end{verbatim}
1288
1289 If you just want a random stream of bytes initialize the cipher with a truly random \textit{key} (32 bytes),
1290 a truly random \textit{nonce} (8 bytes) and zero initial counter. After that you can get a stream of pseudo--random
1291 bytes via:
1292 \begin{verbatim}
1293 err = chacha_keystream(&st, out_buffer, out_len);
1294 \end{verbatim}
1295
1296 At the end you have to terminate the state:
1297 \begin{verbatim}
1298 err = chacha_done(&st);
1299 \end{verbatim}
1300
1301 \mysection{RC4}
1302
1303 For more information about RC4 see \url{https://en.wikipedia.org/wiki/RC4}.
1304
1305 Supported key size: 5--256 bytes
1306
1307 You need to initialize RC4 only with a \textit{key}.
1308 \begin{verbatim}
1309 rc4_state st;
1310 err = rc4_stream_setup(&st, key, key_len);
1311 \end{verbatim}
1312
1313 For the actual encryption or decryption you have to call:
1314 \begin{verbatim}
1315 err = rc4_stream_crypt(&st, in_buffer, in_len, out_buffer);
1316 \end{verbatim}
1317
1318
1319 If you just want a random stream of bytes initialize the cipher with truly random \textit{key}.
1320 After that you can get a stream of pseudo--random bytes via:
1321 \begin{verbatim}
1322 err = rc4_stream_keystream(&st, out_buffer, out_len);
1323 \end{verbatim}
1324
1325 At the end you have to terminate the state:
1326 \begin{verbatim}
1327 err = rc4_stream_done(&st);
1328 \end{verbatim}
1329
1330 \mysection{Sober128}
1331
1332 Supported key size: must be multiple of 4 bytes
1333
1334 You need to initialize Sober128 with a \textit{key} and a \textit{nonce} (must be multiple of 4 bytes).
1335 \begin{verbatim}
1336 sober128_state st;
1337 err = sober128_stream_setup(&st, key, 16);
1338 err = sober128_stream_setiv(&st, nonce, 12);
1339 \end{verbatim}
1340
1341 For the actual encryption or decryption you to call:
1342 \begin{verbatim}
1343 err = sober128_stream_crypt(&st, in_buffer, in_len, out_buffer);
1344 \end{verbatim}
1345
1346 If you just want a random stream of bytes initialize the cipher with a truly random \textit{key}
1347 and a truly random \textit{nonce}. After that you can get a stream of pseudo--random bytes via:
1348 \begin{verbatim}
1349 err = sober128_stream_keystream(&st, out_buffer, out_len);
1350 \end{verbatim}
1351
1352 At the end you have to terminate the state:
1353 \begin{verbatim}
1354 err = sober128_stream_done(&st);
1355 \end{verbatim}
1356
1357 \chapter{Authenticated Encryption}
1358
1359 Authenticated Encryption - sometimes also called Authenticated Encryption with Associated Data (AEAD) - is a variant of encryption
1360 that provides not only confidentiality (as other symmetric or stream ciphers) but also integrity.
1361
1362 The inputs of Authenticated Encryption are: \textit{key}, \textit{nonce} (sometimes called initialization vector), \textit{plaintext},
1363 optional \textit{header} (sometimes called additional authenticated data - AAD). The outputs are: \textit{ciphertext} and \textit{tag}.
1364
1365 \mysection{EAX Mode}
1366 LibTomCrypt provides support for a mode called EAX\footnote{See
1367 M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
1368 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,
1369 CTR and OMAC support and provides encryption and
1370 authentication\footnote{Note that since EAX only requires OMAC and CTR you may use \textit{encrypt only} cipher descriptors with this mode.}.
1371 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.
1372
1373 The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages). It can
1374 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.
1375
1376 The mode can then process plaintext producing ciphertext as well as compute a partial checksum. The actual checksum
1377 called a \textit{tag} is only emitted when the message is finished. In the interim, the user can process any arbitrary
1378 sized message block to send to the recipient as ciphertext. This makes the EAX mode especially suited for streaming modes
1379 of operation.
1380
1381 The mode is initialized with the following function.
1382 \index{eax\_init()}
1383 \begin{verbatim}
1384 int eax_init( eax_state *eax,
1385 int cipher,
1386 const unsigned char *key,
1387 unsigned long keylen,
1388 const unsigned char *nonce,
1389 unsigned long noncelen,
1390 const unsigned char *header,
1391 unsigned long headerlen);
1392 \end{verbatim}
1393
1394 Where \textit{eax} is the EAX state. The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.
1395 The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets. The \textit{nonce} parameter is the
1396 random public string of length \textit{noncelen} octets. The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the
1397 message of length \textit{headerlen} octets.
1398
1399 When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or
1400 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.
1401
1402 To encrypt or decrypt data in a streaming mode use the following.
1403 \index{eax\_encrypt()} \index{eax\_decrypt()}
1404 \begin{verbatim}
1405 int eax_encrypt( eax_state *eax,
1406 const unsigned char *pt,
1407 unsigned char *ct,
1408 unsigned long length);
1409
1410 int eax_decrypt( eax_state *eax,
1411 const unsigned char *ct,
1412 unsigned char *pt,
1413 unsigned long length);
1414 \end{verbatim}
1415 The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
1416 \textit{ct}. Note: \textit{ct} and \textit{pt} may be the same region in memory. This function will also send the ciphertext
1417 through the OMAC function. The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}. This also allows
1418 \textit{pt} and \textit{ct} to be the same region in memory.
1419
1420 You cannot both encrypt or decrypt with the same \textit{eax} context. For bi--directional communication you will need to initialize
1421 two EAX contexts (preferably with different headers and nonces).
1422
1423 Note: both of these functions allow you to send the data in any granularity but the order is important. While
1424 the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
1425 EAX stream with the following.
1426
1427 \index{eax\_addheader()}
1428 \begin{verbatim}
1429 int eax_addheader( eax_state *eax,
1430 const unsigned char *header,
1431 unsigned long length);
1432 \end{verbatim}
1433 This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header. Once the message is finished, the
1434 \textit{tag} (checksum) may be computed with the following function:
1435
1436 \index{eax\_done()}
1437 \begin{verbatim}
1438 int eax_done( eax_state *eax,
1439 unsigned char *tag,
1440 unsigned long *taglen);
1441 \end{verbatim}
1442 This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}. The function
1443 then stores how many bytes of the tag were written out back in to \textit{taglen}.
1444
1445 The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
1446 \index{eax\_test()}
1447 \begin{verbatim}
1448 int eax_test(void);
1449 \end{verbatim}
1450 This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.
1451
1452 \begin{verbatim}
1453 #include <tomcrypt.h>
1454 int main(void)
1455 {
1456 int err;
1457 eax_state eax;
1458 unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
1459 unsigned long taglen;
1460
1461 if (register_cipher(&rijndael_desc) == -1) {
1462 printf("Error registering Rijndael");
1463 return EXIT_FAILURE;
1464 }
1465
1466 /* ... make up random nonce and key ... */
1467
1468 /* initialize context */
1469 if ((err = eax_init( &eax, /* context */
1470 find_cipher("rijndael"), /* cipher id */
1471 nonce, /* the nonce */
1472 16, /* nonce is 16 bytes */
1473 "TestApp", /* example header */
1474 7) /* header length */
1475 ) != CRYPT_OK) {
1476 printf("Error eax_init: %s", error_to_string(err));
1477 return EXIT_FAILURE;
1478 }
1479
1480 /* now encrypt data, say in a loop or whatever */
1481 if ((err = eax_encrypt( &eax, /* eax context */
1482 pt, /* plaintext (source) */
1483 ct, /* ciphertext (destination) */
1484 sizeof(pt) /* size of plaintext */
1485 ) != CRYPT_OK) {
1486 printf("Error eax_encrypt: %s", error_to_string(err));
1487 return EXIT_FAILURE;
1488 }
1489
1490 /* finish message and get authentication tag */
1491 taglen = sizeof(tag);
1492 if ((err = eax_done( &eax, /* eax context */
1493 tag, /* where to put tag */
1494 &taglen /* length of tag space */
1495 ) != CRYPT_OK) {
1496 printf("Error eax_done: %s", error_to_string(err));
1497 return EXIT_FAILURE;
1498 }
1499
1500 /* now we have the authentication tag in "tag" and
1501 * it's taglen bytes long */
1502 }
1503 \end{verbatim}
1504
1505 You can also perform an entire EAX state on a block of memory in a single function call with the
1506 following functions.
1507
1508
1509 \index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
1510 \begin{verbatim}
1511 int eax_encrypt_authenticate_memory(
1512 int cipher,
1513 const unsigned char *key, unsigned long keylen,
1514 const unsigned char *nonce, unsigned long noncelen,
1515 const unsigned char *header, unsigned long headerlen,
1516 const unsigned char *pt, unsigned long ptlen,
1517 unsigned char *ct,
1518 unsigned char *tag, unsigned long *taglen);
1519
1520 int eax_decrypt_verify_memory(
1521 int cipher,
1522 const unsigned char *key, unsigned long keylen,
1523 const unsigned char *nonce, unsigned long noncelen,
1524 const unsigned char *header, unsigned long headerlen,
1525 const unsigned char *ct, unsigned long ctlen,
1526 unsigned char *pt,
1527 unsigned char *tag, unsigned long taglen,
1528 int *res);
1529 \end{verbatim}
1530
1531 Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done(). The parameters
1532 have the same meaning as with those respective functions.
1533
1534 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
1535 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$.
1536
1537 \mysection{OCB Modes}
1538 \subsection{Preface}
1539
1540 LibTomCrypt provides support for a mode called OCB in version 1 ''OCB''\footnote{See
1541 P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit{OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption}.}
1542 and version 3 ''OCB3''\footnote{See RFC7253, T. Krovetz, P. Rogaway, \textit{The OCB Authenticated-Encryption Algorithm}.}.
1543 OCB is an encryption protocol that simultaneously provides authentication. It is slightly faster to use than EAX mode
1544 but is less flexible.
1545
1546 Please be aware that all versions of OCB are patented and there are several licensing models provided by P. Rogaway, the patent holder
1547 -- see \url{http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm}.
1548
1549 \subsection{OCB}
1550 \subsubsection{Initialization and processing}
1551
1552 Let's review how to initialize an OCB context.
1553
1554 \index{ocb\_init()}
1555 \begin{verbatim}
1556 int ocb_init( ocb_state *ocb,
1557 int cipher,
1558 const unsigned char *key,
1559 unsigned long keylen,
1560 const unsigned char *nonce);
1561 \end{verbatim}
1562
1563 This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
1564 and the random \textit{nonce}. Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
1565 block size (e.g. 16 bytes for AES).
1566
1567 This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
1568 To encrypt or decrypt data use the following.
1569
1570 \index{ocb\_encrypt()} \index{ocb\_decrypt()}
1571 \begin{verbatim}
1572 int ocb_encrypt( ocb_state *ocb,
1573 const unsigned char *pt,
1574 unsigned char *ct);
1575
1576 int ocb_decrypt( ocb_state *ocb,
1577 const unsigned char *ct,
1578 unsigned char *pt);
1579 \end{verbatim}
1580
1581 This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
1582 They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
1583 both functions given a single \textit{ocb} state. For bi-directional communication you will have to initialize two \textit{ocb}
1584 states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
1585
1586 \subsubsection{State Termination}
1587
1588 When you are finished encrypting the message you call the following function to compute the tag.
1589
1590 \index{ocb\_done\_encrypt()}
1591 \begin{verbatim}
1592 int ocb_done_encrypt( ocb_state *ocb,
1593 const unsigned char *pt,
1594 unsigned long ptlen,
1595 unsigned char *ct,
1596 unsigned char *tag,
1597 unsigned long *taglen);
1598 \end{verbatim}
1599
1600 This will terminate an encrypt stream \textit{ocb}. If you have trailing bytes of plaintext that will not complete a block
1601 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
1602 store up to \textit{taglen} bytes of the tag into \textit{tag}.
1603
1604 Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen. Also note that if you have
1605 an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.
1606
1607 To terminate a decrypt stream and compared the tag you call the following.
1608
1609 \index{ocb\_done\_decrypt()}
1610 \begin{verbatim}
1611 int ocb_done_decrypt( ocb_state *ocb,
1612 const unsigned char *ct,
1613 unsigned long ctlen,
1614 unsigned char *pt,
1615 const unsigned char *tag,
1616 unsigned long taglen,
1617 int *res);
1618 \end{verbatim}
1619 Similarly to the previous function you can pass trailing message bytes into this function. This will compute the
1620 tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided. By default
1621 \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
1622 message).
1623
1624 \subsubsection{Packet Functions}
1625 To make life simpler the following two functions are provided for memory bound OCB.
1626
1627 %\index{ocb\_encrypt\_authenticate\_memory()}
1628 \begin{verbatim}
1629 int ocb_encrypt_authenticate_memory(
1630 int cipher,
1631 const unsigned char *key, unsigned long keylen,
1632 const unsigned char *nonce,
1633 const unsigned char *pt, unsigned long ptlen,
1634 unsigned char *ct,
1635 unsigned char *tag, unsigned long *taglen);
1636 \end{verbatim}
1637
1638 This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
1639 can be any arbitrary length.
1640
1641 \index{ocb\_decrypt\_verify\_memory()}
1642 \begin{verbatim}
1643 int ocb_decrypt_verify_memory(
1644 int cipher,
1645 const unsigned char *key, unsigned long keylen,
1646 const unsigned char *nonce,
1647 const unsigned char *ct, unsigned long ctlen,
1648 unsigned char *pt,
1649 const unsigned char *tag, unsigned long taglen,
1650 int *res);
1651 \end{verbatim}
1652
1653 Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
1654 appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.
1655
1656 \subsection{OCB3}
1657 \subsubsection{Initialization and processing}
1658
1659 \index{ocb3\_init()}
1660 \begin{verbatim}
1661 int ocb3_init(ocb3_state *ocb, int cipher,
1662 const unsigned char *key, unsigned long keylen,
1663 const unsigned char *nonce, unsigned long noncelen,
1664 unsigned long taglen);
1665 \end{verbatim}
1666
1667 This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}. It will use a \textit{key} of length \textit{keylen}
1668 and the random \textit{nonce} of length \textit{noncelen}. The \textit{nonce} must be a random (public) string of an arbitrary length
1669 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}
1670 and has to be between 0 and 16 octets.
1671
1672 Note that you can only use ciphers with a block length of 16.
1673
1674 \subsubsection{Additional Authenticated Data}
1675
1676 OCB3 has, in contrary to OCB, the possibility to add "Additional Authenticated Data" (AAD) when performing cryptographic operations.
1677
1678 \index{ocb3\_add\_aad()}
1679 \begin{verbatim}
1680 int ocb3_add_aad(ocb3_state *ocb, const unsigned char *aad, unsigned long aadlen);
1681 \end{verbatim}
1682
1683 This will add the AAD at \textit{aad} of the arbitrary length \textit{aadlen} to be authenticated within the context \textit{ocb}.
1684
1685 \index{ocb3\_encrypt()} \index{ocb3\_decrypt()}
1686 \begin{verbatim}
1687 int ocb3_encrypt( ocb3_state *ocb,
1688 const unsigned char *pt,
1689 unsigned long ptlen,
1690 unsigned char *ct);
1691
1692 int ocb3_decrypt( ocb3_state *ocb,
1693 const unsigned char *ct,
1694 unsigned long ctlen,
1695 unsigned char *pt);
1696 \end{verbatim}
1697
1698 This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
1699 They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size. Note that you cannot call
1700 both functions given a single \textit{ocb} state. For bi-directional communication you will have to initialize two \textit{ocb}
1701 states (with different nonces). Also \textit{pt} and \textit{ct} may point to the same location in memory.
1702
1703 \subsubsection{State Termination}
1704
1705 \index{ocb3\_encrypt\_last()} \index{ocb3\_decrypt\_last()}
1706 \begin{verbatim}
1707 int ocb3_encrypt_last( ocb3_state *ocb,
1708 const unsigned char *pt,
1709 unsigned long ptlen,
1710 unsigned char *ct);
1711
1712 int ocb3_decrypt_last( ocb3_state *ocb,
1713 const unsigned char *ct,
1714 unsigned long ctlen,
1715 unsigned char *pt);
1716 \end{verbatim}
1717
1718 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
1719 directly use these functions instead of \textit{ocb3\_encrypt()} or \textit{ocb3\_decrypt()}.
1720
1721 When you are finished encrypting the message you call the following function to compute the tag.
1722
1723 \index{ocb3\_done()}
1724 \begin{verbatim}
1725 int ocb3_done(ocb3_state *ocb, unsigned char *tag, unsigned long *taglen);
1726 \end{verbatim}
1727
1728 This stores the tag of the \textit{ocb} state in \textit{tag}.
1729 The \textit{taglen} parameter defines on input the length of the tag to output and will be set to the actual length written, which
1730 is at most 16 octets.
1731
1732 \subsubsection{Packet Functions}
1733 To make life simpler the following two functions are provided for memory bound OCB3.
1734
1735 \index{ocb3\_encrypt\_authenticate\_memory()}
1736 \begin{verbatim}
1737 int ocb3_encrypt_authenticate_memory(int cipher,
1738 const unsigned char *key, unsigned long keylen,
1739 const unsigned char *nonce, unsigned long noncelen,
1740 const unsigned char *adata, unsigned long adatalen,
1741 const unsigned char *pt, unsigned long ptlen,
1742 unsigned char *ct,
1743 unsigned char *tag, unsigned long *taglen);
1744 \end{verbatim}
1745
1746 This will OCB3 encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}. The length \textit{ptlen}
1747 can be any arbitrary length. The additional authenticated data \textit{adata} of length \textit{adatalen} is optional and can be left out
1748 by passing \textit{NULL} as \textit{adata}. The length of the authentication TAG will be stored in \textit{tag}, which is also optional.
1749 The length of the TAG passed in \textit{taglen} has to be between 0 and 16.
1750
1751 \index{ocb3\_decrypt\_verify\_memory()}
1752 \begin{verbatim}
1753 int ocb3_decrypt_verify_memory(int cipher,
1754 const unsigned char *key, unsigned long keylen,
1755 const unsigned char *nonce, unsigned long noncelen,
1756 const unsigned char *adata, unsigned long adatalen,
1757 const unsigned char *ct, unsigned long ctlen,
1758 unsigned char *pt,
1759 const unsigned char *tag, unsigned long taglen,
1760 int *stat);
1761 \end{verbatim}
1762
1763 Similarly, this will OCB3 decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
1764 appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.
1765
1766 \mysection{CCM Mode}
1767 CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.
1768
1769 \subsection{Initialization}
1770 To initialize the CCM context with a secret key call the following function.
1771
1772 \index{ccm\_init()}
1773 \begin{verbatim}
1774 int ccm_init( ccm_state *ccm,
1775 int cipher,
1776 const unsigned char *key,
1777 int keylen,
1778 int ptlen,
1779 int taglen,
1780 int aadlen);
1781 \end{verbatim}
1782 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
1783 chosen must have a 16--byte block size (e.g., AES).
1784 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
1785 to authenticate is given as \textit{ptlen}.
1786 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
1787 as \textit{aadlen}.
1788
1789 \subsection{Nonce Vector}
1790 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.
1791
1792 \index{ccm\_add\_nonce()}
1793 \begin{verbatim}
1794 int ccm_add_nonce( ccm_state *ccm,
1795 const unsigned char *nonce,
1796 unsigned long noncelen);
1797 \end{verbatim}
1798
1799 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
1800 once and only once.
1801
1802 \subsection{Additional Authentication Data}
1803 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.
1804
1805 \index{ccm\_add\_aad()}
1806 \begin{verbatim}
1807 int ccm_add_aad( ccm_state *ccm,
1808 const unsigned char *adata,
1809 unsigned long adatalen);
1810 \end{verbatim}
1811 This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the CCM state \textit{ccm}.
1812
1813 \subsection{Plaintext Processing}
1814 After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
1815
1816 \index{ccm\_process()}
1817 \begin{verbatim}
1818 int ccm_process(ccm_state *ccm,
1819 unsigned char *pt,
1820 unsigned long ptlen,
1821 unsigned char *ct,
1822 int direction);
1823 \end{verbatim}
1824 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
1825 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,
1826 encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{CCM\_DECRYPT} the opposite occurs.
1827
1828 \subsection{State Termination}
1829 To terminate a CCM state and retrieve the message authentication tag call the following function.
1830
1831 \index{ccm\_done()}
1832 \begin{verbatim}
1833 int ccm_done( ccm_state *ccm,
1834 unsigned char *tag,
1835 unsigned long *taglen);
1836 \end{verbatim}
1837 This terminates the CCM state \textit{ccm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
1838
1839 \subsection{State Reset}
1840 The call to ccm\_init() will perform considerable pre--computation and if you're going to be dealing with a lot of packets
1841 it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function is provided.
1842
1843 \index{ccm\_reset()}
1844 \begin{verbatim}
1845 int ccm_reset(ccm_state *ccm);
1846 \end{verbatim}
1847
1848 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.
1849
1850 \subsection{One--Shot Packet}
1851 To process a single packet under any given key the following helper function can be used.
1852
1853 \index{ccm\_memory()}
1854 \begin{verbatim}
1855 int ccm_memory(
1856 int cipher,
1857 const unsigned char *key, unsigned long keylen,
1858 symmetric_key *uskey,
1859 const unsigned char *nonce, unsigned long noncelen,
1860 const unsigned char *header, unsigned long headerlen,
1861 unsigned char *pt, unsigned long ptlen,
1862 unsigned char *ct,
1863 unsigned char *tag, unsigned long *taglen,
1864 int direction);
1865 \end{verbatim}
1866
1867 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
1868 message tag. The definition of the variables is the same as it is for all the manual functions.
1869
1870 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.
1871
1872 \subsection{Example Usage}
1873 The following is an example usage of how to use CCM over multiple packets with a shared secret key.
1874
1875 \begin{small}
1876 \begin{verbatim}
1877 #include <tomcrypt.h>
1878
1879 int send_packet(const unsigned char *pt, unsigned long ptlen,
1880 const unsigned char *nonce, unsigned long noncelen,
1881 const unsigned char *aad, unsigned long aadlen,
1882 ccm_state *ccm)
1883 {
1884 int err;
1885 unsigned long taglen;
1886 unsigned char tag[16];
1887
1888 /* reset the state */
1889 if ((err = ccm_reset(ccm)) != CRYPT_OK) {
1890 return err;
1891 }
1892
1893 /* Add the nonce */
1894 if ((err = ccm_add_nonce(ccm, nonce, noncelen)) != CRYPT_OK) {
1895 return err;
1896 }
1897
1898 /* Add the AAD (note: aad can be NULL if aadlen == 0) */
1899 if ((err = ccm_add_aad(ccm, aad, aadlen)) != CRYPT_OK) {
1900 return err;
1901 }
1902
1903 /* process the plaintext */
1904 if ((err =
1905 ccm_process(ccm, pt, ptlen, pt, CCM_ENCRYPT)) != CRYPT_OK) {
1906 return err;
1907 }
1908
1909 /* Finish up and get the MAC tag */
1910 taglen = sizeof(tag);
1911 if ((err = ccm_done(ccm, tag, &taglen)) != CRYPT_OK) {
1912 return err;
1913 }
1914
1915 /* ... send a header describing the lengths ... */
1916
1917 /* depending on the protocol and how nonce is
1918 * generated you may have to send it too... */
1919 send(socket, nonce, noncelen, 0);
1920
1921 /* send the aad */
1922 send(socket, aad, aadlen, 0);
1923
1924 /* send the ciphertext */
1925 send(socket, pt, ptlen, 0);
1926
1927 /* send the tag */
1928 send(socket, tag, taglen, 0);
1929
1930 return CRYPT_OK;
1931 }
1932
1933 int main(void)
1934 {
1935 ccm_state ccm;
1936 unsigned char key[16], NONCE[12], pt[PACKET_SIZE];
1937 int err, x;
1938 unsigned long ptlen;
1939
1940 /* somehow fill key/NONCE with random values */
1941
1942 /* register AES */
1943 register_cipher(&aes_desc);
1944
1945 /* init the CCM state */
1946 if ((err =
1947 ccm_init(&ccm, find_cipher("aes"), key, 16, PACKET_SIZE, 16, size(NONCE))) != CRYPT_OK) {
1948 whine_and_pout(err);
1949 }
1950
1951 /* handle us some packets */
1952 for (;;) {
1953 ptlen = make_packet_we_want_to_send(pt);
1954
1955 /* use NONCE as counter (12 byte counter) */
1956 for (x = 11; x >= 0; x--) {
1957 if (++NONCE[x]) {
1958 break;
1959 }
1960 }
1961
1962 if ((err = send_packet(pt, ptlen, NONCE, 12, NULL, 0, &ccm))
1963 != CRYPT_OK) {
1964 whine_and_pout(err);
1965 }
1966 }
1967 return EXIT_SUCCESS;
1968 }
1969 \end{verbatim}
1970 \end{small}
1971
1972 \mysection{GCM Mode}
1973 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
1974 however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed. This mode also only works with
1975 block ciphers with a 16--byte block.
1976
1977 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
1978 unique to every session. Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).
1979
1980 \subsection{Initialization}
1981 To initialize the GCM context with a secret key call the following function.
1982
1983 \index{gcm\_init()}
1984 \begin{verbatim}
1985 int gcm_init( gcm_state *gcm,
1986 int cipher,
1987 const unsigned char *key,
1988 int keylen);
1989 \end{verbatim}
1990 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
1991 chosen must have a 16--byte block size (e.g., AES).
1992
1993 \subsection{Initialization Vector}
1994 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.
1995
1996 \index{gcm\_add\_iv()}
1997 \begin{verbatim}
1998 int gcm_add_iv( gcm_state *gcm,
1999 const unsigned char *IV,
2000 unsigned long IVlen);
2001 \end{verbatim}
2002 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
2003 to process the entire IV.
2004
2005 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
2006 to only use 12--byte IVs. You can just increment it like a counter for each packet.
2007
2008 \subsection{Additional Authentication Data}
2009 After the entire IV has been processed, the additional authentication data can be processed. Unlike the IV, a packet/session does not require additional
2010 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
2011 you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.
2012
2013 \index{gcm\_add\_aad()}
2014 \begin{verbatim}
2015 int gcm_add_aad( gcm_state *gcm,
2016 const unsigned char *adata,
2017 unsigned long adatalen);
2018 \end{verbatim}
2019 This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.
2020
2021 \subsection{Plaintext Processing}
2022 After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
2023
2024 \index{gcm\_process()}
2025 \begin{verbatim}
2026 int gcm_process( gcm_state *gcm,
2027 unsigned char *pt,
2028 unsigned long ptlen,
2029 unsigned char *ct,
2030 int direction);
2031 \end{verbatim}
2032 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
2033 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,
2034 encrypted and stored in the ciphertext buffer. When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.
2035
2036 \subsection{State Termination}
2037 To terminate a GCM state and retrieve the message authentication tag call the following function.
2038
2039 \index{gcm\_done()}
2040 \begin{verbatim}
2041 int gcm_done( gcm_state *gcm,
2042 unsigned char *tag,
2043 unsigned long *taglen);
2044 \end{verbatim}
2045 This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.
2046
2047 \subsection{State Reset}
2048 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
2049 it is very costly to have to call it repeatedly. To aid in this endeavour, the reset function has been provided.
2050
2051 \index{gcm\_reset()}
2052 \begin{verbatim}
2053 int gcm_reset(gcm_state *gcm);
2054 \end{verbatim}
2055
2056 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.
2057
2058 \subsection{One--Shot Packet}
2059 To process a single packet under any given key the following helper function can be used.
2060
2061 \index{gcm\_memory()}
2062 \begin{verbatim}
2063 int gcm_memory(
2064 int cipher,
2065 const unsigned char *key,
2066 unsigned long keylen,
2067 const unsigned char *IV, unsigned long IVlen,
2068 const unsigned char *adata, unsigned long adatalen,
2069 unsigned char *pt, unsigned long ptlen,
2070 unsigned char *ct,
2071 unsigned char *tag, unsigned long *taglen,
2072 int direction);
2073 \end{verbatim}
2074
2075 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
2076 message tag. The definition of the variables is the same as it is for all the manual functions.
2077
2078 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.
2079
2080 \subsection{Example Usage}
2081 The following is an example usage of how to use GCM over multiple packets with a shared secret key.
2082
2083 \begin{small}
2084 \begin{verbatim}
2085 #include <tomcrypt.h>
2086
2087 int send_packet(const unsigned char *pt, unsigned long ptlen,
2088 const unsigned char *iv, unsigned long ivlen,
2089 const unsigned char *aad, unsigned long aadlen,
2090 gcm_state *gcm)
2091 {
2092 int err;
2093 unsigned long taglen;
2094 unsigned char tag[16];
2095
2096 /* reset the state */
2097 if ((err = gcm_reset(gcm)) != CRYPT_OK) {
2098 return err;
2099 }
2100
2101 /* Add the IV */
2102 if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
2103 return err;
2104 }
2105
2106 /* Add the AAD (note: aad can be NULL if aadlen == 0) */
2107 if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
2108 return err;
2109 }
2110
2111 /* process the plaintext */
2112 if ((err =
2113 gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
2114 return err;
2115 }
2116
2117 /* Finish up and get the MAC tag */
2118 taglen = sizeof(tag);
2119 if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
2120 return err;
2121 }
2122
2123 /* ... send a header describing the lengths ... */
2124
2125 /* depending on the protocol and how IV is
2126 * generated you may have to send it too... */
2127 send(socket, iv, ivlen, 0);
2128
2129 /* send the aad */
2130 send(socket, aad, aadlen, 0);
2131
2132 /* send the ciphertext */
2133 send(socket, pt, ptlen, 0);
2134
2135 /* send the tag */
2136 send(socket, tag, taglen, 0);
2137
2138 return CRYPT_OK;
2139 }
2140
2141 int main(void)
2142 {
2143 gcm_state gcm;
2144 unsigned char key[16], IV[12], pt[PACKET_SIZE];
2145 int err, x;
2146 unsigned long ptlen;
2147
2148 /* somehow fill key/IV with random values */
2149
2150 /* register AES */
2151 register_cipher(&aes_desc);
2152
2153 /* init the GCM state */
2154 if ((err =
2155 gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
2156 whine_and_pout(err);
2157 }
2158
2159 /* handle us some packets */
2160 for (;;) {
2161 ptlen = make_packet_we_want_to_send(pt);
2162
2163 /* use IV as counter (12 byte counter) */
2164 for (x = 11; x >= 0; x--) {
2165 if (++IV[x]) {
2166 break;
2167 }
2168 }
2169
2170 if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm))
2171 != CRYPT_OK) {
2172 whine_and_pout(err);
2173 }
2174 }
2175 return EXIT_SUCCESS;
2176 }
2177 \end{verbatim}
2178 \end{small}
2179
2180 \mysection{ChaCha20--Poly1305}
2181
2182 This authenticated encryption is based on ChaCha20 stream cipher and Poly1305 authenticator.
2183 It is defined by \url{https://tools.ietf.org/html/rfc7539}.
2184
2185 \subsection{Initialization}
2186 To initialize the ChaCha20--Poly1305 context with a secret key call the following function.
2187
2188 \index{chacha20poly1305\_init()}
2189 \begin{verbatim}
2190 int chacha20poly1305_init(chacha20poly1305_state *st,
2191 const unsigned char *key,
2192 unsigned long keylen);
2193 \end{verbatim}
2194 This initializes the ChaCha20--Poly1305 state \textit{st} with a secret key \textit{key} of length \textit{keylen}
2195 octets (valid lengths: 32 or 16).
2196
2197 \subsection{Initialization Vector}
2198 After the state has been initialized the next step is to add the initialization vector.
2199
2200 \index{chacha20poly1305\_setiv()}
2201 \begin{verbatim}
2202 int chacha20poly1305_setiv(chacha20poly1305_state *st,
2203 const unsigned char *iv,
2204 unsigned long ivlen);
2205 \end{verbatim}
2206 This adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
2207 the ChaCha20--Poly1305 state \textit{st}.
2208
2209 \index{chacha20poly1305\_setiv\_rfc7905()}
2210 \begin{verbatim}
2211 int chacha20poly1305_setiv_rfc7905(chacha20poly1305_state *st,
2212 const unsigned char *iv,
2213 unsigned long ivlen,
2214 ulong64 sequence_number);
2215 \end{verbatim}
2216 This also adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
2217 the state \textit{st} but it also incorporates 64bit \textit{sequence\_number} into IV as described in RFC7905.
2218
2219 You can call only one of \textit{chacha20poly1305\_setiv} or \textit{chacha20poly1305\_setiv\_rfc7905}.
2220
2221 \subsection{Additional Authentication Data}
2222 After the IV has been set, the additional authentication data can be processed.
2223
2224 \index{chacha20poly1305\_add\_aad()}
2225 \begin{verbatim}
2226 int chacha20poly1305_add_aad(chacha20poly1305_state *st,
2227 const unsigned char *adata,
2228 unsigned long adatalen);
2229
2230 \end{verbatim}
2231 This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the ChaCha20--Poly1305 state \textit{st}.
2232
2233 \subsection{Encryption / Decryption}
2234 After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.
2235
2236 \index{chacha20poly1305\_encrypt()}
2237 \begin{verbatim}
2238 int chacha20poly1305_encrypt(chacha20poly1305_state *st,
2239 const unsigned char *in,
2240 unsigned long inlen,
2241 unsigned char *out);
2242 \end{verbatim}
2243 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}.
2244
2245 \index{chacha20poly1305\_decrypt()}
2246 \begin{verbatim}
2247 int chacha20poly1305_decrypt(chacha20poly1305_state *st,
2248 const unsigned char *in,
2249 unsigned long inlen,
2250 unsigned char *out);
2251 \end{verbatim}
2252 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}.
2253
2254 \subsection{State Termination}
2255 To terminate a ChaCha20--Poly1305 state and retrieve the message authentication tag call the following function.
2256
2257 \index{chacha20poly1305\_done()}
2258 \begin{verbatim}
2259 int chacha20poly1305_done(chacha20poly1305_state *st,
2260 unsigned char *tag,
2261 unsigned long *taglen);
2262 \end{verbatim}
2263 This terminates the ChaCha20--Poly1305 state \textit{st} and stores the tag in \textit{tag} of length \textit{taglen} octets (always 16).
2264
2265 \subsection{One--Shot Packet}
2266 To process a single packet under any given key the following helper function can be used.
2267
2268 \index{chacha20poly1305\_memory()}
2269 \begin{verbatim}
2270 int chacha20poly1305_memory(const unsigned char *key,
2271 unsigned long keylen,
2272 const unsigned char *iv,
2273 unsigned long ivlen,
2274 const unsigned char *aad,
2275 unsigned long aadlen,
2276 const unsigned char *in,
2277 unsigned long inlen,
2278 unsigned char *out,
2279 unsigned char *tag,
2280 unsigned long *taglen,
2281 int direction);
2282 \end{verbatim}
2283 This will initialize the ChaCha20--Poly1305 state with the given key, IV and AAD value then proceed to
2284 encrypt (\textit{direction} equals \textbf{CHACHA20POLY1305\_ENCRYPT}) or decrypt (\textit{direction} equals
2285 \textbf{CHACHA20POLY1305\_DECRYPT}) the message text and store the final message tag. The definition of the
2286 variables is the same as it is for all the manual functions.
2287
2288 \chapter{One-Way Cryptographic Hash Functions}
2289 \mysection{Core Functions}
2290 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
2291 XXX (where XXX is the name) call:
2292 \index{Hash Functions}
2293 \begin{verbatim}
2294 void XXX_init(hash_state *md);
2295 \end{verbatim}
2296
2297 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:
2298 \begin{verbatim}
2299 int XXX_process( hash_state *md,
2300 const unsigned char *in,
2301 unsigned long inlen);
2302 \end{verbatim}
2303 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
2304 are buffered. In the case where this limit is reached the \textit{XXX\_process()} function returns \textit{CRYPT\_HASH\_OVERFLOW}.
2305 \index{CRYPT\_HASH\_OVERFLOW}
2306 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:
2307 \begin{verbatim}
2308 md5_process(&md, "hello ", 6);
2309 md5_process(&md, "world", 5);
2310 \end{verbatim}
2311 Will produce the same message digest as the single call:
2312 \index{Message Digest}
2313 \begin{verbatim}
2314 md5_process(&md, "hello world", 11);
2315 \end{verbatim}
2316
2317 To finally get the message digest (the hash) call:
2318 \begin{verbatim}
2319 int XXX_done( hash_state *md,
2320 unsigned char *out);
2321 \end{verbatim}
2322
2323 This function will finish up the hash and store the result in the \textit{out} array. You must ensure that \textit{out} is long
2324 enough for the hash in question. Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
2325 will wipe the \textit{md} variable before returning automatically.
2326
2327 To test a hash function call:
2328 \begin{verbatim}
2329 int XXX_test(void);
2330 \end{verbatim}
2331
2332 This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code. An
2333 example snippet that hashes a message with md5 is given below.
2334 \begin{small}
2335 \begin{verbatim}
2336 #include <tomcrypt.h>
2337 int main(void)
2338 {
2339 hash_state md;
2340 unsigned char *in = "hello world", out[16];
2341
2342 /* setup the hash */
2343 md5_init(&md);
2344
2345 /* add the message */
2346 md5_process(&md, in, strlen(in));
2347
2348 /* get the hash in out[0..15] */
2349 md5_done(&md, out);
2350
2351 return 0;
2352 }
2353 \end{verbatim}
2354 \end{small}
2355
2356 \mysection{Hash Descriptors}
2357 Like the set of ciphers, the set of hashes have descriptors as well. They are stored in an array called \textit{hash\_descriptor} and
2358 are defined by:
2359 \begin{verbatim}
2360 struct _hash_descriptor {
2361 char *name;
2362
2363 unsigned long hashsize; /* digest output size in bytes */
2364 unsigned long blocksize; /* the block size the hash uses */
2365
2366 void (*init) (hash_state *hash);
2367
2368 int (*process)( hash_state *hash,
2369 const unsigned char *in,
2370 unsigned long inlen);
2371
2372 int (*done) (hash_state *hash, unsigned char *out);
2373
2374 int (*test) (void);
2375 };
2376 \end{verbatim}
2377
2378 \index{find\_hash()}
2379 The \textit{name} member is the name of the hash function (all lowercase). The \textit{hashsize} member is the size of the digest output
2380 in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function. Technically, this detail is not important
2381 for high level developers but is useful to know for performance reasons.
2382
2383 The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the
2384 digest. The \textit{test} member tests the hash against the specified test vectors.
2385
2386 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
2387 position in the descriptor table of the hash.
2388
2389 In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
2390 \index{find\_hash\_oid()}
2391 \begin{verbatim}
2392 int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
2393 \end{verbatim}
2394
2395 You can use the table to indirectly call a hash function that is chosen at run-time. For example:
2396 \begin{small}
2397 \begin{verbatim}
2398 #include <tomcrypt.h>
2399 int main(void)
2400 {
2401 unsigned char buffer[100], hash[MAXBLOCKSIZE];
2402 int idx, x;
2403 hash_state md;
2404
2405 /* register hashes .... */
2406 if (register_hash(&md5_desc) == -1) {
2407 printf("Error registering MD5.\n");
2408 return -1;
2409 }
2410
2411 /* register other hashes ... */
2412
2413 /* prompt for name and strip newline */
2414 printf("Enter hash name: \n");
2415 fgets(buffer, sizeof(buffer), stdin);
2416 buffer[strlen(buffer) - 1] = 0;
2417
2418 /* get hash index */
2419 idx = find_hash(buffer);
2420 if (idx == -1) {
2421 printf("Invalid hash name!\n");
2422 return -1;
2423 }
2424
2425 /* hash input until blank line */
2426 hash_descriptor[idx].init(&md);
2427 while (fgets(buffer, sizeof(buffer), stdin) != NULL)
2428 hash_descriptor[idx].process(&md, buffer, strlen(buffer));
2429 hash_descriptor[idx].done(&md, hash);
2430
2431 /* dump to screen */
2432 for (x = 0; x < hash_descriptor[idx].hashsize; x++)
2433 printf("%02x ", hash[x]);
2434 printf("\n");
2435 return 0;
2436 }
2437 \end{verbatim}
2438 \end{small}
2439
2440 Note the usage of \textbf{MAXBLOCKSIZE}. In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
2441 length. This provides a simple size you can set your automatic arrays to that will not get overrun.
2442
2443 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
2444 function call.
2445
2446 \index{hash\_memory()}
2447 \begin{verbatim}
2448 int hash_memory( int hash,
2449 const unsigned char *in,
2450 unsigned long inlen,
2451 unsigned char *out,
2452 unsigned long *outlen);
2453 \end{verbatim}
2454
2455 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
2456 digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.
2457
2458 The next helper function allows for the hashing of a file based on a file name.
2459 \index{hash\_file()}
2460 \begin{verbatim}
2461 int hash_file( int hash,
2462 const char *fname,
2463 unsigned char *out,
2464 unsigned long *outlen);
2465 \end{verbatim}
2466
2467 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
2468 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}
2469 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.
2470
2471 \index{hash\_filehandle()}
2472 \begin{verbatim}
2473 int hash_filehandle( int hash,
2474 FILE *in,
2475 unsigned char *out,
2476 unsigned long *outlen);
2477 \end{verbatim}
2478
2479 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
2480 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}
2481 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.
2482
2483 To perform the above hash with md5 the following code could be used:
2484 \begin{small}
2485 \begin{verbatim}
2486 #include <tomcrypt.h>
2487 int main(void)
2488 {
2489 int idx, err;
2490 unsigned long len;
2491 unsigned char out[MAXBLOCKSIZE];
2492
2493 /* register the hash */
2494 if (register_hash(&md5_desc) == -1) {
2495 printf("Error registering MD5.\n");
2496 return -1;
2497 }
2498
2499 /* get the index of the hash */
2500 idx = find_hash("md5");
2501
2502 /* call the hash */
2503 len = sizeof(out);
2504 if ((err =
2505 hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
2506 printf("Error hashing data: %s\n", error_to_string(err));
2507 return -1;
2508 }
2509 return 0;
2510 }
2511 \end{verbatim}
2512 \end{small}
2513
2514 \subsection{Hash Registration}
2515 Similar to the cipher descriptor table you must register your hash algorithms before you can use them. These functions
2516 work exactly like those of the cipher registration code. The functions are:
2517 \index{register\_hash()} \index{unregister\_hash()}
2518 \begin{verbatim}
2519 int register_hash(const struct _hash_descriptor *hash);
2520
2521 int unregister_hash(const struct _hash_descriptor *hash);
2522 \end{verbatim}
2523
2524 The following hashes are provided as of this release within the LibTomCrypt library:
2525 \index{Hash descriptor table}
2526
2527 \begin{figure}[H]
2528 \begin{center}
2529 \begin{tabular}{|c|c|c|}
2530 \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Size of Message Digest (bytes)} \\
2531 \hline WHIRLPOOL & whirlpool\_desc & 64 \\
2532 \hline SHA3-512 & sha3\_512\_desc & 64 \\
2533 \hline SHA-512 & sha512\_desc & 64 \\
2534 \hline BLAKE2B-512 & blake2b\_512\_desc & 64 \\
2535 \hline SHA3-384 & sha3\_384\_desc & 48 \\
2536 \hline SHA-384 & sha384\_desc & 48 \\
2537 \hline RIPEMD-320 & rmd160\_desc & 40 \\
2538 \hline SHA-512/256 & sha512\_256\_desc & 32 \\
2539 \hline SHA3-256 & sha3\_256\_desc & 32 \\
2540 \hline SHA-256 & sha256\_desc & 32 \\
2541 \hline RIPEMD-256 & rmd160\_desc & 32 \\
2542 \hline BLAKE2S-256 & blake2s\_256\_desc & 32 \\
2543 \hline BLAKE2B-256 & blake2b\_256\_desc & 32 \\
2544 \hline SHA-512/224 & sha512\_224\_desc & 28 \\
2545 \hline SHA3-224 & sha3\_224\_desc & 28 \\
2546 \hline SHA-224 & sha224\_desc & 28 \\
2547 \hline BLAKE2S-224 & blake2s\_224\_desc & 28 \\
2548 \hline BLAKE2B-384 & blake2b\_384\_desc & 48 \\
2549 \hline TIGER-192 & tiger\_desc & 24 \\
2550 \hline SHA-1 & sha1\_desc & 20 \\
2551 \hline RIPEMD-160 & rmd160\_desc & 20 \\
2552 \hline BLAKE2S-160 & blake2s\_160\_desc & 20 \\
2553 \hline BLAKE2B-160 & blake2b\_160\_desc & 20 \\
2554 \hline RIPEMD-128 & rmd128\_desc & 16 \\
2555 \hline MD5 & md5\_desc & 16 \\
2556 \hline MD4 & md4\_desc & 16 \\
2557 \hline MD2 & md2\_desc & 16 \\
2558 \hline BLAKE2S-128 & blake2s\_128\_desc & 16 \\
2559 \hline
2560 \end{tabular}
2561 \end{center}
2562 \caption{Built--In Software Hashes}
2563 \end{figure}
2564 \vfil
2565
2566 \mysection{Cipher Hash Construction}
2567 \index{Cipher Hash Construction}
2568 An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode. In this mode
2569 applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use. In
2570 particular this allows a cryptosystem to be designed using very few moving parts.
2571
2572 In order to use the CHC system the developer will have to take a few extra steps. First the \textit{chc\_desc} hash
2573 descriptor must be registered with register\_hash(). At this point the CHC hash cannot be used to hash
2574 data. While it is in the hash system you still have to tell the CHC code which cipher to use. This is accomplished
2575 via the chc\_register() function.
2576
2577 \index{chc\_register()}
2578 \begin{verbatim}
2579 int chc_register(int cipher);
2580 \end{verbatim}
2581
2582 A cipher has to be registered with CHC (and also in the cipher descriptor tables with
2583 register\_cipher()). The chc\_register() function will bind a cipher to the CHC system. Only one cipher can
2584 be bound to the CHC hash at a time. There are additional requirements for the system to work.
2585
2586 \begin{enumerate}
2587 \item The cipher must have a block size greater than 64--bits.
2588 \item The cipher must allow an input key the size of the block size.
2589 \end{enumerate}
2590
2591 Example of using CHC with the AES block cipher.
2592
2593 \begin{verbatim}
2594 #include <tomcrypt.h>
2595 int main(void)
2596 {
2597 int err;
2598
2599 /* register cipher and hash */
2600 if (register_cipher(&aes_enc_desc) == -1) {
2601 printf("Could not register cipher\n");
2602 return EXIT_FAILURE;
2603 }
2604 if (register_hash(&chc_desc) == -1) {
2605 printf("Could not register hash\n");
2606 return EXIT_FAILURE;
2607 }
2608
2609 /* start chc with AES */
2610 if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
2611 printf("Error binding AES to CHC: %s\n",
2612 error_to_string(err));
2613 }
2614
2615 /* now you can use chc_hash in any LTC function
2616 * [aside from pkcs...] */
2617 }
2618 \end{verbatim}
2619
2620 \mysection{SHA3 SHAKE}
2621 The SHA3 class of algorithms provides a special XOF (Extendable Output Functions) mode, called SHAKE.
2622 SHAKE operates in 2 security configurations, 128bit or 256bit, and allows to generate message digests of an arbitrary length.
2623
2624 For further information see \url{https://en.wikipedia.org/wiki/SHA-3}
2625
2626 Example of using SHAKE256 with an arbitrary length output.
2627
2628 \begin{verbatim}
2629 #include <tomcrypt.h>
2630 int main(void)
2631 {
2632 int err;
2633 hash_state state;
2634 const void* msg = "The quick brown fox jumps over the lazy dog";
2635 unsigned char output[345];
2636
2637 if ((err = sha3_shake_init(&state, 256)) != CRYPT_OK) {
2638 printf("Could not init SHAKE256 (%s)\n", error_to_string(err));
2639 return EXIT_FAILURE;
2640 }
2641 if ((err = sha3_shake_process(&state, msg, strlen(msg))) != CRYPT_OK) {
2642 printf("Could not process SHAKE256 (%s)\n", error_to_string(err));
2643 return EXIT_FAILURE;
2644 }
2645 if ((err = sha3_shake_done(&state, output, sizeof(output))) != CRYPT_OK) {
2646 printf("Could not finish SHAKE256 (%s)\n", error_to_string(err));
2647 return EXIT_FAILURE;
2648 }
2649 return EXIT_SUCCESS;
2650 }
2651 \end{verbatim}
2652
2653 \mysection{Notice}
2654 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.
2655 These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
2656 (e.g. Yarrow).
2657
2658 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
2659 for all purposes you would normally use a hash for.
2660
2661 \chapter{Checksum Functions}
2662
2663 \mysection{Preface}
2664
2665 The API for all checksum functions operate in mode: \textit{init} -- \textit{update} -- \textit{update} -- ... -- \textit{finish}.
2666
2667 The \textit{finish} functions allow to output a partial result if necessary.
2668
2669 \mysection{CRC-32 -- Cyclic redundancy check}
2670
2671 A Cyclic Redundancy Check is an error-detecting code, where LibTomCrypt implements CRC-32 with the polynomial \textit{0x04C11DB7}.
2672
2673 For further information see \url{https://en.wikipedia.org/wiki/Cyclic_redundancy_check}
2674
2675 \begin{verbatim}
2676 void crc32_init(crc32_state *ctx);
2677 void crc32_update(crc32_state *ctx, const unsigned char *input, unsigned long length);
2678 void crc32_finish(crc32_state *ctx, void *hash, unsigned long size);
2679 \end{verbatim}
2680
2681 \mysection{Adler-32}
2682
2683 Adler-32 is a checksum algorithm.
2684
2685 For further information see \url{https://en.wikipedia.org/wiki/Adler-32}.
2686
2687 \begin{verbatim}
2688 void adler32_init(adler32_state *ctx);
2689 void adler32_update(adler32_state *ctx, const unsigned char *input, unsigned long length);
2690 void adler32_finish(adler32_state *ctx, void *hash, unsigned long size);
2691 \end{verbatim}
2692
2693 \chapter{Message Authentication Codes}
2694 \mysection{HMAC Protocol}
2695 Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short. An HMAC
2696 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
2697 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
2698 eavesdropper will not be able to verify the authenticity of a message.
2699
2700 The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
2701 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
2702 unsigned characters. The initialization routine is:
2703 \index{hmac\_init()}
2704 \begin{verbatim}
2705 int hmac_init( hmac_state *hmac,
2706 int hash,
2707 const unsigned char *key,
2708 unsigned long keylen);
2709 \end{verbatim}
2710 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
2711 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
2712 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:
2713 \index{hmac\_process()}
2714 \begin{verbatim}
2715 int hmac_process( hmac_state *hmac,
2716 const unsigned char *in,
2717 unsigned long inlen);
2718 \end{verbatim}
2719 \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
2720 number of octets to process. Like the hash process routines, you can send the data in arbitrarily sized chunks. When you
2721 are finished with the HMAC process you must call the following function to get the HMAC code:
2722 \index{hmac\_done()}
2723 \begin{verbatim}
2724 int hmac_done( hmac_state *hmac,
2725 unsigned char *out,
2726 unsigned long *outlen);
2727 \end{verbatim}
2728 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.
2729 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
2730 produced (depending on which hash was picked). If \textit{outlen} is less than the size of the message digest (and ultimately
2731 the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).
2732
2733 There are two utility functions provided to make using HMACs easier to do. They accept the key and information about the
2734 message (file pointer, address in memory), and produce the HMAC result in one shot. These are useful if you want to avoid
2735 calling the three step process yourself.
2736
2737 \index{hmac\_memory()}
2738 \begin{verbatim}
2739 int hmac_memory(
2740 int hash,
2741 const unsigned char *key, unsigned long keylen,
2742 const unsigned char *in, unsigned long inlen,
2743 unsigned char *out, unsigned long *outlen);
2744 \end{verbatim}
2745 This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}. The index into the hash descriptor
2746 table must be provided in \textit{hash}. It uses the key from \textit{key} with a key length of \textit{keylen}.
2747 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
2748 to the size of the destination buffer before calling this function. Similarly for files there is the following function:
2749 \index{hmac\_file()}
2750 \begin{verbatim}
2751 int hmac_file(
2752 int hash,
2753 const char *fname,
2754 const unsigned char *key, unsigned long keylen,
2755 unsigned char *out, unsigned long *outlen);
2756 \end{verbatim}
2757 \textit{hash} is the index into the hash descriptor table of the hash you want to use. \textit{fname} is the filename to process.
2758 \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
2759 result should be stored.
2760
2761 To test if the HMAC code is working there is the following function:
2762 \index{hmac\_test()}
2763 \begin{verbatim}
2764 int hmac_test(void);
2765 \end{verbatim}
2766 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
2767 HMAC system is given below.
2768
2769 \begin{small}
2770 \begin{verbatim}
2771 #include <tomcrypt.h>
2772 int main(void)
2773 {
2774 int idx, err;
2775 hmac_state hmac;
2776 unsigned char key[16], dst[MAXBLOCKSIZE];
2777 unsigned long dstlen;
2778
2779 /* register SHA-1 */
2780 if (register_hash(&sha1_desc) == -1) {
2781 printf("Error registering SHA1\n");
2782 return -1;
2783 }
2784
2785 /* get index of SHA1 in hash descriptor table */
2786 idx = find_hash("sha1");
2787
2788 /* we would make up our symmetric key in "key[]" here */
2789
2790 /* start the HMAC */
2791 if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
2792 printf("Error setting up hmac: %s\n", error_to_string(err));
2793 return -1;
2794 }
2795
2796 /* process a few octets */
2797 if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
2798 printf("Error processing hmac: %s\n", error_to_string(err));
2799 return -1;
2800 }
2801
2802 /* get result (presumably to use it somehow...) */
2803 dstlen = sizeof(dst);
2804 if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
2805 printf("Error finishing hmac: %s\n", error_to_string(err));
2806 return -1;
2807 }
2808 printf("The hmac is %lu bytes long\n", dstlen);
2809
2810 /* return */
2811 return 0;
2812 }
2813 \end{verbatim}
2814 \end{small}
2815
2816 \mysection{OMAC Support}
2817 \index{OMAC} \index{CMAC}
2818 OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
2819 algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES. Note: OMAC has been standardized as
2820 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
2821 HMAC routines. Instead, in this case a cipher is used instead of a hash.
2822
2823 To start an OMAC state you call
2824 \index{omac\_init()}
2825 \begin{verbatim}
2826 int omac_init( omac_state *omac,
2827 int cipher,
2828 const unsigned char *key,
2829 unsigned long keylen);
2830 \end{verbatim}
2831 The \textit{omac} parameter is the state for the OMAC algorithm. The \textit{cipher} parameter is the index into the cipher\_descriptor table
2832 of the cipher\footnote{The cipher must have a 64 or 128 bit block size. Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
2833 wish to use. The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.
2834
2835 To send data through the algorithm call
2836 \index{omac\_process()}
2837 \begin{verbatim}
2838 int omac_process( omac_state *state,
2839 const unsigned char *in,
2840 unsigned long inlen);
2841 \end{verbatim}
2842 This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}. Returns \textbf{CRYPT\_OK} if the
2843 function succeeds. The function is not sensitive to the granularity of the data. For example,
2844
2845 \begin{verbatim}
2846 omac_process(&mystate, "hello", 5);
2847 omac_process(&mystate, " world", 6);
2848 \end{verbatim}
2849
2850 Would produce the same result as,
2851
2852 \begin{verbatim}
2853 omac_process(&mystate, "hello world", 11);
2854 \end{verbatim}
2855
2856 When you are done processing the message you can call the following to compute the message tag.
2857
2858 \index{omac\_done()}
2859 \begin{verbatim}
2860 int omac_done( omac_state *state,
2861 unsigned char *out,
2862 unsigned long *outlen);
2863 \end{verbatim}
2864 Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}. Note that unlike the HMAC and other code
2865 \textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag). Part of the OMAC
2866 specification states that the output may be truncated. So if you pass in $outlen = 5$ and use AES as your cipher than
2867 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
2868 size to show how many bytes were actually used.
2869
2870 Similar to the HMAC code the file and memory functions are also provided. To OMAC a buffer of memory in one shot use the
2871 following function.
2872
2873 \index{omac\_memory()}
2874 \begin{verbatim}
2875 int omac_memory(
2876 int cipher,
2877 const unsigned char *key, unsigned long keylen,
2878 const unsigned char *in, unsigned long inlen,
2879 unsigned char *out, unsigned long *outlen);
2880 \end{verbatim}
2881 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
2882 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
2883 rules as omac\_done.
2884
2885 To OMAC a file use
2886 \index{omac\_file()}
2887 \begin{verbatim}
2888 int omac_file(
2889 int cipher,
2890 const unsigned char *key, unsigned long keylen,
2891 const char *filename,
2892 unsigned char *out, unsigned long *outlen);
2893 \end{verbatim}
2894
2895 Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
2896 and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
2897 the same rules as omac\_done.
2898
2899 To test if the OMAC code is working there is the following function:
2900 \index{omac\_test()}
2901 \begin{verbatim}
2902 int omac_test(void);
2903 \end{verbatim}
2904 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code. Some example code for using the
2905 OMAC system is given below.
2906
2907 \begin{small}
2908 \begin{verbatim}
2909 #include <tomcrypt.h>
2910 int main(void)
2911 {
2912 int idx, err;
2913 omac_state omac;
2914 unsigned char key[16], dst[MAXBLOCKSIZE];
2915 unsigned long dstlen;
2916
2917 /* register Rijndael */
2918 if (register_cipher(&rijndael_desc) == -1) {
2919 printf("Error registering Rijndael\n");
2920 return -1;
2921 }
2922
2923 /* get index of Rijndael in cipher descriptor table */
2924 idx = find_cipher("rijndael");
2925
2926 /* we would make up our symmetric key in "key[]" here */
2927
2928 /* start the OMAC */
2929 if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
2930 printf("Error setting up omac: %s\n", error_to_string(err));
2931 return -1;
2932 }
2933
2934 /* process a few octets */
2935 if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
2936 printf("Error processing omac: %s\n", error_to_string(err));
2937 return -1;
2938 }
2939
2940 /* get result (presumably to use it somehow...) */
2941 dstlen = sizeof(dst);
2942 if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
2943 printf("Error finishing omac: %s\n", error_to_string(err));
2944 return -1;
2945 }
2946 printf("The omac is %lu bytes long\n", dstlen);
2947
2948 /* return */
2949 return 0;
2950 }
2951 \end{verbatim}
2952 \end{small}
2953
2954 \mysection{PMAC Support}
2955 The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}}
2956 protocol is another MAC algorithm that relies solely on a symmetric-key block cipher. It uses essentially the same
2957 API as the provided OMAC code.
2958
2959 A PMAC state is initialized with the following.
2960
2961 \index{pmac\_init()}
2962 \begin{verbatim}
2963 int pmac_init( pmac_state *pmac,
2964 int cipher,
2965 const unsigned char *key,
2966 unsigned long keylen);
2967 \end{verbatim}
2968 Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes. The chosen cipher
2969 must have a 64 or 128 bit block size (e.x. AES).
2970
2971 To MAC data simply send it through the process function.
2972
2973 \index{pmac\_process()}
2974 \begin{verbatim}
2975 int pmac_process( pmac_state *state,
2976 const unsigned char *in,
2977 unsigned long inlen);
2978 \end{verbatim}
2979 This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}. The function is not sensitive to the granularity of the
2980 data. For example,
2981
2982 \begin{verbatim}
2983 pmac_process(&mystate, "hello", 5);
2984 pmac_process(&mystate, " world", 6);
2985 \end{verbatim}
2986
2987 Would produce the same result as,
2988
2989 \begin{verbatim}
2990 pmac_process(&mystate, "hello world", 11);
2991 \end{verbatim}
2992
2993 When a complete message has been processed the following function can be called to compute the message tag.
2994
2995 \index{pmac\_done()}
2996 \begin{verbatim}
2997 int pmac_done( pmac_state *state,
2998 unsigned char *out,
2999 unsigned long *outlen);
3000 \end{verbatim}
3001 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
3002 than the size of the tag it is set to the amount of bytes stored in \textit{out}.
3003
3004 Similar to the OMAC code the file and memory functions are also provided. To PMAC a buffer of memory in one shot use the
3005 following function.
3006
3007 \index{pmac\_memory()}
3008 \begin{verbatim}
3009 int pmac_memory(
3010 int cipher,
3011 const unsigned char *key, unsigned long keylen,
3012 const unsigned char *in, unsigned long inlen,
3013 unsigned char *out, unsigned long *outlen);
3014 \end{verbatim}
3015 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
3016 specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with the same
3017 rules as pmac\_done().
3018
3019 To PMAC a file use
3020 \index{pmac\_file()}
3021 \begin{verbatim}
3022 int pmac_file(
3023 int cipher,
3024 const unsigned char *key, unsigned long keylen,
3025 const char *filename,
3026 unsigned char *out, unsigned long *outlen);
3027 \end{verbatim}
3028
3029 Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes,
3030 and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table. It will store the MAC in \textit{out} with
3031 the same rules as pmac\_done().
3032
3033 To test if the PMAC code is working there is the following function:
3034 \index{pmac\_test()}
3035 \begin{verbatim}
3036 int pmac_test(void);
3037 \end{verbatim}
3038 Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.
3039
3040 \mysection{Pelican MAC}
3041 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
3042 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
3043 as it calls AES directly.
3044
3045 \index{pelican\_init()}
3046 \begin{verbatim}
3047 int pelican_init( pelican_state *pelmac,
3048 const unsigned char *key,
3049 unsigned long keylen);
3050 \end{verbatim}
3051 This will initialize the Pelican state with the given AES key. Once this has been done you can begin processing data.
3052
3053 \index{pelican\_process()}
3054 \begin{verbatim}
3055 int pelican_process( pelican_state *pelmac,
3056 const unsigned char *in,
3057 unsigned long inlen);
3058 \end{verbatim}
3059 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
3060 routine more efficient but you may pass in any length of text. You can call this function as many times as required to process
3061 an entire message.
3062
3063 \index{pelican\_done()}
3064 \begin{verbatim}
3065 int pelican_done(pelican_state *pelmac, unsigned char *out);
3066 \end{verbatim}
3067 This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.
3068
3069 \subsection{Example}
3070
3071 \begin{verbatim}
3072 #include <tomcrypt.h>
3073 int main(void)
3074 {
3075 pelican_state pelstate;
3076 unsigned char key[32], tag[16];
3077 int err;
3078
3079 /* somehow initialize a key */
3080
3081 /* initialize pelican mac */
3082 if ((err = pelican_init(&pelstate, /* the state */
3083 key, /* user key */
3084 32 /* key length in octets */
3085 )) != CRYPT_OK) {
3086 printf("Error initializing Pelican: %s",
3087 error_to_string(err));
3088 return EXIT_FAILURE;
3089 }
3090
3091 /* MAC some data */
3092 if ((err = pelican_process(&pelstate, /* the state */
3093 "hello world", /* data to mac */
3094 11 /* length of data */
3095 )) != CRYPT_OK) {
3096 printf("Error processing Pelican: %s",
3097 error_to_string(err));
3098 return EXIT_FAILURE;
3099 }
3100
3101 /* Terminate the MAC */
3102 if ((err = pelican_done(&pelstate,/* the state */
3103 tag /* where to store the tag */
3104 )) != CRYPT_OK) {
3105 printf("Error terminating Pelican: %s",
3106 error_to_string(err));
3107 return EXIT_FAILURE;
3108 }
3109
3110 /* tag[0..15] has the MAC output now */
3111
3112 return EXIT_SUCCESS;
3113 }
3114 \end{verbatim}
3115
3116 \mysection{XCBC-MAC}
3117 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
3118 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
3119 initialized with the following function:
3120
3121 \index{xcbc\_init()}
3122 \begin{verbatim}
3123 int xcbc_init( xcbc_state *xcbc,
3124 int cipher,
3125 const unsigned char *key,
3126 unsigned long keylen);
3127 \end{verbatim}
3128
3129 This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
3130 by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
3131
3132 \index{LTC\_XCBC\_PURE}
3133 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
3134 interpretted as three keys. If the cipher has a block size of $n$ octets, the first key is then $keylen - 2n$ octets and is the encryption key. The next
3135 $2n$ octets are the $K_1$ and $K_2$ padding keys (used on the last block). For example, to use AES--192 \textit{keylen} should be $24 + 2 \cdot 16 = 56$ octets.
3136 The three keys are interpretted as if they were concatenated in the \textit{key} buffer.
3137
3138
3139 To process data through XCBC--MAC use the following function:
3140
3141 \index{xcbc\_process()}
3142 \begin{verbatim}
3143 int xcbc_process( xcbc_state *state,
3144 const unsigned char *in,
3145 unsigned long inlen);
3146 \end{verbatim}
3147
3148 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,
3149 the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
3150
3151 To compute the MAC tag value use the following function:
3152
3153 \index{xcbc\_done()}
3154 \begin{verbatim}
3155 int xcbc_done( xcbc_state *state,
3156 unsigned char *out,
3157 unsigned long *outlen);
3158 \end{verbatim}
3159
3160 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
3161 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.
3162
3163 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
3164
3165 \index{xcbc\_memory()}
3166 \begin{verbatim}
3167 int xcbc_memory(
3168 int cipher,
3169 const unsigned char *key, unsigned long keylen,
3170 const unsigned char *in, unsigned long inlen,
3171 unsigned char *out, unsigned long *outlen);
3172 \end{verbatim}
3173 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
3174 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().
3175
3176 To xcbc a file use
3177 \index{xcbc\_file()}
3178 \begin{verbatim}
3179 int xcbc_file(
3180 int cipher,
3181 const unsigned char *key, unsigned long keylen,
3182 const char *filename,
3183 unsigned char *out, unsigned long *outlen);
3184 \end{verbatim}
3185
3186 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
3187 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().
3188
3189
3190 To test XCBC--MAC for RFC 3566 compliance use the following function:
3191
3192 \index{xcbc\_test()}
3193 \begin{verbatim}
3194 int xcbc_test(void);
3195 \end{verbatim}
3196
3197 This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
3198 \textbf{CRYPT\_NOP}.
3199
3200 \mysection{F9--MAC}
3201 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
3202 with other ciphers. For LibTomCrypt, the F9--MAC code can use any cipher.
3203
3204 \subsection{Usage Notice}
3205 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
3206 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
3207 a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.
3208
3209 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
3210 with F9--MAC.
3211
3212 \subsection{F9--MAC Functions}
3213 A F9--MAC state is initialized with the following function:
3214 \index{f9\_init()}
3215 \begin{verbatim}
3216 int f9_init( f9_state *f9,
3217 int cipher,
3218 const unsigned char *key,
3219 unsigned long keylen);
3220 \end{verbatim}
3221
3222 This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets. The cipher indicated
3223 by the \textit{cipher} index can be either a 64 or 128--bit block cipher. This will return \textbf{CRYPT\_OK} on success.
3224
3225 To process data through F9--MAC use the following function:
3226 \index{f9\_process()}
3227 \begin{verbatim}
3228 int f9_process( f9_state *state,
3229 const unsigned char *in,
3230 unsigned long inlen);
3231 \end{verbatim}
3232
3233 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,
3234 the granularity of the input is not important but the order is. This will return \textbf{CRYPT\_OK} on success.
3235
3236 To compute the MAC tag value use the following function:
3237
3238 \index{f9\_done()}
3239 \begin{verbatim}
3240 int f9_done( f9_state *state,
3241 unsigned char *out,
3242 unsigned long *outlen);
3243 \end{verbatim}
3244
3245 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
3246 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
3247 \textbf{CRYPT\_OK} on success.
3248
3249 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
3250
3251 \index{f9\_memory()}
3252 \begin{verbatim}
3253 int f9_memory(
3254 int cipher,
3255 const unsigned char *key, unsigned long keylen,
3256 const unsigned char *in, unsigned long inlen,
3257 unsigned char *out, unsigned long *outlen);
3258 \end{verbatim}
3259 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
3260 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().
3261
3262 To F9--MAC a file use
3263 \index{f9\_file()}
3264 \begin{verbatim}
3265 int f9_file(
3266 int cipher,
3267 const unsigned char *key, unsigned long keylen,
3268 const char *filename,
3269 unsigned char *out, unsigned long *outlen);
3270 \end{verbatim}
3271
3272 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
3273 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().
3274
3275
3276 To test f9--MAC for RFC 3566 compliance use the following function:
3277
3278 \index{f9\_test()}
3279 \begin{verbatim}
3280 int f9_test(void);
3281 \end{verbatim}
3282
3283 This will return \textbf{CRYPT\_OK} on success. This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
3284 \textbf{CRYPT\_NOP}.
3285
3286 \mysection{Poly1305--MAC}
3287
3288 The Poly1305--MAC is a cryptographic message authentication code created by Daniel J. Bernstein.
3289 More info at \url{https://en.wikipedia.org/wiki/Poly1305}.
3290
3291 A Poly1305--MAC state is initialized with the following function:
3292 \index{poly1305\_init()}
3293 \begin{verbatim}
3294 int poly1305_init( poly1305_state *st,
3295 const unsigned char *key,
3296 unsigned long keylen);
3297 \end{verbatim}
3298 This will initialize the Poly1305--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (always 32).
3299
3300 To process data through Poly1305--MAC use the following function:
3301 \index{poly1305\_process()}
3302 \begin{verbatim}
3303 int poly1305_process( poly1305_state *st,
3304 const unsigned char *in,
3305 unsigned long inlen);
3306 \end{verbatim}
3307
3308 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}.
3309
3310 To compute the MAC tag value use the following function:
3311 \index{poly1305\_done()}
3312 \begin{verbatim}
3313 int poly1305_done(poly1305_state *st,
3314 unsigned char *mac,
3315 unsigned long *maclen);
3316 \end{verbatim}
3317
3318 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}.
3319 The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
3320 the function returns.
3321
3322 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
3323 \index{poly1305\_memory()}
3324 \begin{verbatim}
3325 int poly1305_memory(const unsigned char *key,
3326 unsigned long keylen,
3327 const unsigned char *in,
3328 unsigned long inlen,
3329 unsigned char *mac,
3330 unsigned long *maclen);
3331 \end{verbatim}
3332 This will compute the Poly1305--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
3333 It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
3334
3335 To Poly1305--MAC a file use
3336 \index{poly1305\_file()}
3337 \begin{verbatim}
3338 int poly1305_file( const char *fname,
3339 const unsigned char *key,
3340 unsigned long keylen,
3341 unsigned char *mac,
3342 unsigned long *maclen);
3343 \end{verbatim}
3344
3345 Which will Poly1305--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
3346 length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as poly1305\_done().
3347
3348 \mysection{BLAKE2s + BLAKE2b MAC}
3349
3350 The BLAKE2s and BLAKE2b are cryptographic message authentication code designed by Jean--Philippe Aumasson,
3351 Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. More info at \url{https://tools.ietf.org/html/rfc7693}.
3352
3353 A BLAKE2s/b--MAC state is initialized with the following function:
3354 \index{blake2smac\_init()}
3355 \begin{verbatim}
3356 int blake2smac_init(blake2smac_state *st,
3357 unsigned long outlen,
3358 const unsigned char *key,
3359 unsigned long keylen);
3360 \end{verbatim}
3361 \index{blake2bmac\_init()}
3362 \begin{verbatim}
3363 int blake2bmac_init(blake2smac_state *st,
3364 unsigned long outlen,
3365 const unsigned char *key,
3366 unsigned long keylen);
3367 \end{verbatim}
3368 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).
3369 The \textit{outlen} specifies the size of the final tag (up to 64 octets).
3370
3371 To process data through BLAKE2s/b--MAC use the following function:
3372 \index{blake2smac\_process()}
3373 \begin{verbatim}
3374 int blake2smac_process( blake2smac_state *st,
3375 const unsigned char *in,
3376 unsigned long inlen);
3377 \end{verbatim}
3378 \index{blake2bmac\_process()}
3379 \begin{verbatim}
3380 int blake2bmac_process( blake2bmac_state *st,
3381 const unsigned char *in,
3382 unsigned long inlen);
3383 \end{verbatim}
3384
3385 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}.
3386
3387 To compute the MAC tag value use the following function:
3388 \index{blake2smac\_done()}
3389 \begin{verbatim}
3390 int blake2smac_done(blake2smac_state *st,
3391 unsigned char *mac,
3392 unsigned long *maclen);
3393 \end{verbatim}
3394 \index{blake2bmac\_done()}
3395 \begin{verbatim}
3396 int blake2bmac_done(blake2bmac_state *st,
3397 unsigned char *mac,
3398 unsigned long *maclen);
3399 \end{verbatim}
3400
3401 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}.
3402 The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
3403 the function returns.
3404
3405 Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
3406 \index{blake2smac\_memory()}
3407 \begin{verbatim}
3408 int blake2smac_memory(const unsigned char *key,
3409 unsigned long keylen,
3410 const unsigned char *in,
3411 unsigned long inlen,
3412 unsigned char *mac,
3413 unsigned long *maclen);
3414 \end{verbatim}
3415 \index{blake2bmac\_memory()}
3416 \begin{verbatim}
3417 int blake2bmac_memory(const unsigned char *key,
3418 unsigned long keylen,
3419 const unsigned char *in,
3420 unsigned long inlen,
3421 unsigned char *mac,
3422 unsigned long *maclen);
3423 \end{verbatim}
3424 This will compute the BLAKE2s/b--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
3425 It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().
3426
3427 To BLAKE2s/b--MAC a file use
3428 \index{blake2smac\_file()}
3429 \begin{verbatim}
3430 int blake2smac_file( const char *fname,
3431 const unsigned char *key,
3432 unsigned long keylen,
3433 unsigned char *mac,
3434 unsigned long *maclen);
3435 \end{verbatim}
3436 \index{blake2bmac\_file()}
3437 \begin{verbatim}
3438 int blake2bmac_file( const char *fname,
3439 const unsigned char *key,
3440 unsigned long keylen,
3441 unsigned char *mac,
3442 unsigned long *maclen);
3443 \end{verbatim}
3444
3445 Which will BLAKE2s/b--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
3446 length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().
3447
3448 \chapter{Pseudo-Random Number Generators}
3449 \mysection{Core Functions}
3450 The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well. A cryptographic PRNG is
3451 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)
3452 key generation. There is a universal structure called \textit{prng\_state}. To initialize a PRNG call:
3453 \index{PRNG start}
3454 \begin{verbatim}
3455 int XXX_start(prng_state *prng);
3456 \end{verbatim}
3457
3458 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
3459 entropy. Ideally you'd have some OS level source to tap like in UNIX. To add entropy to the PRNG call:
3460 \index{PRNG add\_entropy}
3461 \begin{verbatim}
3462 int XXX_add_entropy(const unsigned char *in,
3463 unsigned long inlen,
3464 prng_state *prng);
3465 \end{verbatim}
3466 Which returns {\bf CRYPT\_OK} if the entropy was accepted. Once you think you have enough entropy you call another
3467 function to put the entropy into action.
3468 \index{PRNG ready}
3469 \begin{verbatim}
3470 int XXX_ready(prng_state *prng);
3471 \end{verbatim}
3472
3473 Which returns {\bf CRYPT\_OK} if it is ready. Finally to actually read bytes call:
3474 \index{PRNG read}
3475 \begin{verbatim}
3476 unsigned long XXX_read(unsigned char *out,
3477 unsigned long outlen,
3478 prng_state *prng);
3479 \end{verbatim}
3480
3481 Which returns the number of bytes read from the PRNG. When you are finished with a PRNG state you call
3482 the following.
3483
3484 \index{PRNG done}
3485 \begin{verbatim}
3486 void XXX_done(prng_state *prng);
3487 \end{verbatim}
3488
3489 This will terminate a PRNG state and free any memory (if any) allocated. To export a PRNG state
3490 so that you can later resume the PRNG call the following.
3491
3492 \index{PRNG export}
3493 \begin{verbatim}
3494 int XXX_export(unsigned char *out,
3495 unsigned long *outlen,
3496 prng_state *prng);
3497 \end{verbatim}
3498
3499 This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes. The idea of
3500 the export is meant to be used as a \textit{seed file}. That is, when the program starts up there will not likely
3501 be that much entropy available. To import a state to seed a PRNG call the following function.
3502
3503 \index{PRNG import}
3504 \begin{verbatim}
3505 int XXX_import(const unsigned char *in,
3506 unsigned long inlen,
3507 prng_state *prng);
3508 \end{verbatim}
3509
3510 This will call the start and add\_entropy functions of the given PRNG. It will use the state in
3511 \textit{in} of length \textit{inlen} as the initial seed. You must pass the same seed length as was exported
3512 by the corresponding export function.
3513
3514 Note that importing a state will not \textit{resume} the PRNG from where it left off. That is, if you export
3515 a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
3516 specifically equal the 8 bytes you generated previously.
3517
3518 When a program is first executed the normal course of operation is:
3519
3520 \begin{enumerate}
3521 \item Gather entropy from your sources for a given period of time or number of events.
3522 \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
3523 \end{enumerate}
3524
3525 When your program is finished you simply call the export function and save the state to a medium (disk,
3526 flash memory, etc). The next time your application starts up you can detect the state, feed it to the
3527 import function and go on your way. It is ideal that (as soon as possible) after start up you export a
3528 fresh state. This helps in the case that the program aborts or the machine is powered down without
3529 being given a chance to exit properly.
3530
3531 Note that even if you have a state to import it is important to add new entropy to the state. However,
3532 there is less pressure to do so.
3533
3534 To test a PRNG for operational conformity call the following functions.
3535
3536 \index{PRNG test}
3537 \begin{verbatim}
3538 int XXX_test(void);
3539 \end{verbatim}
3540
3541 This will return \textbf{CRYPT\_OK} if PRNG is operating properly.
3542
3543 \subsection{Remarks}
3544
3545 It is possible to be adding entropy and reading from a PRNG at the same time. For example, if you first seed the PRNG
3546 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
3547 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
3548 checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.
3549
3550 \subsection{Example}
3551 Below is a simple snippet to read 10 bytes from Yarrow. It is important to note that this snippet is {\bf NOT} secure since
3552 the entropy added is not random.
3553
3554 \begin{verbatim}
3555 #include <tomcrypt.h>
3556 int main(void)
3557 {
3558 prng_state prng;
3559 unsigned char buf[10];
3560 int err;
3561
3562 /* start it */
3563 if ((err = yarrow_start(&prng)) != CRYPT_OK) {
3564 printf("Start error: %s\n", error_to_string(err));
3565 }
3566 /* add entropy */
3567 if ((err = yarrow_add_entropy("hello world", 11, &prng))
3568 != CRYPT_OK) {
3569 printf("Add_entropy error: %s\n", error_to_string(err));
3570 }
3571 /* ready and read */
3572 if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
3573 printf("Ready error: %s\n", error_to_string(err));
3574 }
3575 printf("Read %lu bytes from yarrow\n",
3576 yarrow_read(buf, sizeof(buf), &prng));
3577 return 0;
3578 }
3579 \end{verbatim}
3580
3581 \mysection{PRNG Descriptors}
3582 \index{PRNG Descriptor}
3583 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
3584 format of an element is:
3585 \begin{verbatim}
3586 struct _prng_descriptor {
3587 char *name;
3588 int export_size; /* size in bytes of exported state */
3589
3590 int (*start) (prng_state *);
3591
3592 int (*add_entropy)(const unsigned char *, unsigned long,
3593 prng_state *);
3594
3595 int (*ready) (prng_state *);
3596
3597 unsigned long (*read)(unsigned char *, unsigned long len,
3598 prng_state *);
3599
3600 void (*done)(prng_state *);
3601
3602 int (*pexport)(unsigned char *, unsigned long *, prng_state *);
3603
3604 int (*pimport)(const unsigned char *, unsigned long, prng_state *);
3605
3606 int (*test)(void);
3607 };
3608 \end{verbatim}
3609
3610 To find a PRNG in the descriptor table the following function can be used:
3611 \index{find\_prng()}
3612 \begin{verbatim}
3613 int find_prng(const char *name);
3614 \end{verbatim}
3615 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
3616 the index into the descriptor table.
3617
3618 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.
3619 They are the following:
3620 \index{register\_prng()} \index{unregister\_prng()}
3621 \begin{verbatim}
3622 int register_prng(const struct _prng_descriptor *prng);
3623 int unregister_prng(const struct _prng_descriptor *prng);
3624 \end{verbatim}
3625
3626 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
3627 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
3628 will return \textbf{CRYPT\_OK} if the PRNG was found and removed. Otherwise, it returns \textbf{CRYPT\_ERROR}.
3629
3630 \subsection{PRNGs Provided}
3631 \begin{figure}[H]
3632 \begin{center}
3633 \begin{small}
3634 \begin{tabular}{|c|c|l|}
3635 \hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
3636 \hline ChaCha20 & chacha20\_prng\_desc & Stream Cipher PRNG (recommended, fast) \\
3637 \hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended, secure) \\
3638 \hline RC4 & rc4\_desc & Stream Cipher PRNG \\
3639 \hline SOBER-128 & sober128\_desc & Stream Cipher PRNG \\
3640 \hline sprng & sprng\_desc & Secure PRNG using the System RNG \\
3641 \hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
3642 \hline
3643 \end{tabular}
3644 \end{small}
3645 \end{center}
3646 \caption{List of Provided PRNGs}
3647 \end{figure}
3648
3649 \subsubsection{Yarrow}
3650 Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
3651 (keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.
3652
3653 \textit{Note:} This PRNG is still secure for most tasks but is no longer recommended. Users
3654 should use Fortuna or ChaCha20 instead.
3655
3656 \subsubsection{Fortuna}
3657
3658 Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
3659 usage. It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
3660 to work with most cipher and hash combos based on which you have chosen to build into the library.} while
3661 providing more security.
3662
3663 Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
3664 and SHA--256 hash function. Technically, Fortuna will work with any block cipher that accepts a 256--bit
3665 key, and any hash that produces at least a 256--bit output. However, to make the implementation simpler
3666 it has been fixed to those choices.
3667
3668 Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
3669 added to the PRNG learn far less about the state than that of Yarrow. Without getting into to many
3670 details Fortuna has the ability to recover from state determination attacks where the attacker starts
3671 to learn information from the PRNGs output about the internal state. Yarrow on the other hand, cannot
3672 recover from that problem until new entropy is added to the pool and put to use through the ready() function.
3673
3674 \subsubsection{RC4}
3675
3676 RC4 is an old stream cipher that can also double duty as a PRNG in a pinch. You key RC4 by
3677 calling add\_entropy(), and setup the key by calling ready().
3678
3679 You really should not use RC4 for cryptographical purposes, it's broken.
3680
3681 \subsubsection{SOBER-128}
3682
3683 SOBER--128 is a stream cipher designed by the QUALCOMM Australia team. Like RC4, you key it by
3684 calling add\_entropy(). There is no need to call ready() for this PRNG as it does not do anything.
3685
3686 Note: this cipher has several oddities about how it operates. The first call to add\_entropy() sets the cipher's key.
3687 Every other time call to the add\_entropy() function sets the cipher's IV variable. The IV mechanism allows you to
3688 encrypt several messages with the same key, and not re--use the same key material.
3689
3690 Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
3691 you pass it on the \textbf{first} call to add\_entropy(). All buffers sent to add\_entropy() must have a length
3692 that is a multiple of four bytes.
3693
3694 Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it. In this manner, you can use
3695 sober128\_read() as an encrypt (and decrypt) function.
3696
3697 Since SOBER--128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
3698 key it from the output of Fortuna (or Yarrow), and use it to encrypt messages. It is also ideal for
3699 simulations which need a high quality (and fast) stream of bytes.
3700
3701 \subsubsection{ChaCha20}
3702
3703 ChaCha20 is a fast stream cipher built on a pseudorandom function designed by Daniel J. Bernstein.
3704 It can also double duty as a PRNG.
3705
3706 It is recommended to use 40 bytes of truly random bytes for initialization.
3707
3708 The implementation supports adding entropy via the add\_entropy() function while already being operational.
3709
3710 \subsubsection{Example Usage}
3711 \begin{small}
3712 \begin{verbatim}
3713 #include <tomcrypt.h>
3714 int main(void)
3715 {
3716 prng_state prng;
3717 unsigned char buf[32];
3718 int err;
3719
3720 if ((err = rc4_start(&prng)) != CRYPT_OK) {
3721 printf("RC4 init error: %s\n", error_to_string(err));
3722 exit(-1);
3723 }
3724
3725 /* use "key" as the key */
3726 if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
3727 printf("RC4 add entropy error: %s\n", error_to_string(err));
3728 exit(-1);
3729 }
3730
3731 /* setup RC4 for use */
3732 if ((err = rc4_ready(&prng)) != CRYPT_OK) {
3733 printf("RC4 ready error: %s\n", error_to_string(err));
3734 exit(-1);
3735 }
3736
3737 /* encrypt buffer */
3738 strcpy(buf,"hello world");
3739 if (rc4_read(buf, 11, &prng) != 11) {
3740 printf("RC4 read error\n");
3741 exit(-1);
3742 }
3743 return 0;
3744 }
3745 \end{verbatim}
3746 \end{small}
3747 To decrypt you have to do the exact same steps.
3748
3749 \mysection{The Secure RNG}
3750 \index{Secure RNG}
3751 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
3752 by performing some computation on fresh input bits. Possibly the hardest thing to get correctly in a cryptosystem is the
3753 PRNG. Computers are deterministic that try hard not to stray from pre--determined paths. This makes gathering entropy needed to seed a PRNG
3754 a hard task.
3755
3756 There is one small function that may help on certain platforms:
3757 \index{rng\_get\_bytes()}
3758 \begin{verbatim}
3759 unsigned long rng_get_bytes(
3760 unsigned char *buf,
3761 unsigned long len,
3762 void (*callback)(void));
3763 \end{verbatim}
3764
3765 Which will try one of three methods of getting random data. The first is to open the popular \textit{/dev/random} device which
3766 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.}.
3767 The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG. The third method is an ANSI C
3768 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
3769 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
3770 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
3771 any RNG source. There is a function to help setup a PRNG as well:
3772 \index{rng\_make\_prng()}
3773 \begin{verbatim}
3774 int rng_make_prng( int bits,
3775 int wprng,
3776 prng_state *prng,
3777 void (*callback)(void));
3778 \end{verbatim}
3779 This will try to initialize the prng with a state of at least \textit{bits} of entropy. The \textit{callback} parameter works much like
3780 the callback in \textit{rng\_get\_bytes()}. It is highly recommended that you use this function to setup your PRNGs unless you have a
3781 platform where the RNG does not work well. Example usage of this function is given below:
3782
3783 \begin{small}
3784 \begin{verbatim}
3785 #include <tomcrypt.h>
3786 int main(void)
3787 {
3788 ecc_key mykey;
3789 prng_state prng;
3790 int err;
3791
3792 /* register yarrow */
3793 if (register_prng(&yarrow_desc) == -1) {
3794 printf("Error registering Yarrow\n");
3795 return -1;
3796 }
3797
3798 /* setup the PRNG */
3799 if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL))
3800 != CRYPT_OK) {
3801 printf("Error setting up PRNG, %s\n", error_to_string(err));
3802 return -1;
3803 }
3804
3805 /* make a 192-bit ECC key */
3806 if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey))
3807 != CRYPT_OK) {
3808 printf("Error making key: %s\n", error_to_string(err));
3809 return -1;
3810 }
3811 return 0;
3812 }
3813 \end{verbatim}
3814 \end{small}
3815
3816 \subsection{The Secure PRNG Interface}
3817 \index{sprng\_desc}
3818 It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
3819 as the PK API. This simplifies the cryptosystem on platforms where the secure RNG is fast. The secure PRNG never
3820 requires to be started, that is you need not call the start, add\_entropy, or ready functions. For example, consider
3821 the previous example using this PRNG.
3822
3823 \begin{small}
3824 \begin{verbatim}
3825 #include <tomcrypt.h>
3826 int main(void)
3827 {
3828 ecc_key mykey;
3829 int err;
3830
3831 /* register SPRNG */
3832 if (register_prng(&sprng_desc) == -1) {
3833 printf("Error registering SPRNG\n");
3834 return -1;
3835 }
3836
3837 /* make a 192-bit ECC key */
3838 if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey))
3839 != CRYPT_OK) {
3840 printf("Error making key: %s\n", error_to_string(err));
3841 return -1;
3842 }
3843 return 0;
3844 }
3845 \end{verbatim}
3846 \end{small}
3847
3848 \chapter{RSA Public Key Cryptography}
3849
3850 \mysection{Introduction}
3851 RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography. In the specifications are
3852 padding algorithms for encryption and signatures. The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
3853 To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.
3854
3855 \mysection{PKCS \#1 Padding}
3856 PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function. Note: the
3857 signature padding does \textbf{not} include the ASN.1 padding required. That is performed by the rsa\_sign\_hash\_ex() function
3858 documented later on in this chapter.
3859
3860 \subsection{PKCS \#1 v1.5 Encoding}
3861 The following function performs PKCS \#1 v1.5 padding:
3862 \index{pkcs\_1\_v1\_5\_encode()}
3863 \begin{verbatim}
3864 int pkcs_1_v1_5_encode(
3865 const unsigned char *msg,
3866 unsigned long msglen,
3867 int block_type,
3868 unsigned long modulus_bitlen,
3869 prng_state *prng,
3870 int prng_idx,
3871 unsigned char *out,
3872 unsigned long *outlen);
3873 \end{verbatim}
3874
3875 This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets. The \textit{block\_type} parameter must be set to
3876 \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}
3877 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
3878 longer than the modulus which helps allocate the correct output buffer size.
3879
3880 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.
3881
3882 \subsection{PKCS \#1 v1.5 Decoding}
3883 The following function performs PKCS \#1 v1.5 de--padding:
3884 \index{pkcs\_1\_v1\_5\_decode()}
3885 \begin{verbatim}
3886 int pkcs_1_v1_5_decode(
3887 const unsigned char *msg,
3888 unsigned long msglen,
3889 int block_type,
3890 unsigned long modulus_bitlen,
3891 unsigned char *out,
3892 unsigned long *outlen,
3893 int *is_valid);
3894 \end{verbatim}
3895 \index{LTC\_PKCS\_1\_EME} \index{LTC\_PKCS\_1\_EMSA}
3896 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
3897 \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
3898 \textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.
3899
3900 \mysection{PKCS \#1 v2.1 Encryption}
3901 PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation. As far as this portion of
3902 the library is concerned we are only dealing with th OAEP padding of the message.
3903
3904 \subsection{OAEP Encoding}
3905
3906 The following function performs PKCS \#1 v2.1 encryption padding:
3907
3908 \index{pkcs\_1\_oaep\_encode()}
3909 \begin{alltt}
3910 int pkcs_1_oaep_encode(
3911 const unsigned char *msg,
3912 unsigned long msglen,
3913 const unsigned char *lparam,
3914 unsigned long lparamlen,
3915 unsigned long modulus_bitlen,
3916 prng_state *prng,
3917 int prng_idx,
3918 int hash_idx,
3919 unsigned char *out,
3920 unsigned long *outlen);
3921 \end{alltt}
3922
3923 This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded. The \textit{lparam} variable is an additional system specific
3924 tag that can be applied to the encoding. This is useful to identify which system encoded the message. If no variance is desired then
3925 \textit{lparam} can be set to \textbf{NULL}.
3926
3927 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
3928 \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
3929 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
3930 sized input message. \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.
3931 The padded message is stored in \textit{out} along with the length in \textit{outlen}.
3932
3933 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
3934 $m - 2h - 2$. For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.
3935
3936 Note that when the message is padded it still has not been RSA encrypted. You must pass the output of this function to
3937 rsa\_exptmod() to encrypt it.
3938
3939 \subsection{OAEP Decoding}
3940
3941 \index{pkcs\_1\_oaep\_decode()}
3942 \begin{alltt}
3943 int pkcs_1_oaep_decode(
3944 const unsigned char *msg,
3945 unsigned long msglen,
3946 const unsigned char *lparam,
3947 unsigned long lparamlen,
3948 unsigned long modulus_bitlen,
3949 int hash_idx,
3950 unsigned char *out,
3951 unsigned long *outlen,
3952 int *res);
3953 \end{alltt}
3954
3955 This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder. \textit{msg} is the
3956 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
3957 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
3958 and must match what was used during encoding. Similarly the \textit{hash\_idx} index into the hash descriptor table must match what was used
3959 during encoding.
3960
3961 If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a
3962 $1$ in \textit{res}. If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
3963 it returns an error code.
3964
3965 \mysection{PKCS \#1 Digital Signatures}
3966
3967 \subsection{PSS Encoding}
3968 PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.
3969
3970 \index{pkcs\_1\_pss\_encode()}
3971 \begin{alltt}
3972 int pkcs_1_pss_encode(
3973 const unsigned char *msghash,
3974 unsigned long msghashlen,
3975 unsigned long saltlen,
3976 prng_state *prng,
3977 int prng_idx,
3978 int hash_idx,
3979 unsigned long modulus_bitlen,
3980 unsigned char *out,
3981 unsigned long *outlen);
3982 \end{alltt}
3983
3984 This function assumes the message to be PSS encoded has previously been hashed. The input hash \textit{msghash} is of length
3985 \textit{msghashlen}. PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
3986 \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
3987 number generator information required for the salt.
3988
3989 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
3990 of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.
3991
3992 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().
3993
3994 \subsection{PSS Decoding}
3995
3996 To decode a PSS encoded signature block you have to use the following.
3997
3998 \index{pkcs\_1\_pss\_decode()}
3999 \begin{alltt}
4000 int pkcs_1_pss_decode(
4001 const unsigned char *msghash,
4002 unsigned long msghashlen,
4003 const unsigned char *sig,
4004 unsigned long siglen,
4005 unsigned long saltlen,
4006 int hash_idx,
4007 unsigned long modulus_bitlen,
4008 int *res);
4009 \end{alltt}
4010 This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
4011 \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,
4012 it is set to zero. The rest of the parameters are as in the PSS encode call.
4013
4014 It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.
4015
4016 \mysection{RSA Key Operations}
4017 \subsection{Background}
4018
4019 RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown
4020 factorization. Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
4021 not strictly equivalent.
4022
4023 The system begins with with two primes $p$ and $q$ and their product $N = pq$. The order or \textit{Euler totient} of the
4024 multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
4025 $\mbox{lcm}(p - 1, q - 1)$. The public key consists of the composite $N$ and some integer $e$ such that
4026 $\mbox{gcd}(e, \phi(N)) = 1$. The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
4027 often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.
4028
4029 A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
4030 $1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$. Since finding the inverse exponent $d$
4031 given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
4032 $C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$. Similarly the owner of the private key
4033 can sign a message by \textit{decrypting} it. Others can verify it by \textit{encrypting} it.
4034
4035 Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
4036 Ideally $e$ should be larger than $100$ to prevent direct analysis. For example, if $e$ is three and you do not pad
4037 the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
4038 The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
4039 designed for fast exponentiation (requires 16 squarings and one multiplication).
4040
4041 It is important to pad the input to RSA since it has particular mathematical structure. For instance
4042 $M_1^dM_2^d = (M_1M_2)^d$ which can be used to forge a signature. Suppose $M_3 = M_1M_2$ is a message you want
4043 to have a forged signature for. Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
4044 together. Similar tricks can be used to deduce plaintexts from ciphertexts. It is important not only to sign
4045 the hash of documents only but also to pad the inputs with data to remove such structure.
4046
4047 \subsection{RSA Key Generation}
4048
4049 For RSA routines a single \textit{rsa\_key} structure is used. To make a new RSA key call:
4050 \index{rsa\_make\_key()}
4051 \begin{verbatim}
4052 int rsa_make_key(prng_state *prng,
4053 int wprng,
4054 int size,
4055 long e,
4056 rsa_key *key);
4057 \end{verbatim}
4058
4059 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.
4060 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
4061 trivial math attacks, and not super slow. The \textit{key} parameter is where the constructed key is placed. All keys must be at
4062 least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).
4063
4064 \index{rsa\_free()}
4065 Note: the \textit{rsa\_make\_key()} function allocates memory at run--time when you make the key. Make sure to call
4066 \textit{rsa\_free()} (see below) when you are finished with the key. If \textit{rsa\_make\_key()} fails it will automatically
4067 free the memory allocated.
4068
4069 \index{PK\_PRIVATE} \index{PK\_PUBLIC}
4070 There are two types of RSA keys. The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}. The first type is a private
4071 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
4072 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.
4073 It takes the form of a RSAPublicKey (PKCS \#1 compliant).
4074
4075 \subsection{RSA Exponentiation}
4076 To do raw work with the RSA function, that is without padding, use the following function:
4077 \index{rsa\_exptmod()}
4078 \begin{verbatim}
4079 int rsa_exptmod(const unsigned char *in,
4080 unsigned long inlen,
4081 unsigned char *out,
4082 unsigned long *outlen,
4083 int which,
4084 rsa_key *key);
4085 \end{verbatim}
4086 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
4087 in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e}
4088 (i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).
4089
4090 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.
4091
4092 \subsection{RSA Key Size}
4093 To fetch the key size of an RSA key, use the following function:
4094 \index{rsa\_get\_size()}
4095 \begin{verbatim}
4096 int rsa_get_size(rsa_key *key);
4097 \end{verbatim}
4098 This can be used to determine the modulus size of an RSA key.
4099
4100 \mysection{RSA Key Encryption}
4101 Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
4102 To facilitate encrypting short keys the following functions have been provided.
4103
4104 \index{rsa\_encrypt\_key()}
4105 \begin{verbatim}
4106 int rsa_encrypt_key(
4107 const unsigned char *in,
4108 unsigned long inlen,
4109 unsigned char *out,
4110 unsigned long *outlen,
4111 const unsigned char *lparam,
4112 unsigned long lparamlen,
4113 prng_state *prng,
4114 int prng_idx,
4115 int hash_idx,
4116 rsa_key *key);
4117 \end{verbatim}
4118 This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
4119 in \textit{out} of length \textit{outlen} octets. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
4120 to \index{pkcs\_1\_oaep\_encode()} pkcs\_1\_oaep\_encode().
4121
4122 \subsection{Extended Encryption}
4123 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
4124 encryption function:
4125
4126 \index{rsa\_encrypt\_key\_ex()}
4127 \begin{verbatim}
4128 int rsa_encrypt_key_ex(
4129 const unsigned char *in,
4130 unsigned long inlen,
4131 unsigned char *out,
4132 unsigned long *outlen,
4133 const unsigned char *lparam,
4134 unsigned long lparamlen,
4135 prng_state *prng,
4136 int prng_idx,
4137 int hash_idx,
4138 int padding,
4139 rsa_key *key);
4140 \end{verbatim}
4141
4142 \index{LTC\_PKCS\_1\_OAEP} \index{LTC\_PKCS\_1\_V1\_5}
4143 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
4144 \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 encryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 encryption.
4145
4146 When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
4147
4148 \mysection{RSA Key Decryption}
4149 \index{rsa\_decrypt\_key()}
4150 \begin{verbatim}
4151 int rsa_decrypt_key(
4152 const unsigned char *in,
4153 unsigned long inlen,
4154 unsigned char *out,
4155 unsigned long *outlen,
4156 const unsigned char *lparam,
4157 unsigned long lparamlen,
4158 int hash_idx,
4159 int *stat,
4160 rsa_key *key);
4161 \end{verbatim}
4162 This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
4163 \textit{out} of length \textit{outlen}. The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
4164 to pkcs\_1\_oaep\_decode().
4165
4166 If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$. Otherwise, it is set to $1$.
4167
4168 \subsection{Extended Decryption}
4169 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
4170 decryption function:
4171
4172 \index{rsa\_decrypt\_key\_ex()}
4173 \begin{verbatim}
4174 int rsa_decrypt_key_ex(
4175 const unsigned char *in,
4176 unsigned long inlen,
4177 unsigned char *out,
4178 unsigned long *outlen,
4179 const unsigned char *lparam,
4180 unsigned long lparamlen,
4181 int hash_idx,
4182 int padding,
4183 int *stat,
4184 rsa_key *key);
4185 \end{verbatim}
4186
4187 Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.
4188 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.
4189
4190 When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).
4191
4192
4193 \mysection{RSA Signature Generation}
4194 Similar to RSA key encryption RSA is also used to \textit{digitally sign} message digests (hashes). To facilitate this
4195 process the following functions have been provided.
4196
4197 \index{rsa\_sign\_hash()}
4198 \begin{verbatim}
4199 int rsa_sign_hash(const unsigned char *in,
4200 unsigned long inlen,
4201 unsigned char *out,
4202 unsigned long *outlen,
4203 prng_state *prng,
4204 int prng_idx,
4205 int hash_idx,
4206 unsigned long saltlen,
4207 rsa_key *key);
4208 \end{verbatim}
4209
4210 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
4211 \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.
4212
4213 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
4214 hash the message being signed. The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small. A good
4215 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
4216 the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.
4217
4218 \subsection{Extended Signatures}
4219
4220 As of v1.15, the library supports both v1.5 and v2.1 signatures. The extended signature generation function has the following prototype:
4221
4222 \index{rsa\_sign\_hash\_ex()}
4223 \begin{verbatim}
4224 int rsa_sign_hash_ex(
4225 const unsigned char *in,
4226 unsigned long inlen,
4227 unsigned char *out,
4228 unsigned long *outlen,
4229 int padding,
4230 prng_state *prng,
4231 int prng_idx,
4232 int hash_idx,
4233 unsigned long saltlen,
4234 rsa_key *key);
4235 \end{verbatim}
4236
4237 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
4238 \textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets. The \textit{padding} parameter
4239 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
4240 v2.1 signature.
4241
4242 \index{LTC\_PKCS\_1\_V1\_5\_NA1}
4243 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
4244 \textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter. This option has been introduced to provide compatibilty to SSL3.0 implementations
4245 which implemented this.
4246
4247 When generating a standard v1.5 signature the \textit{prng}, and \textit{prng\_idx} parameters are ignored.
4248 When generating a v1.5 signature without ASN.1 decoding additionally the textit{hash\_idx} parameter is ignored.
4249
4250 \mysection{RSA Signature Verification}
4251 \index{rsa\_verify\_hash()}
4252 \begin{verbatim}
4253 int rsa_verify_hash(const unsigned char *sig,
4254 unsigned long siglen,
4255 const unsigned char *msghash,
4256 unsigned long msghashlen,
4257 int hash_idx,
4258 unsigned long saltlen,
4259 int *stat,
4260 rsa_key *key);
4261 \end{verbatim}
4262
4263 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
4264 and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
4265
4266 If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash}
4267 value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
4268
4269 \subsection{RSA Signature Salt Length}
4270
4271 The v2.1 signature algorithm requires a salt length to be able to properly
4272 encode resp. decode. To fetch the maximum possible salt length this function
4273 is provided:
4274
4275 \index{rsa\_sign\_saltlen\_get\_max()}
4276 \begin{verbatim}
4277 int rsa_sign_saltlen_get_max(int hash_idx, rsa_key *key);
4278 \end{verbatim}
4279
4280 As stated in the PKCS\#1 RFC3447 "Typical salt lengths in octets are hLen
4281 (the length of the output of the hash function Hash) and 0".
4282 This function is provided to be able to use other lengths as well and to make
4283 sure at runtime that the RSA key can handle the desired salt length.
4284
4285 \subsection{Extended Verification}
4286
4287 As of v1.15, the library supports both v1.5 and v2.1 signature verification. The extended signature verification function has the following prototype:
4288
4289 \index{rsa\_verify\_hash\_ex()}
4290 \begin{verbatim}
4291 int rsa_verify_hash_ex(
4292 const unsigned char *sig,
4293 unsigned long siglen,
4294 const unsigned char *hash,
4295 unsigned long hashlen,
4296 int padding,
4297 int hash_idx,
4298 unsigned long saltlen,
4299 int *stat,
4300 rsa_key *key);
4301 \end{verbatim}
4302
4303 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
4304 and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.
4305
4306 If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash}
4307 value, \textit{res} is set to $0$. Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.
4308
4309 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
4310 \textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification.
4311
4312 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
4313 \textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter.
4314
4315 When performing a standard v1.5 verification the \textit{saltlen} parameter is ignored.
4316 When performing a v1.5 verification without ASN.1 decoding additionally the \textit{hash\_idx} parameter is ignored.
4317
4318
4319 \mysection{RSA Encryption Example}
4320 \begin{small}
4321 \begin{verbatim}
4322 #include <tomcrypt.h>
4323 int main(void)
4324 {
4325 int err, hash_idx, prng_idx, res;
4326 unsigned long l1, l2;
4327 unsigned char pt[16], pt2[16], out[1024];
4328 rsa_key key;
4329
4330 /* register prng/hash */
4331 if (register_prng(&sprng_desc) == -1) {
4332 printf("Error registering sprng");
4333 return EXIT_FAILURE;
4334 }
4335
4336 /* register a math library (in this case TomsFastMath)
4337 ltc_mp = tfm_desc;
4338
4339 if (register_hash(&sha1_desc) == -1) {
4340 printf("Error registering sha1");
4341 return EXIT_FAILURE;
4342 }
4343 hash_idx = find_hash("sha1");
4344 prng_idx = find_prng("sprng");
4345
4346 /* make an RSA-1024 key */
4347 if ((err = rsa_make_key(NULL, /* PRNG state */
4348 prng_idx, /* PRNG idx */
4349 1024/8, /* 1024-bit key */
4350 65537, /* we like e=65537 */
4351 &key) /* where to store the key */
4352 ) != CRYPT_OK) {
4353 printf("rsa_make_key %s", error_to_string(err));
4354 return EXIT_FAILURE;
4355 }
4356
4357 /* fill in pt[] with a key we want to send ... */
4358 l1 = sizeof(out);
4359 if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
4360 16, /* data is 16 bytes long */
4361 out, /* where to store ciphertext */
4362 &l1, /* length of ciphertext */
4363 "TestApp", /* our lparam for this program */
4364 7, /* lparam is 7 bytes long */
4365 NULL, /* PRNG state */
4366 prng_idx, /* prng idx */
4367 hash_idx, /* hash idx */
4368 &key) /* our RSA key */
4369 ) != CRYPT_OK) {
4370 printf("rsa_encrypt_key %s", error_to_string(err));
4371 return EXIT_FAILURE;
4372 }
4373
4374 /* now let's decrypt the encrypted key */
4375 l2 = sizeof(pt2);
4376 if ((err = rsa_decrypt_key(out, /* encrypted data */
4377 l1, /* length of ciphertext */
4378 pt2, /* where to put plaintext */
4379 &l2, /* plaintext length */
4380 "TestApp", /* lparam for this program */
4381 7, /* lparam is 7 bytes long */
4382 hash_idx, /* hash idx */
4383 &res, /* validity of data */
4384 &key) /* our RSA key */
4385 ) != CRYPT_OK) {
4386 printf("rsa_decrypt_key %s", error_to_string(err));
4387 return EXIT_FAILURE;
4388 }
4389 /* if all went well pt == pt2, l2 == 16, res == 1 */
4390 }
4391 \end{verbatim}
4392 \end{small}
4393
4394 \mysection{RSA Key Format}
4395
4396 The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as
4397 RSAPublicKey and RSAPrivateKey. Additionally, the OpenSSL key format is supported as well.
4398
4399 \subsection{RSA Key Export}
4400 To export a RSA key use the following function.
4401
4402 \index{rsa\_export()}
4403 \begin{verbatim}
4404 int rsa_export(unsigned char *out,
4405 unsigned long *outlen,
4406 int type,
4407 rsa_key *key);
4408 \end{verbatim}
4409
4410 This will export the RSA key depending on the value of \textit{type}.
4411
4412 The RSAPublicKey (PKCS \#1 type) format will be used for the public key,
4413 indicated by \textbf{PK\_PUBLIC}.
4414 The RSAPrivateKey (PKCS \#1 type) format will be used for the private key,
4415 indicated by \textbf{PK\_PRIVATE}.
4416
4417 As of v1.18.0 this function can also export OpenSSL-compatible formatted public RSA keys.
4418 By OR'ing \textbf{PK\_STD} and \textbf{PK\_PUBLIC} the public key will be exported
4419 in the SubjectPublicKeyInfo (X.509 type) format.
4420
4421 \subsection{RSA Key Import}
4422 To import a RSA key use one of the following function.
4423
4424 \subsubsection{Import from standard formats}
4425
4426 This will import the key stored in \textit{in} of length inlen and import it to \textit{key}.
4427
4428 These formats are normally distributed in the PEM format, consisting of a label defining the content and base64 encoded DER-serialized data.
4429
4430 All the import functions expect binary DER data.
4431
4432 \index{rsa\_import()}
4433 \begin{verbatim}
4434 int rsa_import(const unsigned char *in,
4435 unsigned long inlen,
4436 rsa_key *key);
4437 \end{verbatim}
4438
4439 This function can import both RSAPublicKey and RSAPrivateKey formats.
4440
4441 As of v1.06 this function can also import OpenSSL DER formatted public RSA keys. They are essentially encapsulated RSAPublicKeys. LibTomCrypt will
4442 import the key, strip off the additional data and fill in the \textit{rsa\_key} structure.
4443
4444 \index{rsa\_import\_pkcs8()}
4445 \begin{verbatim}
4446 int rsa_import_pkcs8(const unsigned char *in,
4447 unsigned long inlen,
4448 const void *passwd,
4449 unsigned long passwdlen,
4450 rsa_key *key);
4451 \end{verbatim}
4452
4453 This function can import RSA private keys serialized in PKCS\#8 format.
4454
4455 It provides a \textit{password} parameter for the encrypted PKCS\#8 format, but this functionality is currently NOT implemented.
4456
4457 \index{rsa\_import\_x509()}
4458 \begin{verbatim}
4459 int rsa_import_x509(const unsigned char *in,
4460 unsigned long inlen,
4461 rsa_key *key);
4462 \end{verbatim}
4463
4464 This function can import the RSA public key from a X.509 certificate.
4465
4466 \subsubsection{Import from plain big numbers}
4467
4468 \index{rsa\_set\_key()}
4469 \begin{verbatim}
4470 int rsa_set_key(const unsigned char *N,
4471 unsigned long Nlen,
4472 const unsigned char *e,
4473 unsigned long elen,
4474 const unsigned char *d,
4475 unsigned long dlen,
4476 rsa_key *key);
4477 \end{verbatim}
4478
4479 This function can import the plain RSA key parameters \textit{N}, \textit{e} and \textit{d}.
4480 The parameter \textit{d} is optional and only required when importing a private key.
4481
4482 \index{rsa\_set\_factors()}
4483 \begin{verbatim}
4484 int rsa_set_factors(const unsigned char *p,
4485 unsigned long plen,
4486 const unsigned char *q,
4487 unsigned long qlen,
4488 rsa_key *key);
4489 \end{verbatim}
4490
4491 This function can import the plain RSA key factors \textit{p} and \textit{q}.
4492
4493 \index{rsa\_set\_crt\_params()}
4494 \begin{verbatim}
4495 int rsa_set_crt_params(const unsigned char *dP,
4496 unsigned long dPlen,
4497 const unsigned char *dQ,
4498 unsigned long dQlen,
4499 const unsigned char *qP,
4500 unsigned long qPlen,
4501 rsa_key *key);
4502 \end{verbatim}
4503
4504 This function can import the plain RSA CRT (chinese remainder theorem) parameters \textit{dP}, \textit{dQ} and \textit{qP}.
4505
4506 After importing \textit{p}, \textit{q}, \textit{dP}, \textit{dQ} and \textit{qP}
4507 the library can perfrom the optimized CRT calculations on private key operations.
4508
4509 \chapter{Diffie-Hellman Key Exchange}
4510
4511 \mysection{Background}
4512
4513 Diffie-Hellman was the original public key system proposed. The system is based upon the group structure
4514 of finite fields. For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
4515 generates a large sub-group of prime order (for unique values of $x$).
4516
4517 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
4518 ``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$. The key exchange part of
4519 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
4520 a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.
4521
4522 From this public encryption and signatures can be developed. The trivial way to encrypt (for example) using a public key
4523 $y$ is to perform the key exchange offline. The sender invents a key $k$ and its public copy
4524 $k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
4525 the message with. Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
4526 symmetric cipher.
4527
4528 It is important that the order of the sub-group that $g$ generates not only be large but also prime. There are
4529 discrete logarithm algorithms that take $\sqrt r$ time given the order $r$. The discrete logarithm can be computed
4530 modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem. In the cases where
4531 $r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.
4532
4533 To thwart such attacks the primes and bases in the library have been designed and fixed. Given a prime $p$ the order of
4534 the sub-group generated is a large prime namely ${p - 1} \over 2$. Such primes are known as ``strong primes'' and the
4535 smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.
4536
4537 \mysection{Core Functions}
4538
4539 This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums. The routines
4540 provided are relatively easy to use and only take two function calls to negotiate a shared key. There is a structure
4541 called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use. The first set of routines
4542 are to make a Diffie-Hellman private key pair:
4543 \index{dh\_make\_key()}
4544 \begin{verbatim}
4545 int dh_set_pg_groupsize(int groupsize, dh_key *key);
4546 int dh_generate_key(prng_state *prng, int wprng, dh_key *key);
4547 \end{verbatim}
4548 The ``groupsize'' is the size of the modulus you want in bytes. Currently support sizes are 96 to 1024 bytes which correspond
4549 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
4550 specifying a size not explicitly supported by the library it will round {\em up} to the next key size. If the size is
4551 above 512 it will return an error. So if you pass ``groupsize == 32'' it will use a 768 bit key but if you pass
4552 ``groupsize == 20000'' it will return an error. The primes and generators used are built-into the library and were designed
4553 to meet very specific goals. The primes are strong primes which means that if $p$ is the prime then
4554 $p-1$ is equal to $2r$ where $r$ is a large prime. The bases are chosen to generate a group of order $r$ to prevent
4555 leaking a bit of the key. This means the bases generate a very large prime order group which is good to make cryptanalysis
4556 hard.
4557
4558 The next two routines are for exporting/importing Diffie-Hellman keys in/from DER encoded ASN.1. This is useful for transport
4559 over communication mediums.
4560
4561 \index{dh\_export()} \index{dh\_import()}
4562 \begin{verbatim}
4563 int dh_export(unsigned char *out, unsigned long *outlen,
4564 int type, dh_key *key);
4565
4566 int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
4567 \end{verbatim}
4568
4569 The ASN.1 sequence used to represent a DH key is as following:
4570
4571 \begin{verbatim}
4572 DiffieHellmanKey ::= SEQUENCE {
4573 version Version,
4574 flags Flags,
4575 p INTEGER, -- prime
4576 g INTEGER, -- base/group
4577 n INTEGER -- either x when private key or y when public key }
4578
4579 Version ::= INTEGER { v1(0) }
4580
4581 Flags ::= BIT STRING {
4582 privateKey (0) -- this BIT is '1' if it's a private key
4583 -- or '0' if it's a public key
4584 }
4585 \end{verbatim}
4586
4587 These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
4588 Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails.
4589
4590 You can free a ``dh\_key'' using:
4591 \begin{verbatim}
4592 void dh_free(dh_key *key);
4593 \end{verbatim}
4594 After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
4595 with the other user using:
4596 \index{dh\_shared\_secret()}
4597 \begin{verbatim}
4598 int dh_shared_secret(dh_key *private_key,
4599 dh_key *public_key,
4600 unsigned char *out, unsigned long *outlen);
4601 \end{verbatim}
4602
4603 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
4604 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
4605 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
4606 key:
4607 \index{dh\_get\_groupsize()}
4608 \begin{verbatim}
4609 int dh_get_groupsize(dh_key *key);
4610 \end{verbatim}
4611 This returns the size in bytes of the modulus chosen for that key.
4612
4613 \mysection{Other Diffie-Hellman Functions}
4614
4615 To be able to import Diffie-Hellman keys LibTomCrypt provides several API functions.
4616 \\
4617
4618 To import the prime and group from binary format:
4619 \index{dh\_set\_pg()}
4620 \begin{verbatim}
4621 int dh_set_pg(const unsigned char *p, unsigned long plen,
4622 const unsigned char *g, unsigned long glen,
4623 dh_key *key);
4624 \end{verbatim}
4625 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}.
4626 \\
4627
4628 To import the prime and group from an ASN.1 encoded DHparam Sequence:
4629 \index{dh\_set\_pg\_dhparam()}
4630 \begin{verbatim}
4631 int dh_set_pg_dhparam(const unsigned char *dhparam, unsigned long dhparamlen, dh_key *key);
4632 \end{verbatim}
4633 This sets the parameters in \textit{dhparam} of \textit{dhparamlen} in the DH key \textit{key}.
4634 \\
4635
4636 To import a private or public key from binary data:
4637 \index{dh\_set\_key()}
4638 \begin{verbatim}
4639 int dh_set_key(const unsigned char *in, unsigned long inlen, int type, dh_key *key);
4640 \end{verbatim}
4641 This will import, depending on \textit{type} which can be either \textit{PK\_PRIVATE} or \textit{PK\_PUBLIC},
4642 the according part of the DH key \textit{key} from \textit{in} of length \textit{inlen}.
4643 After import the key will be verified and in case of an error it will be free'd.
4644
4645 \mysection{Remarks on Usage}
4646 Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something. An
4647 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.}:
4648 \newpage
4649 \begin{small}
4650 \begin{verbatim}
4651 int establish_secure_socket(int sock, int mode, unsigned char *key,
4652 prng_state *prng, int wprng)
4653 {
4654 unsigned char buf[4096], buf2[4096];
4655 unsigned long x, len;
4656 int res, err, inlen;
4657 dh_key mykey, theirkey;
4658
4659 /* make up our private key */
4660 if ((err = dh_set_pg_groupsize(128, &mykey)) != CRYPT_OK) {
4661 return err;
4662 }
4663 if ((err = dh_generate_key(prng, wprng, &mykey)) != CRYPT_OK) {
4664 return err;
4665 }
4666
4667 /* export our key as public */
4668 x = sizeof(buf);
4669 if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
4670 res = err;
4671 goto done2;
4672 }
4673
4674 if (mode == 0) {
4675 /* mode 0 so we send first */
4676 if (send(sock, buf, x, 0) != x) {
4677 res = CRYPT_ERROR;
4678 goto done2;
4679 }
4680
4681 /* get their key */
4682 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
4683 res = CRYPT_ERROR;
4684 goto done2;
4685 }
4686 } else {
4687 /* mode >0 so we send second */
4688 if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
4689 res = CRYPT_ERROR;
4690 goto done2;
4691 }
4692
4693 if (send(sock, buf, x, 0) != x) {
4694 res = CRYPT_ERROR;
4695 goto done2;
4696 }
4697 }
4698
4699 if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
4700 res = err;
4701 goto done2;
4702 }
4703
4704 /* make shared secret */
4705 x = sizeof(buf);
4706 if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
4707 res = err;
4708 goto done;
4709 }
4710
4711 /* hash it */
4712 len = 16; /* default is MD5 so "key" must be at least 16 bytes long */
4713 if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
4714 res = err;
4715 goto done;
4716 }
4717
4718 /* clean up and return */
4719 res = CRYPT_OK;
4720 done:
4721 dh_free(&theirkey);
4722 done2:
4723 dh_free(&mykey);
4724 zeromem(buf, sizeof(buf));
4725 zeromem(buf2, sizeof(buf2));
4726 return res;
4727 }
4728 \end{verbatim}
4729 \end{small}
4730 \subsection{Remarks on The Snippet}
4731 When the above code snippet is done (assuming all went well) there will be a shared 128-bit key in the ``key'' array
4732 passed to ``establish\_secure\_socket()''.
4733
4734 \chapter{Elliptic Curve Cryptography}
4735
4736 \mysection{Background}
4737 The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
4738 Diffie-Hellman routines in the previous chapter. Elliptic curves (of certain forms) have the benefit that they are harder
4739 to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
4740 of the order of the base point in time. That means if you use a base point of order $2^{192}$ (which would represent a
4741 192-bit key) then the work factor is $2^{96}$ in order to find the secret key.
4742
4743 The curves in this library are taken from the following website:
4744 \begin{verbatim}
4745 http://csrc.nist.gov/cryptval/dss.htm
4746 \end{verbatim}
4747
4748 As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves. These curves were added to
4749 support smaller devices which do not need as large keys for security.
4750
4751 They are all curves over the integers modulo a prime. The curves have the basic equation that is:
4752 \begin{equation}
4753 y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
4754 \end{equation}
4755
4756 The variable $b$ is chosen such that the number of points is nearly maximal. In fact the order of the base points $\beta$
4757 provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$. The curves
4758 range in order from $\approx 2^{112}$ points to $\approx 2^{521}$. According to the source document any key size greater
4759 than or equal to 256-bits is sufficient for long term security.
4760
4761 \mysection{Fixed Point Optimizations}
4762 \index{Fixed Point ECC}
4763 \index{MECC\_FP}
4764 As of v1.12 of LibTomCrypt, support for Fixed Point ECC point multiplication has been added. It is a generic optimization that is
4765 supported by any conforming math plugin. It is enabled by defining \textbf{MECC\_FP} during the build, such as
4766
4767 \begin{verbatim}
4768 CFLAGS="-DTFM_DESC -DMECC_FP" make
4769 \end{verbatim}
4770
4771 which will build LTC using the TFM math library and enabling this new feature. The feature is not enabled by default as it is \textbf{NOT} thread
4772 safe (by default). It supports the LTC locking macros (such as by enabling LTC\_PTHREAD), but by default is not locked.
4773
4774 \index{FP\_ENTRIES}
4775 The optimization works by using a Fixed Point multiplier on any base point you use twice or more in a short period of time. It has a limited size
4776 cache (of FP\_ENTRIES entries) which it uses to hold recent bases passed to ltc\_ecc\_mulmod(). Any base detected to be used twice is sent through the
4777 pre--computation phase, and then the fixed point algorithm can be used. For example, if you use a NIST base point twice in a row, the 2$^{nd}$ and
4778 all subsequent point multiplications with that point will use the faster algorithm.
4779
4780 \index{FP\_LUT}
4781 The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the
4782 value the faster the algorithm will be but the more memory it will take. The memory usage is $3 \cdot 2^{FP\_LUT}$ integers which by default
4783 with TFM amounts to about 400kB of memory. Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount. Memory is only used by a cache entry
4784 if it is active. Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,
4785
4786 \begin{verbatim}
4787 CFLAGS="-DTFM_DESC -DMECC_FP -DFP_ENTRIES=8 -DFP_LUT=6" make
4788 \end{verbatim}
4789
4790 \begin{flushleft}
4791 \index{FP\_SIZE} \index{TFM} \index{tfm.h}
4792 would define a window of 6 bits and limit the cache to 8 entries. Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h). It defaults
4793 to 4096 bits (512 bytes) which is way more than what is required by ECC. At most, you need 1152 bits to accommodate ECC--521. If you're only using (say)
4794 ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
4795 \end{flushleft}
4796
4797 \mysection{Key Format}
4798 LibTomCrypt uses a unique format for ECC public and private keys. While ANSI X9.63 partially specifies key formats, it does it in a less than ideally simple manner. \
4799 In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves. The format of the keys is as follows:
4800
4801 \index{ECC Key Format}
4802 \begin{small}
4803 \begin{verbatim}
4804 ECCPublicKey ::= SEQUENCE {
4805 flags BIT STRING(0), -- public/private flag (always zero),
4806 keySize INTEGER, -- Curve size (in bits) divided by eight
4807 -- and rounded down, e.g. 521 => 65
4808 pubkey.x INTEGER, -- The X co-ordinate of the public key point
4809 pubkey.y INTEGER, -- The Y co-ordinate of the public key point
4810 }
4811
4812 ECCPrivateKey ::= SEQUENCE {
4813 flags BIT STRING(1), -- public/private flag (always one),
4814 keySize INTEGER, -- Curve size (in bits) divided by eight
4815 -- and rounded down, e.g. 521 => 65
4816 pubkey.x INTEGER, -- The X co-ordinate of the public key point
4817 pubkey.y INTEGER, -- The Y co-ordinate of the public key point
4818 secret.k INTEGER, -- The secret key scalar
4819 }
4820 \end{verbatim}
4821 \end{small}
4822
4823 The first flags bit denotes whether the key is public (zero) or private (one).
4824
4825 \vfil
4826
4827 \mysection{ECC Curve Parameters}
4828 The library uses the following structure to describe an elliptic curve. This is used internally, as well as by the new
4829 extended ECC functions which allow the user to specify their own curves.
4830
4831 \index{ltc\_ecc\_set\_type}
4832 \begin{verbatim}
4833 /** Structure defines a NIST GF(p) curve */
4834 typedef struct {
4835 /** The size of the curve in octets */
4836 int size;
4837
4838 /** name of curve */
4839 char *name;
4840
4841 /** The prime that defines the field (encoded in hex) */
4842 char *prime;
4843
4844 /** The fields B param (hex) */
4845 char *B;
4846
4847 /** The order of the curve (hex) */
4848 char *order;
4849
4850 /** The x co-ordinate of the base point on the curve (hex) */
4851 char *Gx;
4852
4853 /** The y co-ordinate of the base point on the curve (hex) */
4854 char *Gy;
4855 } ltc_ecc_set_type;
4856 \end{verbatim}
4857
4858 The curve must be of the form $y^2 = x^3 - 3x + b$, and all of the integer parameters are encoded in hexadecimal format.
4859
4860 \mysection{Core Functions}
4861 \subsection{ECC Key Generation}
4862 There is a key structure called \textit{ecc\_key} used by the ECC functions. There is a function to make a key:
4863 \index{ecc\_make\_key()}
4864 \begin{verbatim}
4865 int ecc_make_key(prng_state *prng,
4866 int wprng,
4867 int keysize,
4868 ecc_key *key);
4869 \end{verbatim}
4870
4871 The \textit{keysize} is the size of the modulus in bytes desired. Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
4872 correspond to key sizes of 112, 128, 160, 192, 224, 256, 384, and 521 bits respectively. If you pass a key size that is between any key size it will round
4873 the keysize up to the next available one.
4874
4875 The function will free any internally allocated resources if there is an error.
4876
4877 \subsection{Extended Key Generation}
4878 As of v1.16, the library supports an extended key generation routine which allows the user to specify their own curve. It is specified as follows:
4879
4880 \index{ecc\_make\_key\_ex()}
4881 \begin{verbatim}
4882 int ecc_make_key_ex(
4883 prng_state *prng,
4884 int wprng,
4885 ecc_key *key,
4886 const ltc_ecc_set_type *dp);
4887 \end{verbatim}
4888
4889 This function generates a random ECC key over the curve specified by the parameters by \textit{dp}. The rest of the parameters are equivalent to
4890 those from the original key generation function.
4891
4892 \subsection{ECC Key Free}
4893 To free the memory allocated by a ecc\_make\_key(), ecc\_make\_key\_ex(), ecc\_import(), or ecc\_import\_ex() call use the following function:
4894 \index{ecc\_free()}
4895 \begin{verbatim}
4896 void ecc_free(ecc_key *key);
4897 \end{verbatim}
4898
4899 \subsection{ECC Key Export}
4900 To export an ECC key using the LibTomCrypt format call the following function:
4901 \index{ecc\_export()}
4902 \begin{verbatim}
4903 int ecc_export(unsigned char *out,
4904 unsigned long *outlen,
4905 int type,
4906 ecc_key *key);
4907 \end{verbatim}
4908 This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.
4909
4910 \subsection{ECC Key Import}
4911 The following function imports a LibTomCrypt format ECC key:
4912 \index{ecc\_import()}
4913 \begin{verbatim}
4914 int ecc_import(const unsigned char *in,
4915 unsigned long inlen,
4916 ecc_key *key);
4917 \end{verbatim}
4918 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
4919 any allocated memory automatically.
4920
4921 \subsection{Extended Key Import}
4922
4923 The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
4924 \index{ecc\_import\_ex()}
4925 \begin{verbatim}
4926 int ecc_import_ex(const unsigned char *in,
4927 unsigned long inlen,
4928 ecc_key *key,
4929 const ltc_ecc_set_type *dp);
4930 \end{verbatim}
4931 This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets. The key is stored in
4932 the ECC structure pointed to by \textit{key}. The curve is specified by the parameters pointed to by \textit{dp}. The function will free
4933 all internally allocated memory upon error.
4934
4935 \subsection{ANSI X9.63 Export}
4936 The following function exports an ECC public key in the ANSI X9.63 format:
4937
4938 \index{ecc\_ansi\_x963\_export()}
4939 \begin{verbatim}
4940 int ecc_ansi_x963_export( ecc_key *key,
4941 unsigned char *out,
4942 unsigned long *outlen);
4943 \end{verbatim}
4944 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
4945 section 4.3.6 of the standard. It does not allow for the export of private keys.
4946
4947 \subsection{ANSI X9.63 Import}
4948 The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:
4949
4950 \index{ecc\_ansi\_x963\_import()}
4951 \begin{verbatim}
4952 int ecc_ansi_x963_import(const unsigned char *in,
4953 unsigned long inlen,
4954 ecc_key *key);
4955 \end{verbatim}
4956 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
4957 \textit{key}. The function will free any allocated memory upon error.
4958
4959 \subsection{Extended ANSI X9.63 Import}
4960 The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:
4961
4962 \index{ecc\_ansi\_x963\_import\_ex()}
4963 \begin{verbatim}
4964 int ecc_ansi_x963_import_ex(const unsigned char *in,
4965 unsigned long inlen,
4966 ecc_key *key,
4967 ltc_ecc_set_type *dp);
4968 \end{verbatim}
4969 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}.
4970 The imported key is stored in the ECC key pointed to by \textit{key}. The function will free any allocated memory upon error.
4971
4972 \subsection{ECC Shared Secret}
4973 To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
4974 \index{ecc\_shared\_secret()}
4975 \begin{verbatim}
4976 int ecc_shared_secret( ecc_key *private_key,
4977 ecc_key *public_key,
4978 unsigned char *out,
4979 unsigned long *outlen);
4980 \end{verbatim}
4981 The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.
4982 Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.
4983
4984 \mysection{ECC Diffie-Hellman Encryption}
4985 ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext. It is not strictly ANSI X9.63 compliant
4986 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
4987 encrypts a short string (no longer than the message digest) using this technique:
4988
4989 \subsection{ECC-DH Encryption}
4990 \index{ecc\_encrypt\_key()}
4991 \begin{verbatim}
4992 int ecc_encrypt_key(const unsigned char *in,
4993 unsigned long inlen,
4994 unsigned char *out,
4995 unsigned long *outlen,
4996 prng_state *prng,
4997 int wprng,
4998 int hash,
4999 ecc_key *key);
5000 \end{verbatim}
5001
5002 As the name implies this function encrypts a (symmetric) key, and is not intended for encrypting long messages directly. It will encrypt the
5003 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
5004 hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext. The ciphertext is stored in
5005 the output buffer pointed to by \textit{out} of length \textit{outlen} octets.
5006
5007 The data is encrypted to the public ECC \textit{key} such that only the holder of the private key can decrypt the payload. To have multiple
5008 recipients multiple call to this function for each public ECC key is required.
5009
5010 \subsection{ECC-DH Decryption}
5011 \index{ecc\_decrypt\_key()}
5012 \begin{verbatim}
5013 int ecc_decrypt_key(const unsigned char *in,
5014 unsigned long inlen,
5015 unsigned char *out,
5016 unsigned long *outlen,
5017 ecc_key *key);
5018 \end{verbatim}
5019
5020 This function will decrypt an encrypted payload. The \textit{key} provided must be the private key corresponding to the public key
5021 used during encryption. If the wrong key is provided the function will not specifically return an error code. It is important
5022 to use some form of challenge response in that case (e.g. compute a MAC of a known string).
5023
5024 \subsection{ECC Encryption Format}
5025 The packet format for the encrypted keys is the following ASN.1 SEQUENCE:
5026
5027 \begin{verbatim}
5028 ECCEncrypt ::= SEQUENCE {
5029 hashID OBJECT IDENTIFIER, -- OID of hash used
5030 pubkey OCTET STRING , -- Encapsulated ECCPublicKey
5031 skey OCTET STRING -- xor of plaintext and
5032 --"hash of shared secret"
5033 }
5034 \end{verbatim}
5035
5036 \mysection{EC DSA Signatures}
5037
5038 There are also functions to sign and verify messages. They use the ANSI X9.62 EC-DSA algorithm to generate and verify signatures in the
5039 ANSI X9.62 format.
5040
5041 \subsection{EC-DSA Signature Generation}
5042 To sign a message digest (hash) use the following function:
5043
5044 \index{ecc\_sign\_hash()}
5045 \begin{verbatim}
5046 int ecc_sign_hash(const unsigned char *in,
5047 unsigned long inlen,
5048 unsigned char *out,
5049 unsigned long *outlen,
5050 prng_state *prng,
5051 int wprng,
5052 ecc_key *key);
5053 \end{verbatim}
5054
5055 This function will EC--DSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets. The signature
5056 will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets. The function requires a properly seeded PRNG, and
5057 the ECC \textit{key} provided must be a private key.
5058
5059 \index{ecc\_sign\_hash\_rfc7518()}
5060 \begin{verbatim}
5061 int ecc_sign_hash_rfc7518(const unsigned char *in,
5062 unsigned long inlen,
5063 unsigned char *out,
5064 unsigned long *outlen,
5065 prng_state *prng,
5066 int wprng,
5067 ecc_key *key);
5068 \end{verbatim}
5069
5070 This function creates the same EC--DSA signature as \textit{ecc\_sign\_hash} only the output format is different.
5071 The format follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}, sometimes it is also called plain signature.
5072
5073 \subsection{EC-DSA Signature Verification}
5074 \index{ecc\_verify\_hash()}
5075 \begin{verbatim}
5076 int ecc_verify_hash(const unsigned char *sig,
5077 unsigned long siglen,
5078 const unsigned char *hash,
5079 unsigned long hashlen,
5080 int *stat,
5081 ecc_key *key);
5082 \end{verbatim}
5083
5084 This function will verify the EC-DSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest
5085 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:
5086 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.
5087 The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
5088 The function \textit{ecc\_verify\_hash} implements signature format according to X9.62 EC--DSA, and the output is compliant for GF(p) curves.
5089
5090 \index{ecc\_verify\_hash\_rfc7518()}
5091 \begin{verbatim}
5092 int ecc_verify_hash_rfc7518(const unsigned char *sig,
5093 unsigned long siglen,
5094 const unsigned char *hash,
5095 unsigned long hashlen,
5096 int *stat,
5097 ecc_key *key);
5098 \end{verbatim}
5099
5100 This function validate the EC--DSA signature as \textit{ecc\_verify\_hash} only the signature input format
5101 follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}.
5102
5103 \mysection{ECC Keysizes}
5104 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
5105 work. With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller. For example, if you sign with
5106 SHA256 and an ECC-192 key, you in effect have 96--bits of security.
5107
5108 The library will not warn you if you make this mistake, so it is important to check yourself before using the signatures.
5109
5110 \chapter{Digital Signature Algorithm}
5111 \mysection{Introduction}
5112 The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
5113 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.
5114 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
5115 would require only at least 40 bytes.
5116
5117 \mysection{Key Format}
5118 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
5119 now so that others can interoperate with this library.
5120
5121 \begin{verbatim}
5122 DSAPublicKey ::= SEQUENCE {
5123 publicFlags BIT STRING(0), -- must be 0
5124 g INTEGER , -- base generator
5125 -- check that g^q mod p == 1
5126 -- and that 1 < g < p - 1
5127 p INTEGER , -- prime modulus
5128 q INTEGER , -- order of sub-group
5129 -- (must be prime)
5130 y INTEGER , -- public key, specifically,
5131 -- g^x mod p,
5132 -- check that y^q mod p == 1
5133 -- and that 1 < y < p - 1
5134 }
5135
5136 DSAPrivateKey ::= SEQUENCE {
5137 publicFlags BIT STRING(1), -- must be 1
5138 g INTEGER , -- base generator
5139 -- check that g^q mod p == 1
5140 -- and that 1 < g < p - 1
5141 p INTEGER , -- prime modulus
5142 q INTEGER , -- order of sub-group
5143 -- (must be prime)
5144 y INTEGER , -- public key, specifically,
5145 -- g^x mod p,
5146 -- check that y^q mod p == 1
5147 -- and that 1 < y < p - 1
5148 x INTEGER -- private key
5149 }
5150 \end{verbatim}
5151
5152 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,
5153 and easy to work with.
5154
5155 \mysection{Key Generation}
5156 To make a DSA key you must call the following function
5157 \begin{verbatim}
5158 int dsa_make_key(prng_state *prng,
5159 int wprng,
5160 int group_size,
5161 int modulus_size,
5162 dsa_key *key);
5163 \end{verbatim}
5164 The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor. \textit{group\_size} and
5165 \textit{modulus\_size} control the difficulty of forging a signature. Both parameters are in bytes. The larger the
5166 \textit{group\_size} the more difficult a forgery becomes upto a limit. The value of $group\_size$ is limited by
5167 $15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$. Suggested values for the pairs are as follows.
5168
5169 \begin{figure}[H]
5170 \begin{center}
5171 \begin{tabular}{|c|c|c|}
5172 \hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
5173 \hline 80 & 20 & 128 \\
5174 \hline 120 & 30 & 256 \\
5175 \hline 140 & 35 & 384 \\
5176 \hline 160 & 40 & 512 \\
5177 \hline
5178 \end{tabular}
5179 \end{center}
5180 \caption{DSA Key Sizes}
5181 \end{figure}
5182
5183 When you are finished with a DSA key you can call the following function to free the memory used.
5184 \index{dsa\_free()}
5185 \begin{verbatim}
5186 void dsa_free(dsa_key *key);
5187 \end{verbatim}
5188
5189 \mysection{Key Verification}
5190 Each DSA key is composed of the following variables.
5191
5192 \begin{enumerate}
5193 \item $q$ a small prime of magnitude $256^{group\_size}$.
5194 \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
5195 \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$. $h$ can be any non-trivial random
5196 value. For this library they start at $h = 2$ and step until $g$ is not $1$.
5197 \item $x$ a random secret (the secret key) in the range $1 < x < q$
5198 \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
5199 \end{enumerate}
5200
5201 A DSA key is considered valid if it passes all of the following tests.
5202
5203 \begin{enumerate}
5204 \item $q$ must be prime.
5205 \item $p$ must be prime.
5206 \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
5207 \item $g$ must be less than $p$.
5208 \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
5209 \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
5210 \item $1 < y < p - 1$
5211 \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
5212 \end{enumerate}
5213
5214 Tests one and two ensure that the values will at least form a field which is required for the signatures to
5215 function. Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
5216 forgery easier. Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
5217 ensures that the generator actually generates a prime order group. Tests seven and eight ensure that the public key
5218 is within range and belongs to a group of prime order. Note that test eight does not prove that $g$ generated $y$ only
5219 that $y$ belongs to a multiplicative sub-group of order $q$.
5220
5221 The following function will perform these tests.
5222
5223 \index{dsa\_verify\_key()}
5224 \begin{verbatim}
5225 int dsa_verify_key(dsa_key *key, int *stat);
5226 \end{verbatim}
5227
5228 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
5229 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).
5230
5231 \mysection{Signatures}
5232 \subsection{Signature Generation}
5233 To generate a DSA signature call the following function:
5234
5235 \index{dsa\_sign\_hash()}
5236 \begin{verbatim}
5237 int dsa_sign_hash(const unsigned char *in,
5238 unsigned long inlen,
5239 unsigned char *out,
5240 unsigned long *outlen,
5241 prng_state *prng,
5242 int wprng,
5243 dsa_key *key);
5244 \end{verbatim}
5245
5246 Which will sign the data in \textit{in} of length \textit{inlen} bytes. The signature is stored in \textit{out} and the size
5247 of the signature in \textit{outlen}. If the signature is longer than the size you initially specify in \textit{outlen} nothing
5248 is stored and the function returns an error code. The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.
5249
5250 \subsection{Signature Verification}
5251 To verify a hash created with that function use the following function:
5252
5253 \index{dsa\_verify\_hash()}
5254 \begin{verbatim}
5255 int dsa_verify_hash(const unsigned char *sig,
5256 unsigned long siglen,
5257 const unsigned char *hash,
5258 unsigned long inlen,
5259 int *stat,
5260 dsa_key *key);
5261 \end{verbatim}
5262 Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.
5263 It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.
5264
5265 \mysection{DSA Encrypt and Decrypt}
5266 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
5267 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
5268 the ECC encryption format to the DSA algorithm.
5269
5270 \subsection{DSA Encryption}
5271 This function will encrypt a small payload with a recipients public DSA key.
5272
5273 \index{dsa\_encrypt\_key()}
5274 \begin{verbatim}
5275 int dsa_encrypt_key(const unsigned char *in,
5276 unsigned long inlen,
5277 unsigned char *out,
5278 unsigned long *outlen,
5279 prng_state *prng,
5280 int wprng,
5281 int hash,
5282 dsa_key *key);
5283 \end{verbatim}
5284
5285 This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}. The
5286 length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer. The DSA \textit{key} can be
5287 a public key.
5288
5289 \subsection{DSA Decryption}
5290
5291 \index{dsa\_decrypt\_key()}
5292 \begin{verbatim}
5293 int dsa_decrypt_key(const unsigned char *in,
5294 unsigned long inlen,
5295 unsigned char *out,
5296 unsigned long *outlen,
5297 dsa_key *key);
5298 \end{verbatim}
5299 This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
5300 The DSA \textit{key} must be a private key.
5301
5302 \mysection{DSA Key Import and Export}
5303
5304 \subsection{DSA Key Export}
5305 To export a DSA key so that it can be transported use the following function:
5306 \index{dsa\_export()}
5307 \begin{verbatim}
5308 int dsa_export(unsigned char *out,
5309 unsigned long *outlen,
5310 int type,
5311 dsa_key *key);
5312 \end{verbatim}
5313 This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
5314 initialized to the maximum buffer size). The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
5315 depending on whether you want to export a private or public copy of the DSA key.
5316
5317 \subsection{DSA Key Import}
5318 To import an exported DSA key use the following function
5319 :
5320 \index{dsa\_import()}
5321 \begin{verbatim}
5322 int dsa_import(const unsigned char *in,
5323 unsigned long inlen,
5324 dsa_key *key);
5325 \end{verbatim}
5326
5327 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
5328 will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).
5329
5330 \mysection{Other DSA Functions}
5331
5332 The following functions allow to create a DSA key in 2 steps:
5333
5334 \begin{enumerate}
5335 \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()}.
5336 \item Load or generate the actual DSA key -- private (\textit{x} and \textit{y} values) or public (\textit{y} value).
5337 \end{enumerate}
5338
5339 \index{dsa\_set\_pqg()}
5340 \begin{verbatim}
5341 int dsa_set_pqg(const unsigned char *p, unsigned long plen,
5342 const unsigned char *q, unsigned long qlen,
5343 const unsigned char *g, unsigned long glen,
5344 dsa_key *key);
5345 \end{verbatim}
5346
5347 This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary
5348 representation of \textit{p} (with length of \textit{plen}), \textit{q} (with length of \textit{qlen}) and \textit{g} (with length of \textit{glen}).
5349 A simple DSA key validity check (without primality testing) is performed at the end of this function.
5350
5351 \index{dsa\_set\_pqg\_dsaparam()}
5352 \begin{verbatim}
5353 int dsa_set_pqg_dsaparam(const unsigned char *dsaparam,
5354 unsigned long dsaparamlen,
5355 dsa_key *key);
5356 \end{verbatim}
5357
5358 This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary representation
5359 of DSA parameters stored as a binary data in a buffer \textit{dsaparam} (with length of \textit{dsaparamlen}). A simple DSA key validity
5360 check (without primality testing) is performed at the end of this function. The \textit{dsaparam} can be generated via:
5361 \begin{verbatim}
5362 openssl dsaparam 2048 -outform DER -out dsaparam.der
5363 \end{verbatim}
5364
5365 \index{dsa\_generate\_pqg()}
5366 \begin{verbatim}
5367 int dsa_generate_pqg(prng_state *prng,
5368 int wprng,
5369 int group_size,
5370 int modulus_size,
5371 dsa_key *key);
5372 \end{verbatim}
5373
5374 This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure with newly generated random values.
5375 As for the parameters they are the same as by \textit{dsa\_make\_key}.
5376
5377 \index{dsa\_set\_key()}
5378 \begin{verbatim}
5379 int dsa_set_key(const unsigned char *in,
5380 unsigned long inlen,
5381 int type,
5382 dsa_key *key);
5383 \end{verbatim}
5384
5385 This function can be used for setting the actual DSA key. If \textit{type} is \textit{PK\_PRIVATE} then the buffer \textit{in}
5386 (with length of \textit{inlen}) contains a binary representation of \textit{x} part of the key (the public part \textit{y} is computed).
5387 If \textit{type} is \textit{PK\_PUBLIC} then the buffer \textit{in} contains a binary representation of \textit{y} part of the key.
5388
5389 \index{dsa\_generate\_key()}
5390 \begin{verbatim}
5391 int dsa_generate_key(prng_state *prng,
5392 int wprng,
5393 dsa_key *key);
5394 \end{verbatim}
5395
5396 This function generates a private DSA key containing both \textit{x} and \textit{y} parts.
5397
5398 \chapter{Standards Support}
5399 \mysection{ASN.1 Formats}
5400 LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols. The data types
5401 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
5402 format, and two functions have been dedicated to encoding and decoding the format.
5403
5404 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
5405 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:
5406
5407 \index{ltc\_asn1\_list structure}
5408 \begin{verbatim}
5409 typedef struct {
5410 ltc_asn1_type type;
5411 void *data;
5412 unsigned long size;
5413 int used;
5414 struct ltc_asn1_list_ *prev, *next,
5415 *child, *parent;
5416 } ltc_asn1_list;
5417 \end{verbatim}
5418
5419 \index{LTC\_SET\_ASN1 macro}
5420 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
5421 \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
5422 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
5423 \textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.
5424
5425 It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size). An example usage would be:
5426
5427 \begin{small}
5428 \begin{verbatim}
5429 ...
5430 ltc_asn1_list sequence[3];
5431 unsigned long three=3;
5432
5433 LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING, "hello", 5);
5434 LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three, 1);
5435 LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL, NULL, 0);
5436 \end{verbatim}
5437 \end{small}
5438
5439 The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.
5440
5441 \begin{small}
5442 \begin{verbatim}
5443 ...
5444 ltc_asn1_list sequence[3];
5445 unsigned long three=3;
5446 int x=0;
5447 LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING, "hello", 5);
5448 LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three, 1);
5449 LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL, NULL, 0);
5450 \end{verbatim}
5451 \end{small}
5452
5453 \begin{figure}[h]
5454 \begin{center}
5455 \begin{small}
5456 \begin{tabular}{|l|l|}
5457 \hline \textbf{Definition} & \textbf{ASN.1 Type} \\
5458 \hline LTC\_ASN1\_EOL & End of a ASN.1 list structure. \\
5459 \hline LTC\_ASN1\_BOOLEAN & BOOLEAN type \\
5460 \hline LTC\_ASN1\_INTEGER & INTEGER (uses mp\_int) \\
5461 \hline LTC\_ASN1\_SHORT\_INTEGER & INTEGER (32--bit using unsigned long) \\
5462 \hline LTC\_ASN1\_BIT\_STRING & BIT STRING (one bit per char) \\
5463 \hline LTC\_ASN1\_OCTET\_STRING & OCTET STRING (one octet per char) \\
5464 \hline LTC\_ASN1\_NULL & NULL \\
5465 \hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER \\
5466 \hline LTC\_ASN1\_IA5\_STRING & IA5 STRING (one octet per char) \\
5467 \hline LTC\_ASN1\_PRINTABLE\_STRING & PRINTABLE STRING (one octet per char) \\
5468 \hline LTC\_ASN1\_UTF8\_STRING & UTF8 STRING (one wchar\_t per char) \\
5469 \hline LTC\_ASN1\_UTCTIME & UTCTIME (see ltc\_utctime structure) \\
5470 \hline LTC\_ASN1\_CHOICE & CHOICE \\
5471 \hline LTC\_ASN1\_SEQUENCE & SEQUENCE (and SEQUENCE OF) \\
5472 \hline LTC\_ASN1\_SET & SET \\
5473 \hline LTC\_ASN1\_SETOF & SET OF \\
5474 \hline LTC\_ASN1\_RAW\_BIT\_STRING & BIT STRING (one octet per char) \\
5475 \hline LTC\_ASN1\_TELETEX\_STRING & TELETEX STRING (one octet per char) \\
5476 \hline LTC\_ASN1\_CONSTRUCTED & A constructed type that is not SEQUENCE or SET \\
5477 \hline LTC\_ASN1\_CONTEXT\_SPECIFIC & A context-specific type \\
5478 \hline LTC\_ASN1\_GENERALIZEDTIME & GeneralizedTime (see ltc\_generalizedtime structure) \\
5479 \hline
5480 \end{tabular}
5481 \caption{List of ASN.1 Supported Types}
5482 \index{ltc\_asn1\_type}
5483 \end{small}
5484 \end{center}
5485 \end{figure}
5486
5487 \subsection{SEQUENCE Type}
5488 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.
5489
5490 \subsubsection{SEQUENCE Encoding}
5491 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
5492 with the following function.
5493
5494 \index{der\_encode\_sequence()}\index{LTC\_ASN1\_EOL}
5495 \begin{verbatim}
5496 int der_encode_sequence(ltc_asn1_list *list,
5497 unsigned long inlen,
5498 unsigned char *out,
5499 unsigned long *outlen);
5500 \end{verbatim}
5501 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
5502 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}.
5503
5504 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
5505 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
5506 the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.
5507
5508 \subsubsection{SEQUENCE Decoding}
5509
5510 \index{der\_decode\_sequence()}
5511
5512 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
5513 (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
5514 units of the respective type has been loaded.
5515
5516 \begin{verbatim}
5517 int der_decode_sequence(const unsigned char *in,
5518 unsigned long inlen,
5519 ltc_asn1_list *list,
5520 unsigned long outlen);
5521 \end{verbatim}
5522
5523 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.
5524 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.
5525
5526 For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
5527 \begin{enumerate}
5528 \item BIT STRING
5529 \item OCTET STRING
5530 \item OBJECT IDENTIFIER
5531 \item IA5 STRING
5532 \item PRINTABLE STRING
5533 \end{enumerate}
5534
5535 \subsubsection{SEQUENCE Length}
5536
5537 The length of a SEQUENCE can be determined with the following function.
5538
5539 \index{der\_length\_sequence()}
5540 \begin{verbatim}
5541 int der_length_sequence(ltc_asn1_list *list,
5542 unsigned long inlen,
5543 unsigned long *outlen);
5544 \end{verbatim}
5545
5546 This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.
5547
5548 \subsubsection{SEQUENCE Multiple Argument Lists}\index{LTC\_ASN1\_EOL}
5549
5550 For small or simple sequences an encoding or decoding can be performed with one of the following two functions.
5551
5552 \index{der\_encode\_sequence\_multi()}
5553 \index{der\_decode\_sequence\_multi()}
5554
5555 \begin{verbatim}
5556 int der_encode_sequence_multi(unsigned char *out,
5557 unsigned long *outlen, ...);
5558
5559 int der_decode_sequence_multi(const unsigned char *in,
5560 unsigned long inlen, ...);
5561 \end{verbatim}
5562
5563 These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.
5564
5565 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}
5566 and \textit{data} is \textbf{void} pointer. The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.
5567
5568 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
5569 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.
5570
5571 \begin{small}
5572 \begin{verbatim}
5573 unsigned char buf[MAXBUFSIZE];
5574 unsigned long buflen;
5575 int err;
5576
5577 buflen = sizeof(buf);
5578 if ((err =
5579 der_encode_sequence_multi(buf, &buflen,
5580 LTC_ASN1_IA5_STRING, 5UL, "Hello",
5581 LTC_ASN1_IA5_STRING, 7UL, " World!",
5582 LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
5583 // error handling
5584 }
5585 \end{verbatim}
5586 \end{small}
5587
5588 This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively. Note the usage of the \textbf{UL} modifier
5589 on the size parameters. This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.
5590
5591 \subsection{SET and SET OF}
5592
5593 \index{SET} \index{SET OF}
5594 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
5595 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
5596 a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.
5597
5598 \subsubsection{SET Encoding}
5599
5600 SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use. They are encoded with the following function:
5601
5602 \index{der\_encode\_set()}
5603 \begin{verbatim}
5604 int der_encode_set(ltc_asn1_list *list,
5605 unsigned long inlen,
5606 unsigned char *out,
5607 unsigned long *outlen);
5608 \end{verbatim}
5609
5610 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.
5611 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
5612 array (to make the process deterministic).
5613
5614 This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.
5615
5616 \subsubsection{SET Decoding}
5617
5618 The SET type can be decoded with the following function.
5619
5620 \index{der\_decode\_set()}
5621 \begin{verbatim}
5622 int der_decode_set(const unsigned char *in,
5623 unsigned long inlen,
5624 ltc_asn1_list *list,
5625 unsigned long outlen);
5626 \end{verbatim}
5627
5628 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.
5629
5630 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.
5631
5632 \subsubsection{SET Length}
5633 The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.
5634
5635 \subsubsection{SET OF Encoding}
5636 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
5637 used to store objects deterministically based solely on their encoding. It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
5638 use. They are encoded with the following function.
5639
5640 \index{der\_encode\_setof()}
5641 \begin{verbatim}
5642 int der_encode_setof(ltc_asn1_list *list,
5643 unsigned long inlen,
5644 unsigned char *out,
5645 unsigned long *outlen);
5646 \end{verbatim}
5647
5648 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}.
5649
5650 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
5651 means you need at least enough memory to keep an additional copy of the output on the heap.
5652
5653 \subsubsection{SET OF Decoding}
5654 Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().
5655
5656 \subsubsection{SET OF Length}
5657 Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.
5658
5659 \subsection{ASN.1 INTEGER}
5660
5661 To encode or decode INTEGER data types use the following functions.
5662
5663 \index{der\_encode\_integer()}\index{der\_decode\_integer()}\index{der\_length\_integer()}
5664 \begin{verbatim}
5665 int der_encode_integer( void *num,
5666 unsigned char *out,
5667 unsigned long *outlen);
5668
5669 int der_decode_integer(const unsigned char *in,
5670 unsigned long inlen,
5671 void *num);
5672
5673 int der_length_integer( void *num,
5674 unsigned long *len);
5675 \end{verbatim}
5676
5677 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
5678 a bignum to store the value, the \textit{short} INTEGER functions were made available.
5679
5680 \index{der\_encode\_short\_integer()}\index{der\_decode\_short\_integer()}\index{der\_length\_short\_integer()}
5681 \begin{verbatim}
5682 int der_encode_short_integer(unsigned long num,
5683 unsigned char *out,
5684 unsigned long *outlen);
5685
5686 int der_decode_short_integer(const unsigned char *in,
5687 unsigned long inlen,
5688 unsigned long *num);
5689
5690 int der_length_short_integer(unsigned long num,
5691 unsigned long *outlen);
5692 \end{verbatim}
5693
5694 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
5695 and short integer functions can encode and decode each others outputs.
5696
5697 \subsection{ASN.1 BIT STRING}
5698
5699 \index{der\_encode\_bit\_string()}\index{der\_decode\_bit\_string()}\index{der\_length\_bit\_string()}
5700 \begin{verbatim}
5701 int der_encode_bit_string(const unsigned char *in,
5702 unsigned long inlen,
5703 unsigned char *out,
5704 unsigned long *outlen);
5705
5706 int der_decode_bit_string(const unsigned char *in,
5707 unsigned long inlen,
5708 unsigned char *out,
5709 unsigned long *outlen);
5710
5711 int der_length_bit_string(unsigned long nbits,
5712 unsigned long *outlen);
5713 \end{verbatim}
5714
5715 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
5716 as a one bit, and a zero value a zero bit.
5717
5718 \subsection{ASN.1 RAW BIT STRING}
5719
5720 \index{der\_encode\_raw\_bit\_string()}\index{der\_decode\_raw\_bit\_string()}
5721 \begin{verbatim}
5722 int der_encode_raw_bit_string(const unsigned char *in,
5723 unsigned long inlen,
5724 unsigned char *out,
5725 unsigned long *outlen);
5726
5727 int der_decode_raw_bit_string(const unsigned char *in,
5728 unsigned long inlen,
5729 unsigned char *out,
5730 unsigned long *outlen);
5731 \end{verbatim}
5732
5733 These will encode or decode a BIT STRING data type.
5734 The bits are passed in (or read out) using one \textbf{unsigned char} per 8 bit.
5735
5736 This function differs from the normal BIT STRING, as it can be used to directly
5737 process raw binary data and store it to resp. read it from an ASN.1 BIT STRING
5738 data type.
5739
5740 The length function is the same as for the normal BIT STRING \textit{der\_length\_bit\_string()}.
5741
5742 \subsection{ASN.1 OCTET STRING}
5743
5744 \index{der\_encode\_octet\_string()}\index{der\_decode\_octet\_string()}\index{der\_length\_octet\_string()}
5745 \begin{verbatim}
5746 int der_encode_octet_string(const unsigned char *in,
5747 unsigned long inlen,
5748 unsigned char *out,
5749 unsigned long *outlen);
5750
5751 int der_decode_octet_string(const unsigned char *in,
5752 unsigned long inlen,
5753 unsigned char *out,
5754 unsigned long *outlen);
5755
5756 int der_length_octet_string(unsigned long noctets,
5757 unsigned long *outlen);
5758 \end{verbatim}
5759
5760 These will encode or decode an OCTET STRING data type. The octets are stored using one \textbf{unsigned char} each.
5761
5762 \subsection{ASN.1 OBJECT IDENTIFIER}
5763
5764 \index{der\_encode\_object\_identifier()}\index{der\_decode\_object\_identifier()}\index{der\_length\_object\_identifier()}
5765 \begin{verbatim}
5766 int der_encode_object_identifier(unsigned long *words,
5767 unsigned long nwords,
5768 unsigned char *out,
5769 unsigned long *outlen);
5770
5771 int der_decode_object_identifier(const unsigned char *in,
5772 unsigned long inlen,
5773 unsigned long *words,
5774 unsigned long *outlen);
5775
5776 int der_length_object_identifier(unsigned long *words,
5777 unsigned long nwords,
5778 unsigned long *outlen);
5779 \end{verbatim}
5780
5781 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
5782 $0 \ldots 2^{32} - 1$.
5783
5784 \subsection{ASN.1 IA5 STRING}
5785
5786 \index{der\_encode\_ia5\_string()}\index{der\_decode\_ia5\_string()}\index{der\_length\_ia5\_string()}
5787 \begin{verbatim}
5788 int der_encode_ia5_string(const unsigned char *in,
5789 unsigned long inlen,
5790 unsigned char *out,
5791 unsigned long *outlen);
5792
5793 int der_decode_ia5_string(const unsigned char *in,
5794 unsigned long inlen,
5795 unsigned char *out,
5796 unsigned long *outlen);
5797
5798 int der_length_ia5_string(const unsigned char *octets,
5799 unsigned long noctets,
5800 unsigned long *outlen);
5801 \end{verbatim}
5802
5803 These will encode or decode an IA5 STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
5804 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
5805 say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
5806 that the build platform honours the run--time platforms character conventions.
5807
5808 \subsection{ASN.1 TELETEX STRING}
5809
5810 \index{der\_decode\_teletex\_string()}\index{der\_length\_teletex\_string()}
5811 \begin{verbatim}
5812 int der_decode_teletex_string(const unsigned char *in,
5813 unsigned long inlen,
5814 unsigned char *out,
5815 unsigned long *outlen);
5816
5817 int der_length_teletex_string(const unsigned char *octets,
5818 unsigned long noctets,
5819 unsigned long *outlen);
5820 \end{verbatim}
5821
5822 These will decode a TELETEX STRING.
5823 The characters are read in individual \textbf{char} elements.
5824 The internal structure is similar to that of the IA5 STRING implementation, to
5825 be able to provide a stable conversion independent of the build-- and run--time
5826 platform.
5827
5828 \subsection{ASN.1 PRINTABLE STRING}
5829
5830 \index{der\_encode\_printable\_string()}\index{der\_decode\_printable\_string()}\index{der\_length\_printable\_string()}
5831 \begin{verbatim}
5832 int der_encode_printable_string(const unsigned char *in,
5833 unsigned long inlen,
5834 unsigned char *out,
5835 unsigned long *outlen);
5836
5837 int der_decode_printable_string(const unsigned char *in,
5838 unsigned long inlen,
5839 unsigned char *out,
5840 unsigned long *outlen);
5841
5842 int der_length_printable_string(const unsigned char *octets,
5843 unsigned long noctets,
5844 unsigned long *outlen);
5845 \end{verbatim}
5846
5847 These will encode or decode an PRINTABLE STRING. The characters are read or stored in individual \textbf{char} elements. These functions performs internal character
5848 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
5849 say a SPARC machine. Internally, these functions have a table of literal characters and their numerical ASCII values. This provides a stable conversion provided
5850 that the build platform honours the run-time platforms character conventions.
5851
5852 \subsection{ASN.1 UTF8 STRING}
5853
5854 \index{der\_encode\_utf8\_string()}\index{der\_decode\_utf8\_string()}\index{der\_length\_utf8\_string()}
5855 \begin{verbatim}
5856 int der_encode_utf8_string(const wchar_t *in,
5857 unsigned long inlen,
5858 unsigned char *out,
5859 unsigned long *outlen);
5860
5861 int der_decode_utf8_string(const unsigned char *in,
5862 unsigned long inlen,
5863 wchar_t *out,
5864 unsigned long *outlen);
5865
5866 int der_length_utf8_string(const wchar_t *octets,
5867 unsigned long noctets,
5868 unsigned long *outlen);
5869 \end{verbatim}
5870
5871 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
5872 mapping and treat the characters as literals.
5873
5874 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
5875 intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.
5876
5877 \subsection{ASN.1 UTCTIME}
5878
5879 The UTCTIME type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
5880
5881 \index{ltc\_utctime structure}
5882 \begin{verbatim}
5883 typedef struct {
5884 unsigned YY, /* year 00--99 */
5885 MM, /* month 01--12 */
5886 DD, /* day 01--31 */
5887 hh, /* hour 00--23 */
5888 mm, /* minute 00--59 */
5889 ss, /* second 00--59 */
5890 off_dir, /* timezone offset direction 0 == +, 1 == - */
5891 off_hh, /* timezone offset hours */
5892 off_mm; /* timezone offset minutes */
5893 } ltc_utctime;
5894 \end{verbatim}
5895
5896 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
5897 will be subtracted. For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of
5898 \textit{2005, June 20th, 22:04:00} with a time offset of +05h00.
5899
5900 \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
5901 \begin{verbatim}
5902 int der_encode_utctime( ltc_utctime *utctime,
5903 unsigned char *out,
5904 unsigned long *outlen);
5905
5906 int der_decode_utctime(const unsigned char *in,
5907 unsigned long *inlen,
5908 ltc_utctime *out);
5909
5910 int der_length_utctime( ltc_utctime *utctime,
5911 unsigned long *outlen);
5912 \end{verbatim}
5913
5914 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
5915 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.
5916
5917 It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
5918
5919 \subsection{ASN.1 GeneralizedTime}
5920
5921 The GeneralizedTime type is to store a date and time in ASN.1 format. It uses the following structure to organize the time.
5922
5923 \index{ltc\_utctime structure}
5924 \begin{verbatim}
5925 typedef struct {
5926 unsigned YYYY, /* year 0--9999 */
5927 MM, /* month 1--12 */
5928 DD, /* day 1--31 */
5929 hh, /* hour 0--23 */
5930 mm, /* minute 0--59 */
5931 ss, /* second 0--59 */
5932 fs, /* fractional seconds 1--UINT_MAX */
5933 off_dir, /* timezone offset direction 0 == +, 1 == - */
5934 off_hh, /* timezone offset hours */
5935 off_mm; /* timezone offset minutes */
5936 } ltc_generalizedtime;
5937 \end{verbatim}
5938
5939 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
5940 will be subtracted. For instance, the array $\lbrace 2005, 6, 20, 22, 4, 0, 122, 0, 5, 0 \rbrace$ represents the current time of
5941 \textit{2005, June 20th, 22:04:00.122} with a time offset of +05h00.
5942
5943 \index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
5944 \begin{verbatim}
5945 int der_encode_generalizedtime(ltc_generalizedtime *gtime,
5946 unsigned char *out,
5947 unsigned long *outlen);
5948
5949 int der_decode_generalizedtime(const unsigned char *in,
5950 unsigned long *inlen,
5951 ltc_generalizedtime *out);
5952
5953 int der_length_generalizedtime(ltc_generalizedtime *gtime,
5954 unsigned long *outlen);
5955 \end{verbatim}
5956
5957 The encoder will store time in one of the following ASN.1 formats, either \textit{YYYYMMDDhhmmssZ} or
5958 \textit{YYYYMMDDhhmmss$\pm$hhmm} or\textit{YYYYMMDDhhmmss.fsZ} or \textit{YYYYMMDDhhmmss.fs$\pm$hhmm},
5959 and perform minimal error checking on the input.
5960 The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but
5961 rational) useful for catching packet errors.
5962
5963 The fractional seconds are always added in case they are not $0$.
5964 The implementation of fractional seconds is currently unreliable and you can't detect decoded
5965 resp. encode leading $0$'s (e.g. \textit{20170424232717.005Z} would be decoded as
5966 \textit{22. April 2017, 23:27:17.5}).
5967
5968 It is suggested that decoded data be further scrutinized (e.g. days of month in particular).
5969
5970 \subsection{ASN.1 CHOICE}
5971
5972 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
5973 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
5974 type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.
5975
5976 There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.
5977
5978 \index{der\_decode\_choice()}
5979 \begin{verbatim}
5980 int der_decode_choice(const unsigned char *in,
5981 unsigned long *inlen,
5982 ltc_asn1_list *list,
5983 unsigned long outlen);
5984 \end{verbatim}
5985
5986 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
5987 \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
5988 will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.
5989
5990 \subsection{ASN.1 Flexi Decoder}
5991 The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
5992 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
5993 free form.
5994
5995 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}
5996 and \textit{child}. The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
5997 encoded in a SEQUENCE are stored as a child element.
5998
5999 When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the child
6000 pointer points to a new list of items contained within the object.
6001
6002 \index{der\_decode\_sequence\_flexi()}
6003 \index{LTC\_ASN1\_CONSTRUCTED}
6004 \index{LTC\_ASN1\_CONTEXT\_SPECIFIC}
6005 \begin{verbatim}
6006 int der_decode_sequence_flexi(const unsigned char *in,
6007 unsigned long *inlen,
6008 ltc_asn1_list **out);
6009 \end{verbatim}
6010
6011 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
6012 all required memory for the decoding. It stores the number of octets read back into \textit{inlen}.
6013
6014 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
6015 normally. The decoded list \textit{out} will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf{NULL}).
6016
6017 An invalid decoding will terminate the process, and free the allocated memory automatically.
6018
6019 The flexi decoder calls itself when decoding a constructed type. This leads to
6020 a 'child process' that will terminate when it decodes an unkown/invalid
6021 identifier and leaves an allocated but uninitialized child element.
6022 However the parent processing will continue with a "soft-error".
6023 This can be detected by checking for \textit{child} elements with
6024 type \textbf{LTC\_ASN1\_EOL} after decoding.
6025
6026 As of v1.18.0 the flexi decoder will also decode arbitrary constructed types
6027 other than SEQUENCE and SET. The \textit{type} field will be set to
6028 \textbf{LTC\_ASN1\_CONSTRUCTED} and the plain identifier that was indicated in the ASN.1
6029 encoding is stored in the \textit{used} field. Further decoding is done in the
6030 same way as if it were a SEQUENCE or SET.
6031
6032 Also as of v1.18.0 the flexi decoder is capable to handle
6033 \textit{context-specific} encodings. The \textit{type} field will be set to
6034 \textbf{LTC\_ASN1\_CONTEXT\_SPECIFIC} and the plain identifier that was indicated
6035 in the ASN.1 encoding is stored in the \textit{used} field. Encapsulated data
6036 in the \textit{context-specific} encoding is copied to newly allocated memory
6037 and is accessible through the \textit{data} field.
6038
6039 \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
6040 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}
6041 pointer. Currently no function in LibTomCrypt provides this ability.
6042
6043 \subsubsection{Sample Decoding}
6044 Suppose we decode the following structure:
6045 \begin{small}
6046 \begin{verbatim}
6047 User ::= SEQUENCE {
6048 Name IA5 STRING
6049 LoginToken SEQUENCE {
6050 passwdHash OCTET STRING
6051 pubkey ECCPublicKey
6052 }
6053 LastOn UTCTIME
6054 }
6055 \end{verbatim}
6056 \end{small}
6057 \begin{flushleft}and we decoded it with the following code:\end{flushleft}
6058
6059 \begin{small}
6060 \begin{verbatim}
6061 unsigned char inbuf[MAXSIZE];
6062 unsigned long inbuflen;
6063 ltc_asn1_list *list;
6064 int err;
6065
6066 /* somehow fill inbuf/inbuflen */
6067 if ((err = der_decode_sequence_flexi(inbuf, inbuflen, &list)) != CRYPT_OK) {
6068 printf("Error decoding: %s\n", error_to_string(err));
6069 exit(EXIT_FAILURE);
6070 }
6071 \end{verbatim}
6072 \end{small}
6073
6074 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
6075 node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
6076 \begin{small}
6077 \begin{verbatim}
6078 list = list->child;
6079 \end{verbatim}
6080 \end{small}
6081 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
6082 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.
6083 We can walk to this node with the following code:
6084 \begin{small}
6085 \begin{verbatim}
6086 /* list already pointing to 'Name' */
6087 list = list->next->child;
6088 \end{verbatim}
6089 \end{small}
6090 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.
6091 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:
6092 \begin{small}
6093 \begin{verbatim}
6094 list = list->parent->next;
6095 \end{verbatim}
6096 \end{small}
6097 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
6098 can walk up and down the nodes without keeping pointers lying around.
6099
6100
6101 \subsubsection{Shrink'ing a Flexi List}
6102 While decoding the flexi decoder will recursively decode an ASN.1 \textit{constructed} type it will store the decoded list
6103 as well as the plain data that was decoded.
6104 To free up this additional data a shrink function is provided.
6105
6106 \index{der\_sequence\_shrink()}
6107 \begin{verbatim}
6108 void der_sequence_shrink(ltc_asn1_list *in);
6109 \end{verbatim}
6110
6111 This will free all the plain constructed data, but keep the decoded list intact.
6112
6113 \subsubsection{Free'ing a Flexi List}
6114 To free the list use the following function.
6115
6116 \index{der\_sequence\_free()}
6117 \begin{verbatim}
6118 void der_sequence_free(ltc_asn1_list *in);
6119 \end{verbatim}
6120
6121 This will free all of the memory allocated by der\_decode\_sequence\_flexi().
6122
6123 \mysection{Password Based Cryptography}
6124 \subsection{PKCS \#5}
6125 \index{PKCS \#5}
6126 In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted. PKCS \#5
6127 is made up of two algorithms, Algorithm One and Algorithm Two. Algorithm One is the older fairly limited algorithm which has been implemented
6128 for completeness. Algorithm Two is a bit more modern and more flexible to work with.
6129
6130 The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.
6131
6132 \subsection{Algorithm One}
6133 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
6134 people trying to brute force guess the password. The higher the iteration counter the longer the delay. This algorithm also requires a hash
6135 algorithm and produces an output no longer than the output of the hash.
6136
6137 \index{pkcs\_5\_alg1()}
6138 \begin{alltt}
6139 int pkcs_5_alg1(const unsigned char *password,
6140 unsigned long password_len,
6141 const unsigned char *salt,
6142 int iteration_count,
6143 int hash_idx,
6144 unsigned char *out,
6145 unsigned long *outlen)
6146 \end{alltt}
6147 Where \textit{password} is the user's password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
6148 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
6149 on the password. The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.
6150
6151 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
6152 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}.
6153
6154 \index{pkcs\_5\_alg1\_openssl()}
6155 \begin{alltt}
6156 int pkcs_5_alg1_openssl(const unsigned char *password,
6157 unsigned long password_len,
6158 const unsigned char *salt,
6159 int iteration_count,
6160 int hash_idx,
6161 unsigned char *out,
6162 unsigned long *outlen)
6163 \end{alltt}
6164 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!!).
6165 \subsection{Algorithm Two}
6166
6167 Algorithm Two is the recommended algorithm for this task. It allows variable length salts, and can produce outputs larger than the
6168 hash functions output. As such, it can easily be used to derive session keys for ciphers and MACs as well initialization vectors as required
6169 from a single password and invocation of this algorithm.
6170
6171 \index{pkcs\_5\_alg2()}
6172 \begin{alltt}
6173 int pkcs_5_alg2(const unsigned char *password,
6174 unsigned long password_len,
6175 const unsigned char *salt,
6176 unsigned long salt_len,
6177 int iteration_count,
6178 int hash_idx,
6179 unsigned char *out,
6180 unsigned long *outlen)
6181 \end{alltt}
6182 Where \textit{password} is the users password. Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
6183 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
6184 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
6185 \textit{outlen} is stored in \textit{out}.
6186
6187 \begin{verbatim}
6188 /* demo to show how to make session state material
6189 * from a password */
6190 #include <tomcrypt.h>
6191 int main(void)
6192 {
6193 unsigned char password[100], salt[100],
6194 cipher_key[16], cipher_iv[16],
6195 mac_key[16], outbuf[48];
6196 int err, hash_idx;
6197 unsigned long outlen, password_len, salt_len;
6198
6199 /* register hash and get it's idx .... */
6200
6201 /* get users password and make up a salt ... */
6202
6203 /* create the material (100 iterations in algorithm) */
6204 outlen = sizeof(outbuf);
6205 if ((err = pkcs_5_alg2(password, password_len, salt,
6206 salt_len, 100, hash_idx, outbuf,
6207 &outlen))
6208 != CRYPT_OK) {
6209 /* error handle */
6210 }
6211
6212 /* now extract it */
6213 memcpy(cipher_key, outbuf, 16);
6214 memcpy(cipher_iv, outbuf+16, 16);
6215 memcpy(mac_key, outbuf+32, 16);
6216
6217 /* use material (recall to store the salt in the output) */
6218 }
6219 \end{verbatim}
6220
6221 \mysection{Key Derviation Functions}
6222 \subsection{HKDF}
6223 \index{HKDF}
6224 A key derivation function (KDF) is a basic and essential component of cryptographic systems. Its goal is to take some source of initial
6225 keying material and derive from it one or more cryptographically strong secret keys.
6226
6227 HKDF follows the "extract-then-expand" paradigm, where the KDF logically consists of two modules. The first stage takes the input
6228 keying material and "extracts" from it a fixed-length pseudorandom key K. The second stage "expands" the key K into several additional
6229 pseudorandom keys (the output of the KDF).
6230
6231 In many applications, the input keying material is not necessarily distributed uniformly, and the attacker may have some partial
6232 knowledge about it (for example, a Diffie-Hellman value computed by a key exchange protocol) or even partial control of it (as in some
6233 entropy-gathering applications). Thus, the goal of the "extract" stage is to "concentrate" the possibly dispersed entropy of the input
6234 keying material into a short, but cryptographically strong, pseudorandom key. In some applications, the input may already be a
6235 good pseudorandom key; in these cases, the "extract" stage is not necessary, and the "expand" part can be used alone.
6236
6237 The second stage "expands" the pseudorandom key to the desired length; the number and lengths of the output keys depend on the
6238 specific cryptographic algorithms for which the keys are needed.
6239
6240 \subsection{HKDF Extract}
6241 To perform the extraction phase, use the following function:
6242
6243 \index{hkdf\_extract()}
6244 \begin{alltt}
6245 int hkdf_extract( int hash_idx,
6246 const unsigned char *salt,
6247 unsigned long saltlen,
6248 const unsigned char *in,
6249 unsigned long inlen,
6250 unsigned char *out,
6251 unsigned long *outlen);
6252 \end{alltt}
6253 The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
6254 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).
6255 \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}.
6256 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.
6257
6258 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.
6259
6260 \subsection{HKDF Expand}
6261 To perform the expansion phase, use the following function:
6262
6263 \index{hkdf\_expand()}
6264 \begin{alltt}
6265 int hkdf_expand( int hash_idx,
6266 const unsigned char *info,
6267 unsigned long infolen,
6268 const unsigned char *in,
6269 unsigned long inlen,
6270 unsigned char *out,
6271 unsigned long outlen);
6272 \end{alltt}
6273
6274 The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
6275 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
6276 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.
6277 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}.
6278
6279 \subsection{HKDF Extract-and-Expand}
6280 To perform both phases together, use the following function:
6281
6282 \index{hkdf()}
6283 \begin{alltt}
6284 int hkdf( int hash_idx,
6285 const unsigned char *salt,
6286 unsigned long saltlen,
6287 const unsigned char *info,
6288 unsigned long infolen,
6289 const unsigned char *in,
6290 unsigned long inlen,
6291 unsigned char *out,
6292 unsigned long outlen);
6293 \end{alltt}
6294
6295 Parameters are as in \textit{hkdf\_extract()} and \textit{hkdf\_expand()}.
6296
6297 \chapter{Miscellaneous}
6298 \mysection{Base64 Encoding and Decoding}
6299 The library provides functions to encode and decode a RFC 4648 Base64 coding scheme.
6300
6301 \subsection{Standard 'base64' encoding}
6302 The characters used in the mappings are:
6303 \begin{verbatim}
6304 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
6305 \end{verbatim}
6306 Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
6307 common e-mail, usenet and HTTP mediums. The format of an encoded stream is just a literal sequence of ASCII characters
6308 where a group of four represent 24-bits of input. The first four chars of the encoders output is the length of the
6309 original input. After the first four characters is the rest of the message.
6310
6311 Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting. The decoder allows you to
6312 put any character (that is not in the above sequence) in between any character of the encoders output. You may not however,
6313 break up the first four characters.
6314
6315 To encode a binary string in base64 call:
6316 \index{base64\_encode()}
6317 \begin{verbatim}
6318 int base64_encode(const unsigned char *in,
6319 unsigned long len,
6320 unsigned char *out,
6321 unsigned long *outlen);
6322 \end{verbatim}
6323 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
6324 to calling this function and it sets the length of the base64 output in \textit{outlen} when it is done. To decode a base64
6325 string call:
6326 \index{base64\_decode()}
6327 \begin{verbatim}
6328 int base64_decode(const unsigned char *in,
6329 unsigned long len,
6330 unsigned char *out,
6331 unsigned long *outlen);
6332 \end{verbatim}
6333
6334 The function \textit{base64\_decode} works in a relaxed way which allows decoding some inputs that do not strictly follow the standard.
6335 If you want to be strict during decoding you can use:
6336 \index{base64\_strict\_decode()}
6337 \begin{verbatim}
6338 int base64_strict_decode(const unsigned char *in,
6339 unsigned long len,
6340 unsigned char *out,
6341 unsigned long *outlen);
6342 \end{verbatim}
6343
6344 \subsection{URL--safe 'base64url' encoding}
6345 The characters used in the mappings are:
6346 \begin{verbatim}
6347 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
6348 \end{verbatim}
6349 Those characters are sometimes also called URL and filename safe alphabet.
6350 The interface is analogous to \textit{base64\_xxxx} functions in previous chapter.
6351
6352 \begin{verbatim}
6353 int base64url_encode(const unsigned char *in, unsigned long len,
6354 unsigned char *out, unsigned long *outlen);
6355
6356 int base64url_strict_encode(const unsigned char *in, unsigned long inlen,
6357 unsigned char *out, unsigned long *outlen);
6358
6359 int base64url_decode(const unsigned char *in, unsigned long len,
6360 unsigned char *out, unsigned long *outlen);
6361
6362 int base64url_strict_decode(const unsigned char *in, unsigned long len,
6363 unsigned char *out, unsigned long *outlen);
6364 \end{verbatim}
6365
6366 \mysection{Primality Testing}
6367 \index{Primality Testing}
6368 The library includes primality testing and random prime functions as well. The primality tester will perform the test in
6369 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
6370 Rabin-Miller primality testing algorithm. If the candidate passes both phases it is declared prime otherwise it is declared
6371 composite. No prime number will fail the two phases but composites can. Each round of the Rabin-Miller algorithm reduces
6372 the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
6373 $\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$. In practice the probability of error is in fact much lower than that.
6374
6375 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}.
6376 In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes. When the candidate
6377 is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
6378 math operations. As a result the routine can scan ahead to the next number required for testing with very little work
6379 involved.
6380
6381 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
6382 instance, in RSA two primes $p$ and $q$ are required. The order of the multiplicative sub-group (modulo $pq$) is given
6383 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
6384 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
6385 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
6386 not equal to $(p - 1)(rs - 1)$.
6387
6388 These are not technically part of the LibTomMath library but this is the best place to document them.
6389 To test if a \textit{mp\_int} is prime call:
6390 \begin{verbatim}
6391 int is_prime(mp_int *N, int *result);
6392 \end{verbatim}
6393 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
6394 it returns an error that the value in \textit{result} is undefined. To make
6395 a random prime call:
6396 \begin{verbatim}
6397 int rand_prime( mp_int *N,
6398 unsigned long len,
6399 prng_state *prng,
6400 int wprng);
6401 \end{verbatim}
6402 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
6403 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
6404 \textit{len = -128} to the function. Upon success it will return {\bf CRYPT\_OK} and \textit{N} will contain an integer which
6405 is very likely prime.
6406
6407 \mysection{Random MPI Generation}
6408 \index{Random MPI Generation}
6409
6410 Several Public Key Cryptography algorithms require random MPI's for operations like signature generation.
6411 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.
6412
6413 \index{rand\_bn\_bits()}
6414 \begin{verbatim}
6415 int rand_bn_bits( void *N,
6416 int bits,
6417 prng_state *prng,
6418 int wprng);
6419 \end{verbatim}
6420
6421 This sets \textit{N} to a \textit{bits}-long random MPI.
6422
6423 \index{rand\_bn\_upto()}
6424 \begin{verbatim}
6425 int rand_bn_upto( void *N,
6426 void *limit,
6427 prng_state *prng,
6428 int wprng);
6429 \end{verbatim}
6430
6431 This ensures that \textit{N} is set to a random MPI in the range $1 \le N < limit$.
6432
6433
6434 \mysection{Helper functions}
6435
6436 \subsection{Zero'ing data}
6437
6438 As widely know optimizing-compilers are sometimes allowed to remove an invocation of \textit{memset(out, 0, outlen)}, which could result
6439 in sensitive data beeing not zero'ed out. Therefore LibTomCrypt implements a variant of this routine which won't be optimized-away.
6440
6441 \index{zeromem()}
6442 \begin{verbatim}
6443 void zeromem(volatile void *out, size_t outlen);
6444 \end{verbatim}
6445
6446 This zero's the buffer \textit{out} of size \textit{outlen}.
6447
6448 \subsection{Constant-time memory compare}
6449
6450 Some symmetric-key cryptographic operation-modes are vulnerable to timing attacks in case non-contant-time memory comparison functions
6451 are used to compare results. Therefore LibTomCrypt implements a constant-time memory compare function.
6452
6453 \index{mem\_neq()}
6454 \begin{verbatim}
6455 int mem_neq(const void *a, const void *b, size_t len);
6456 \end{verbatim}
6457
6458 This will compare the buffer \textit{a} against the buffer \textit{b} for \textit{len} bytes.
6459 The return value is either \textit{0} when the content of \textit{a} and \textit{b} is equal or \textit{1} when it differs.
6460
6461 \subsection{Radix to binary conversion}
6462
6463 All public-key cryptographic algorithms provide a way to import and/or export their key parameters in binary format.
6464 In order to be able to import keys stored in different formats, e.g. hexadecimal strings, the \textit{radix\_to\_bin()} function is provided.
6465
6466 \index{radix\_to\_bin()}
6467 \begin{verbatim}
6468 int radix_to_bin(const void *in, int radix, void *out, unsigned long *len);
6469 \end{verbatim}
6470
6471 This will convert the MPI \textit{in} of radix \textit{radix} to the buffer pointed to by \textit{out}.
6472 The field \textit{len} is a pointer to the length of the buffer on input and the length stored on output.
6473
6474 In case you don't know the length of the buffer you can use \textit{radix\_to\_bin()} to determine the length for you.
6475
6476 \begin{verbatim}
6477 #include <tomcrypt.h>
6478
6479 int main(void)
6480 {
6481 const char *mpi = "AABBCCDD";
6482 unsigned long l = 0;
6483 void* buf;
6484 int ret;
6485 ltc_mp = ltm_desc;
6486
6487 if (radix_to_bin(mpi, 16, NULL, &l) != CRYPT_BUFFER_OVERFLOW)
6488 return EXIT_FAILURE;
6489 buf = malloc(l);
6490
6491 ret = EXIT_SUCCESS;
6492 if (radix_to_bin(mpi, 16, buf, &l) != CRYPT_OK)
6493 ret = EXIT_FAILURE;
6494
6495 free(buf);
6496 return ret;
6497 }
6498 \end{verbatim}
6499
6500
6501 \mysection{Dynamic Language Support}
6502 \index{Dynamic Language Support}
6503 Various LibTomCrypt functions require that their callers define a struct
6504 (or a union) and provide a pointer to it, or allocate sufficient memory and
6505 provide its pointer. Programs written in C or C++ can obtain the necessary
6506 information by simply including the appropriate header files, but dynamic
6507 languages like Python don't understand C header files, and without assistance,
6508 have no way to know how much memory to allocate. A similar story can be told
6509 for certain LTC constant values.
6510
6511 LTC's Dynamic Language Support provides functions that return the size of
6512 a named struct or union, the value of a named constant, a list of all sizes
6513 supported, and a list of all named constants supported. Two additional
6514 functions can initialize LTM and TFM.
6515
6516 To get the size of a named struct or union:
6517 \begin{verbatim}
6518 int crypt_get_size( const char *namein,
6519 unsigned int *sizeout);
6520 \end{verbatim}
6521 $namein$ is spelled exactly as found in the C header files. This function will
6522 return -1 if $namein$ is not found.
6523
6524 To get the value of a named constant:
6525 \begin{verbatim}
6526 int crypt_get_constant(const char *namein,
6527 int *valueout);
6528 \end{verbatim}
6529 $namein$ is spelled exactly as found in the C header files. Again, -1 is
6530 returned if $namein$ is not found.
6531
6532 To get the names of all the supported structs, unions and constants:
6533 \begin{verbatim}
6534 int crypt_list_all_sizes( char *names_list,
6535 unsigned int *names_list_size);
6536
6537 int crypt_list_all_constants( char *names_list,
6538 unsigned int *names_list_size);
6539 \end{verbatim}
6540 You may want to call these functions twice, first to get the amount
6541 of memory to be allocated for the $names_list$, and a final time to
6542 actually populate $names_list$. If $names_list$ is NULL,
6543 $names_list_size$ will be the minimum size needed to receive the
6544 complete $names_list$. If $names_list$ is NOT NULL, $names_list$ must
6545 be a pointer to sufficient memory into which the $names_list$ will be
6546 written. Also, the value in $names_list_size$ sets the upper bound of
6547 the number of characters to be written. A -1 return value signifies
6548 insufficient space.
6549
6550 The format of the $names_list$ string is a series of $name,value$ pairs
6551 where each name and value is separated by a comma, the pairs are separated
6552 by newlines, and the list is null terminated.
6553
6554 Calling either of these functions will initialize the respective
6555 math library.
6556 \begin{verbatim}
6557 void init_LTM(void);
6558 void init_TFM(void);
6559 void init_GMP(void);
6560 \end{verbatim}
6561
6562 Here is a Python program demonstrating how to call various LTC dynamic
6563 language support functions.
6564 \begin{verbatim}
6565 from ctypes import *
6566
6567 # load the OSX shared/dynamic library
6568 LIB = CDLL('libtomcrypt.dylib')
6569
6570 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6571 # print info about this library
6572
6573 little = c_int() # assume False is big
6574 word32 = c_int() # assume False is 64-bit
6575
6576 LIB.crypt_get_constant('ENDIAN_LITTLE', byref(little))
6577 LIB.crypt_get_constant('ENDIAN_32BITWORD', byref(word32))
6578
6579 print('this lib was compiled for a %s endian %d-bit processor'
6580 % ('little' if little else 'big', 32 if word32 else 64))
6581
6582 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6583 # print the size of the struct named "sha256_state"
6584
6585 struct_size = c_int()
6586
6587 # don't forget to add the '_struct' or '_union' suffix
6588 LIB.crypt_get_size('sha256_state_struct', byref(struct_size))
6589
6590 print('allocate %d bytes for sha256_state' % struct_size.value)
6591
6592 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6593 # print a list of all supported named constants
6594
6595 list_size = c_int()
6596
6597 # call with NULL to calc the min size needed for the list
6598 LIB.crypt_list_all_constants(None, byref(list_size))
6599
6600 # allocate required space
6601 names_list = c_buffer(list_size.value)
6602
6603 # call again providing a pointer to where to write the list
6604 LIB.crypt_list_all_constants(names_list, byref(list_size))
6605
6606 print(names_list.value)
6607
6608 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6609 # print a list of all supported named structs and unions
6610
6611 list_size = c_int()
6612
6613 # call with NULL to calc the min size needed for the list
6614 LIB.crypt_list_all_sizes(None, byref(list_size))
6615
6616 # allocate required space
6617 names_list = c_buffer(list_size.value)
6618
6619 # call again providing a pointer to where to write the list
6620 LIB.crypt_list_all_sizes(names_list, byref(list_size))
6621
6622 print(names_list.value)
6623 \end{verbatim}
6624
6625
6626 \chapter{Programming Guidelines}
6627
6628 \mysection{Secure Pseudo Random Number Generators}
6629 Probably the single most vulnerable point of any cryptosystem is the PRNG. Without one, generating and protecting secrets
6630 would be impossible. The requirement that one be setup correctly is vitally important, and to address this point the library
6631 does provide two RNG sources that will address the largest amount of end users as possible. The \textit{sprng} PRNG provides an easy to
6632 access source of entropy for any application on a UNIX (and the like) or Windows computer.
6633
6634 However, when the end user is not on one of these platforms, the application developer must address the issue of finding
6635 entropy. This manual is not designed to be a text on cryptography. I would just like to highlight that when you design
6636 a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.
6637
6638 \mysection{Preventing Trivial Errors}
6639 Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values. All of the functions
6640 which output variable length strings will require you to pass the length of the destination. If the size of your output
6641 buffer is smaller than the output it will report an error. Therefore, make sure the size you pass is correct!
6642
6643 Also, virtually all of the functions return an error code or {\bf CRYPT\_OK}. You should detect all errors, as simple
6644 typos can cause algorithms to fail to work as desired.
6645
6646 \mysection{Registering Your Algorithms}
6647 To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
6648 before you try to use them. This includes any function which would use an algorithm indirectly through a descriptor table.
6649
6650 A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
6651 having to hack the library. For example, suppose you have a hardware specific PRNG on your system. You could easily
6652 write the few functions required plus a descriptor. After registering your PRNG, all of the library functions that
6653 need a PRNG can instantly take advantage of it. The same applies for ciphers, hashes, and bignum math routines.
6654
6655 \mysection{Key Sizes}
6656
6657 \subsection{Symmetric Ciphers}
6658 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
6659 is not a hard thing to do. As a good rule of thumb do not use a key smaller than 128 bits.
6660
6661 \subsection{Asymmetric Ciphers}
6662 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
6663 $n$ is estimated to be
6664 \begin{equation}
6665 e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
6666 \end{equation}
6667
6668 Note that $n$ is not the bit-length but the magnitude. For example, for a 1024-bit key $n = 2^{1024}$. The work required
6669 is:
6670 \begin{figure}[H]
6671 \begin{center}
6672 \begin{tabular}{|c|c|}
6673 \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
6674 \hline 512 & 63.92 \\
6675 \hline 768 & 76.50 \\
6676 \hline 1024 & 86.76 \\
6677 \hline 1536 & 103.37 \\
6678 \hline 2048 & 116.88 \\
6679 \hline 2560 & 128.47 \\
6680 \hline 3072 & 138.73 \\
6681 \hline 4096 & 156.49 \\
6682 \hline
6683 \end{tabular}
6684 \end{center}
6685 \caption{RSA/DH Key Strength}
6686 \end{figure}
6687
6688 The work factor for ECC keys is much higher since the best attack is still fully exponential. Given a key of magnitude
6689 $n$ it requires $\sqrt n$ work. The following table summarizes the work required:
6690 \begin{figure}[H]
6691 \begin{center}
6692 \begin{tabular}{|c|c|}
6693 \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
6694 \hline 112 & 56 \\
6695 \hline 128 & 64 \\
6696 \hline 160 & 80 \\
6697 \hline 192 & 96 \\
6698 \hline 224 & 112 \\
6699 \hline 256 & 128 \\
6700 \hline 384 & 192 \\
6701 \hline 521 & 260.5 \\
6702 \hline
6703 \end{tabular}
6704 \end{center}
6705 \caption{ECC Key Strength}
6706 \end{figure}
6707
6708 Using the above tables the following suggestions for key sizes seems appropriate:
6709 \begin{center}
6710 \begin{tabular}{|c|c|c|}
6711 \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
6712 \hline Near term & 1024 & 160 \\
6713 \hline Short term & 1536 & 192 \\
6714 \hline Long Term & 2560 & 384 \\
6715 \hline
6716 \end{tabular}
6717 \end{center}
6718
6719 \mysection{Thread Safety}
6720 The library is not fully thread safe but several simple precautions can be taken to avoid any problems. The registry functions
6721 such as register\_cipher() are not thread safe no matter what you do. It is best to call them from your programs initialization
6722 code before threads are initiated.
6723
6724 The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc. This means that if each
6725 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
6726 and hashes.
6727
6728 \index{LTC\_PTHREAD}
6729 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
6730 pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.
6731
6732 \chapter{Configuring and Building the Library}
6733 \mysection{Introduction}
6734 The library is fairly flexible about how it can be built, used, and generally distributed. Additions are being made with
6735 each new release that will make the library even more flexible. Each of the classes of functions can be disabled during
6736 the build process to make a smaller library. This is particularly useful for shared libraries.
6737
6738 As of v1.06 of the library, the build process has been moved to two steps for the typical LibTomCrypt application. This is because
6739 LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath, GnuMP, or TomsFastMath).
6740
6741 The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
6742 configured. Note that LibTomCrypt can be built with no internal math descriptors. This means that one must be provided at either
6743 build, or run time for the application. LibTomCrypt comes with three math descriptors that provide a standard interface to math
6744 libraries.
6745
6746 \mysection{Makefile variables}
6747
6748 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
6749 settings can be overwritten from the command line which makes custom installation a breeze.
6750
6751 \subsection{MAKE, CC, AR and CROSS\_COMPILE}
6752 \index{MAKE} \index{CC} \index{AR} \index{CROSS\_COMPILE}
6753 The MAKE, CC and AR flags can all be overwritten. They default to \textit{make}, \textit{\$CC} and \textit{\$AR} respectively.
6754 Changing MAKE allows you to change what program will be invoked to handle sub--directories. For example, this
6755
6756 \begin{verbatim}
6757 gmake install MAKE=gmake
6758 \end{verbatim}
6759
6760 \begin{flushleft} will build and install the libraries with the \textit{gmake} tool. Similarly, \end{flushleft}
6761
6762 \begin{verbatim}
6763 make CC=arm-gcc AR=arm-ar
6764 \end{verbatim}
6765
6766 \begin{flushleft} will build the library using \textit{arm--gcc} as the compiler and \textit{arm--ar} as the archiver. \end{flushleft}
6767
6768 \begin{verbatim}
6769 make CROSS_COMPILE=arm-none-eabi-
6770 \end{verbatim}
6771
6772 \begin{flushleft} will build the library using the \textit{arm--none--eabi--} prefix'ed toolchain. \end{flushleft}
6773
6774 \subsection{IGNORE\_SPEED and LTC\_DEBUG}
6775 \index{IGNORE\_SPEED} \index{LTC\_DEBUG}
6776 When \textbf{IGNORE\_SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
6777 CFLAGS on the command line. E.g. to add debugging
6778
6779 \begin{verbatim}
6780 make IGNORE_SPEED=1 CFLAGS="-g3"
6781 \end{verbatim}
6782
6783 This will turn off optimizations and add \textit{-g3} to the CFLAGS which enables debugging.
6784
6785 Alternatively one can define \textbf{LTC\_DEBUG} instead, which additionally defines \textit{LTC\_NO\_ASM} and enables debug output on test failures.
6786
6787 Defining \textit{LTC\_DEBUG=2} has the effect to enable verbose output in some of the tests.
6788
6789 \begin{verbatim}
6790 make LTC_DEBUG=2
6791 \end{verbatim}
6792
6793 \begin{flushleft} will build the library without compiler-optimisation or architecture specific code and will enable debugging
6794 and verbose debug output. \end{flushleft}
6795
6796 \subsection{LIBNAME}
6797 \index{LIBNAME}
6798 \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
6799 shared.
6800 On installation of the shared library the appropriately versioned \textit{libtomcrypt.so}, \textit{libtomcrypt.so.0} etc. will be created by \textit{libtool}.
6801
6802 \subsection{Installation Directories}
6803 \index{DESTDIR} \index{PREFIX} \index{LIBPATH} \index{INCPATH} \index{DATAPATH} \index{BINPATH}
6804 \textbf{DESTDIR} is the location where the output will be stored. It default to an empty string.
6805 \textbf{PREFIX} is the prefix for the installation directories. It defaults to \textit{/usr/local}.
6806 \textbf{LIBPATH} is the location of the library directory which defaults to \textit{\$PREFIX/lib}.
6807 \textbf{INCPATH} is the location of the header file directory which defaults to \textit{\$PREFIX/include}.
6808 \textbf{DATAPATH} is the location of the data (documentation) directory which defaults to \textit{\$PREFIX/share/doc/libtomcrypt/pdf}.
6809 \textbf{BINPATH} is the location of the binary file directory which defaults to \textit{\$PREFIX/bin}.
6810
6811 They allow to configure the installation locations of the libary.
6812
6813 \begin{verbatim}
6814 make PREFIX=/home/tom/project DATAPATH=/home/tom/project/docs install
6815 \end{verbatim}
6816
6817 This will build the library and install it to the directories under \textit{/home/tom/project/}. e.g.
6818
6819 \begin{small}
6820 \begin{verbatim}
6821 /home/tom/project/:
6822 total 1
6823 drwxr-xr-x 2 tom users 80 Jul 30 16:02 docs
6824 drwxr-xr-x 2 tom users 528 Jul 30 16:02 include
6825 drwxr-xr-x 2 tom users 80 Jul 30 16:02 lib
6826
6827 /home/tom/project/docs:
6828 total 452
6829 -rwxr-xr-x 1 tom users 459009 Jul 30 16:02 crypt.pdf
6830
6831 /home/tom/project/include:
6832 total 132
6833 -rwxr-xr-x 1 tom users 2482 Jul 30 16:02 tomcrypt.h
6834 -rwxr-xr-x 1 tom users 702 Jul 30 16:02 tomcrypt_argchk.h
6835 -rwxr-xr-x 1 tom users 2945 Jul 30 16:02 tomcrypt_cfg.h
6836 -rwxr-xr-x 1 tom users 22763 Jul 30 16:02 tomcrypt_cipher.h
6837 -rwxr-xr-x 1 tom users 5174 Jul 30 16:02 tomcrypt_custom.h
6838 -rwxr-xr-x 1 tom users 11314 Jul 30 16:02 tomcrypt_hash.h
6839 -rwxr-xr-x 1 tom users 11571 Jul 30 16:02 tomcrypt_mac.h
6840 -rwxr-xr-x 1 tom users 13614 Jul 30 16:02 tomcrypt_macros.h
6841 -rwxr-xr-x 1 tom users 14714 Jul 30 16:02 tomcrypt_math.h
6842 -rwxr-xr-x 1 tom users 632 Jul 30 16:02 tomcrypt_misc.h
6843 -rwxr-xr-x 1 tom users 10934 Jul 30 16:02 tomcrypt_pk.h
6844 -rwxr-xr-x 1 tom users 2634 Jul 30 16:02 tomcrypt_pkcs.h
6845 -rwxr-xr-x 1 tom users 7067 Jul 30 16:02 tomcrypt_prng.h
6846 -rwxr-xr-x 1 tom users 1467 Jul 30 16:02 tomcrypt_test.h
6847
6848 /home/tom/project/lib:
6849 total 1073
6850 -rwxr-xr-x 1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
6851 \end{verbatim}
6852 \end{small}
6853
6854 For further information see: \url{https://www.gnu.org/prep/standards/html_node/DESTDIR.html}
6855 and \url{https://www.freebsd.org/doc/en/books/porters-handbook/porting-prefix.html}.
6856
6857 \mysection{Extra libraries}
6858 \index{EXTRALIBS}
6859 \textbf{EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries. They are specified in the notation
6860 that GCC expects for global archives.
6861
6862 \begin{verbatim}
6863 make install test timing CFLAGS="-DTFM_DESC -DUSE_TFM" EXTRALIBS=-ltfm
6864 \end{verbatim}
6865
6866 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
6867 defines are explained below. You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
6868 the \textbf{EXTRALIBS} variable by separating them by a space.
6869
6870 Note that \textbf{EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.
6871
6872 \mysection{Building a Static Library}
6873
6874 Building a static library is fairly trivial as it only requires one invocation of the GNU make command.
6875
6876 \begin{verbatim}
6877 make install CFLAGS="-DTFM_DESC"
6878 \end{verbatim}
6879
6880 That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously. You can enable
6881 the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor). Similarly, you can build the library with no built--in
6882 math descriptors.
6883
6884 \begin{verbatim}
6885 make install
6886 \end{verbatim}
6887
6888 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
6889 public key functions.
6890
6891 Note that even if you include the built--in descriptors you must link against the source library as well.
6892
6893 \begin{verbatim}
6894 gcc -DTFM_DESC myprogram.c -ltomcrypt -ltfm -o myprogram
6895 \end{verbatim}
6896
6897 This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed). Note that
6898 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
6899 giving warnings.
6900
6901 \mysection{Building a Shared Library}
6902
6903 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
6904 that you \textbf{must} specify the \textbf{EXTRALIBS} variable at install time.
6905
6906 \begin{verbatim}
6907 make -f makefile.shared install CFLAGS="-DTFM_DESC" EXTRALIBS=-ltfm
6908 \end{verbatim}
6909
6910 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
6911 shared build process requires libtool to be installed.
6912
6913 \mysection{Header Configuration}
6914 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
6915 stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.
6916
6917 \subsubsection{ARGTYPE}
6918 This lets you control how the LTC\_ARGCHK macro will behave. The macro is used to check pointers inside the functions against
6919 NULL. There are four settings for ARGTYPE. When set to 0, it will have the default behaviour of printing a message to
6920 stderr and raising a SIGABRT signal. This is provided so all platforms that use LibTomCrypt can have an error that functions
6921 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
6922 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
6923 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
6924 to 4, it will return CRYPT\_INVALID\_ARG to the caller.
6925
6926 \subsubsection{Endianness}
6927 There are five macros related to endianness issues. For little endian platforms define, \textbf{ENDIAN\_LITTLE}. For big endian
6928 platforms define \textbf{ENDIAN\_BIG}. Similarly when the default word size of an \textit{unsigned long} is 32-bits define \textbf{ENDIAN\_32BITWORD}
6929 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}
6930 which will work on all platforms.
6931
6932 Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.
6933
6934 \mysection{Customisation}
6935 There are also options you can specify from the \textit{tomcrypt\_custom.h} header file.
6936
6937 \subsection{X memory routines}
6938 \index{XMALLOC}\index{XREALLOC}\index{XCALLOC}\index{XFREE}\index{XMEMSET}\index{XMEMCPY}\index{XMEMMOVE}\index{XMEMCMP}\index{XSTRCMP}
6939 At the top of tomcrypt\_custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on. They resolve to
6940 the name of the respective functions from the standard C library by default. This lets you substitute in your own memory routines.
6941 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
6942 output.
6943
6944 These macros are handy for working with platforms which do not have a standard C library.
6945 For instance, the OLPC\footnote{See \url{http://dev.laptop.org/git?p=bios-crypto;a=summary}}
6946 bios code uses these macros to redirect to very compact heap and string operations.
6947
6948 \subsection{X clock routines}
6949 The rng\_get\_bytes() function can call a function that requires the clock() function. These macros let you override
6950 the default clock() used with a replacement. By default the standard C library clock() function is used.
6951
6952 \subsection{LTC\_NO\_FILE}
6953 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
6954 functions and instead simply return CRYPT\_NOP. This should help resolve any linker errors stemming from a lack of
6955 file I/O on embedded platforms.
6956
6957 \subsection{LTC\_CLEAN\_STACK}
6958 When this functions is defined the functions that store key material on the stack will clean up afterwards.
6959 Assumes that you have no memory paging with the stack.
6960
6961 \subsection{LTC\_TEST}
6962 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.
6963 If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.
6964
6965 \subsection{LTC\_NO\_FAST}
6966 When this has been defined the library will not use faster word oriented operations. By default, they are only enabled for platforms
6967 which can be auto-detected. This macro ensures that they are never enabled.
6968
6969 \subsection{LTC\_FAST}
6970 This mode (auto-detected with x86\_32, x86\_64 platforms with GCC or CLANG) configures various routines such as ctr\_encrypt() or
6971 cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type. This has the benefit of
6972 cutting down the overhead of the respective functions.
6973
6974 This mode does have one downside. It can cause unaligned reads from memory if you are not careful with the functions. This is why
6975 it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed. Technically LTC\_FAST
6976 is not \textit{portable} since unaligned accesses are not covered by the ISO C specifications.
6977
6978 In practice however, you can use it on pretty much any platform (even MIPS) with care.
6979
6980 By design the \textit{fast} mode functions won't get unaligned on their own. For instance, if you call ctr\_encrypt() right after calling
6981 ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only. However, if you
6982 call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used. This will
6983 cause the ctr routine to first use up the remaining pad bytes. Then if there are enough plaintext bytes left it will use
6984 whole word XOR operations. These operations will be unaligned.
6985
6986 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
6987 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.
6988
6989 \index{LTC\_FAST\_TYPE}
6990 If you do plan on using the \textit{LTC\_FAST} mode, a \textit{LTC\_FAST\_TYPE} type which resolves to an optimal sized
6991 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
6992 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
6993 use this mode. So sad.
6994
6995 \subsection{LTC\_NO\_ASM}
6996 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
6997 cannot handle all of the assembler functions.
6998
6999 \subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
7000 There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
7001 self-explanatory. When they are defined the functionality is included otherwise it is not. There are some
7002 dependency issues which are noted in the file. For instance, Yarrow requires CTR chaining mode, a block
7003 cipher and a hash function.
7004
7005 Also see technical note number five for more details.
7006
7007 \subsection{LTC\_EASY}
7008 When defined the library is configured to build fewer algorithms and modes. Mostly it sticks to NIST and ANSI approved algorithms. See
7009 the header file \textit{tomcrypt\_custom.h} for more details. It is meant to provide literally an easy method of trimming the library
7010 build to the most minimum of useful functionality.
7011
7012 \subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
7013 Twofish is a 128-bit symmetric block cipher that is provided within the library. The cipher itself is flexible enough
7014 to allow some trade-offs in the implementation. When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
7015 requires only 200 bytes of memory. This is achieved by not pre-computing the substitution boxes. Having this
7016 defined will also greatly slow down the cipher. When this macro is not defined Twofish will pre-compute the
7017 tables at a cost of 4KB of memory. The cipher will be much faster as a result.
7018
7019 When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work. This is
7020 useful when TWOFISH\_SMALL is defined as the table values are computed on the fly. When this is defined the code size
7021 will increase by approximately 500 bytes. If this is defined but TWOFISH\_SMALL is not the cipher will still work but
7022 it will not speed up the encryption or decryption functions.
7023
7024 \subsection{GCM\_TABLES}
7025 When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
7026 It also increases the initialization time and is not suitable when you are going to use a key a few times only.
7027
7028 \subsection{GCM\_TABLES\_SSE2}
7029 \index{SSE2}
7030 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
7031 of GCM output on both the AMD64 and Intel Pentium 4 platforms. Requires GCC and an SSE2 equipped platform.
7032
7033 \subsection{LTC\_SMALL\_CODE}
7034 When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
7035 These variants are slower but can save quite a bit of code space.
7036
7037 \subsection{LTC\_PTHREAD}
7038 When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables. Note that
7039 it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.
7040
7041 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
7042 the tables safer.
7043
7044 \subsection{LTC\_ECC\_TIMING\_RESISTANT}
7045 When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
7046 algorithm which prevents leaking key bits of the private key (scalar). It is a slower algorithm but useful for situations
7047 where timing side channels pose a significant threat.
7048
7049 This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_ECC\_TIMING\_RESISTANT}.
7050
7051 \subsection{LTC\_RSA\_BLINDING}
7052 When this has been defined the RSA modular exponentiation will use a blinding algorithm to improve timing resistance.
7053
7054 This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_BLINDING}.
7055
7056 \subsection{LTC\_RSA\_CRT\_HARDENING}
7057 When this has been defined the RSA modular exponentiation will do some sanity checks regarding the CRT parameters and the operations' results.
7058
7059 This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_CRT\_HARDENING}.
7060
7061 \subsection{Math Descriptors}
7062 The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
7063 libraries. When \textbf{GMP\_DESC}, \textbf{LTM\_DESC}, or \textbf{TFM\_DESC} are defined
7064 descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.
7065
7066 In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
7067 to tell the program which library to use. Only one of the USE flags can be defined at once.
7068
7069 \index{GMP\_DESC} \index{USE\_GMP} \index{LTM\_DESC} \index{TFM\_DESC} \index{USE\_LTM} \index{USE\_TFM}
7070 \begin{small}
7071 \begin{verbatim}
7072 make -f makefile.shared install timing CFLAGS="-DGMP_DESC -DLTM_DESC -DTFM_DESC -DUSE_TFM" \
7073 EXTRALIBS="-lgmp -ltommath -ltfm"
7074 \end{verbatim}
7075 \end{small}
7076
7077 That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.
7078
7079 \chapter{Optimizations}
7080 \mysection{Introduction}
7081 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
7082 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
7083 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
7084 about the platform, etc...
7085
7086 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
7087 portable routines. For instance, hand optimized assembler versions of AES could be provided. Any existing function that uses the cipher could automatically use
7088 the optimized code without re--writing. This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.
7089
7090 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
7091 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
7092 development simple. In most dependent routines all an end developer has to do is register\_XXX() the descriptor and they are set.
7093
7094 \mysection{Ciphers}
7095 The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.
7096
7097 \label{sec:cipherdesc}
7098 \begin{small}
7099 \begin{verbatim}
7100 struct ltc_cipher_descriptor {
7101 /** name of cipher */
7102 char *name;
7103
7104 /** internal ID */
7105 unsigned char ID;
7106
7107 /** min keysize (octets) */
7108 int min_key_length,
7109
7110 /** max keysize (octets) */
7111 max_key_length,
7112
7113 /** block size (octets) */
7114 block_length,
7115
7116 /** default number of rounds */
7117 default_rounds;
7118
7119 /** Setup the cipher
7120 @param key The input symmetric key
7121 @param keylen The length of the input key (octets)
7122 @param num_rounds The requested number of rounds (0==default)
7123 @param skey [out] The destination of the scheduled key
7124 @return CRYPT_OK if successful
7125 */
7126 int (*setup)(const unsigned char *key,
7127 int keylen,
7128 int num_rounds,
7129 symmetric_key *skey);
7130
7131 /** Encrypt a block
7132 @param pt The plaintext
7133 @param ct [out] The ciphertext
7134 @param skey The scheduled key
7135 @return CRYPT_OK if successful
7136 */
7137 int (*ecb_encrypt)(const unsigned char *pt,
7138 unsigned char *ct,
7139 symmetric_key *skey);
7140
7141 /** Decrypt a block
7142 @param ct The ciphertext
7143 @param pt [out] The plaintext
7144 @param skey The scheduled key
7145 @return CRYPT_OK if successful
7146 */
7147 int (*ecb_decrypt)(const unsigned char *ct,
7148 unsigned char *pt,
7149 symmetric_key *skey);
7150
7151 /** Test the block cipher
7152 @return CRYPT_OK if successful,
7153 CRYPT_NOP if self-testing has been disabled
7154 */
7155 int (*test)(void);
7156
7157 /** Terminate the context
7158 @param skey The scheduled key
7159 */
7160 void (*done)(symmetric_key *skey);
7161
7162 /** Determine a key size
7163 @param keysize [in/out] The size of the key desired
7164 The suggested size
7165 @return CRYPT_OK if successful
7166 */
7167 int (*keysize)(int *keysize);
7168
7169 /** Accelerators **/
7170 /** Accelerated ECB encryption
7171 @param pt Plaintext
7172 @param ct Ciphertext
7173 @param blocks The number of complete blocks to process
7174 @param skey The scheduled key context
7175 @return CRYPT_OK if successful
7176 */
7177 int (*accel_ecb_encrypt)(const unsigned char *pt,
7178 unsigned char *ct,
7179 unsigned long blocks,
7180 symmetric_key *skey);
7181
7182 /** Accelerated ECB decryption
7183 @param pt Plaintext
7184 @param ct Ciphertext
7185 @param blocks The number of complete blocks to process
7186 @param skey The scheduled key context
7187 @return CRYPT_OK if successful
7188 */
7189 int (*accel_ecb_decrypt)(const unsigned char *ct,
7190 unsigned char *pt,
7191 unsigned long blocks,
7192 symmetric_key *skey);
7193
7194 /** Accelerated CBC encryption
7195 @param pt Plaintext
7196 @param ct Ciphertext
7197 @param blocks The number of complete blocks to process
7198 @param IV The initial value (input/output)
7199 @param skey The scheduled key context
7200 @return CRYPT_OK if successful
7201 */
7202 int (*accel_cbc_encrypt)(const unsigned char *pt,
7203 unsigned char *ct,
7204 unsigned long blocks,
7205 unsigned char *IV,
7206 symmetric_key *skey);
7207
7208 /** Accelerated CBC decryption
7209 @param pt Plaintext
7210 @param ct Ciphertext
7211 @param blocks The number of complete blocks to process
7212 @param IV The initial value (input/output)
7213 @param skey The scheduled key context
7214 @return CRYPT_OK if successful
7215 */
7216 int (*accel_cbc_decrypt)(const unsigned char *ct,
7217 unsigned char *pt,
7218 unsigned long blocks,
7219 unsigned char *IV,
7220 symmetric_key *skey);
7221
7222 /** Accelerated CTR encryption
7223 @param pt Plaintext
7224 @param ct Ciphertext
7225 @param blocks The number of complete blocks to process
7226 @param IV The initial value (input/output)
7227 @param mode little or big endian counter (mode=0 or mode=1)
7228 @param skey The scheduled key context
7229 @return CRYPT_OK if successful
7230 */
7231 int (*accel_ctr_encrypt)(const unsigned char *pt,
7232 unsigned char *ct,
7233 unsigned long blocks,
7234 unsigned char *IV,
7235 int mode,
7236 symmetric_key *skey);
7237
7238 /** Accelerated LRW
7239 @param pt Plaintext
7240 @param ct Ciphertext
7241 @param blocks The number of complete blocks to process
7242 @param IV The initial value (input/output)
7243 @param tweak The LRW tweak
7244 @param skey The scheduled key context
7245 @return CRYPT_OK if successful
7246 */
7247 int (*accel_lrw_encrypt)(const unsigned char *pt,
7248 unsigned char *ct,
7249 unsigned long blocks,
7250 unsigned char *IV,
7251 const unsigned char *tweak,
7252 symmetric_key *skey);
7253
7254 /** Accelerated LRW
7255 @param ct Ciphertext
7256 @param pt Plaintext
7257 @param blocks The number of complete blocks to process
7258 @param IV The initial value (input/output)
7259 @param tweak The LRW tweak
7260 @param skey The scheduled key context
7261 @return CRYPT_OK if successful
7262 */
7263 int (*accel_lrw_decrypt)(const unsigned char *ct,
7264 unsigned char *pt,
7265 unsigned long blocks,
7266 unsigned char *IV,
7267 const unsigned char *tweak,
7268 symmetric_key *skey);
7269
7270 /** Accelerated CCM packet (one-shot)
7271 @param key The secret key to use
7272 @param keylen The length of the secret key (octets)
7273 @param uskey A previously scheduled key [can be NULL]
7274 @param nonce The session nonce [use once]
7275 @param noncelen The length of the nonce
7276 @param header The header for the session
7277 @param headerlen The length of the header (octets)
7278 @param pt [out] The plaintext
7279 @param ptlen The length of the plaintext (octets)
7280 @param ct [out] The ciphertext
7281 @param tag [out] The destination tag
7282 @param taglen [in/out] The max size and resulting size
7283 of the authentication tag
7284 @param direction Encrypt or Decrypt direction (0 or 1)
7285 @return CRYPT_OK if successful
7286 */
7287 int (*accel_ccm_memory)(
7288 const unsigned char *key, unsigned long keylen,
7289 symmetric_key *uskey,
7290 const unsigned char *nonce, unsigned long noncelen,
7291 const unsigned char *header, unsigned long headerlen,
7292 unsigned char *pt, unsigned long ptlen,
7293 unsigned char *ct,
7294 unsigned char *tag, unsigned long *taglen,
7295 int direction);
7296
7297 /** Accelerated GCM packet (one shot)
7298 @param key The secret key
7299 @param keylen The length of the secret key
7300 @param IV The initialization vector
7301 @param IVlen The length of the initialization vector
7302 @param adata The additional authentication data (header)
7303 @param adatalen The length of the adata
7304 @param pt The plaintext
7305 @param ptlen The length of the plaintext/ciphertext
7306 @param ct The ciphertext
7307 @param tag [out] The MAC tag
7308 @param taglen [in/out] The MAC tag length
7309 @param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
7310 @return CRYPT_OK on success
7311 */
7312 int (*accel_gcm_memory)(
7313 const unsigned char *key, unsigned long keylen,
7314 const unsigned char *IV, unsigned long IVlen,
7315 const unsigned char *adata, unsigned long adatalen,
7316 unsigned char *pt, unsigned long ptlen,
7317 unsigned char *ct,
7318 unsigned char *tag, unsigned long *taglen,
7319 int direction);
7320
7321 /** Accelerated one shot OMAC
7322 @param key The secret key
7323 @param keylen The key length (octets)
7324 @param in The message
7325 @param inlen Length of message (octets)
7326 @param out [out] Destination for tag
7327 @param outlen [in/out] Initial and final size of out
7328 @return CRYPT_OK on success
7329 */
7330 int (*omac_memory)(
7331 const unsigned char *key, unsigned long keylen,
7332 const unsigned char *in, unsigned long inlen,
7333 unsigned char *out, unsigned long *outlen);
7334
7335 /** Accelerated one shot XCBC
7336 @param key The secret key
7337 @param keylen The key length (octets)
7338 @param in The message
7339 @param inlen Length of message (octets)
7340 @param out [out] Destination for tag
7341 @param outlen [in/out] Initial and final size of out
7342 @return CRYPT_OK on success
7343 */
7344 int (*xcbc_memory)(
7345 const unsigned char *key, unsigned long keylen,
7346 const unsigned char *in, unsigned long inlen,
7347 unsigned char *out, unsigned long *outlen);
7348
7349 /** Accelerated one shot F9
7350 @param key The secret key
7351 @param keylen The key length (octets)
7352 @param in The message
7353 @param inlen Length of message (octets)
7354 @param out [out] Destination for tag
7355 @param outlen [in/out] Initial and final size of out
7356 @return CRYPT_OK on success
7357 @remark Requires manual padding
7358 */
7359 int (*f9_memory)(
7360 const unsigned char *key, unsigned long keylen,
7361 const unsigned char *in, unsigned long inlen,
7362 unsigned char *out, unsigned long *outlen);
7363 };
7364 \end{verbatim}
7365 \end{small}
7366
7367 \subsection{Name}
7368 \index{find\_cipher()}
7369 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
7370 tables.
7371
7372 \subsection{Internal ID}
7373 This is a single byte Internal ID you can use to distinguish ciphers from each other.
7374
7375 \subsection{Key Lengths}
7376 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
7377 and both must valid key sizes for the cipher. Values in between are not assumed to be valid though they may be.
7378
7379 \subsection{Block Length}
7380 The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.
7381
7382 \subsection{Rounds}
7383 Some ciphers allow different number of rounds to be used. Usually you just use the default. The default round count is \textit{default\_rounds}.
7384
7385 \subsection{Setup}
7386 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
7387 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
7388 in \textit{skey}.
7389
7390 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
7391 ones provided. Just make sure in your \textit{done()} function that you free the allocated memory.
7392
7393 \subsection{Single block ECB}
7394 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
7395 must make sure you do not overwrite the output before you are finished with the input.
7396
7397 \subsection{Testing}
7398 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
7399 \textbf{CRYPT\_NOP} to indicate that no testing was performed.
7400
7401 \subsection{Key Sizing}
7402 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
7403 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
7404 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
7405 cannot be mapped to a valid key size for the cipher.
7406
7407 \subsection{Acceleration}
7408 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
7409 it is not supported. In those cases the software defaults are used (using the single ECB block routines).
7410
7411 \subsubsection{Accelerated ECB}
7412 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
7413 through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers. The \textit{blocks} count is the number of complete blocks to process.
7414
7415 \subsubsection{Accelerated CBC}
7416 These two functions are meant for accelerated CBC encryption. These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
7417 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
7418 updated by the function before returning.
7419
7420 \subsubsection{Accelerated CTR}
7421 This function is meant for accelerated CTR encryption. It is accessible through the accel\_ctr\_encrypt pointer.
7422 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
7423 updated by the function before returning. The \textit{mode} value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or
7424 little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.
7425
7426 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
7427 called if the following conditions are met.
7428
7429 \begin{enumerate}
7430 \item The accelerator is present
7431 \item The CTR pad is empty
7432 \item The remaining length of the input to process is greater than or equal to the block size.
7433 \end{enumerate}
7434
7435 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
7436 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
7437 buffer provided) before encrypting it to create the pad.
7438
7439 The accelerator will only be used to encrypt whole blocks. Partial blocks are always handled in software.
7440
7441 \subsubsection{Accelerated LRW}
7442 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}
7443 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
7444 to use accelerators for LRW.
7445
7446 While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_setiv() more efficient.
7447
7448 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
7449 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
7450 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
7451 free them.
7452
7453 \subsubsection{Accelerated CCM}
7454 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
7455 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
7456 function MUST support both key passing methods.
7457
7458 \begin{center}
7459 \begin{small}
7460 \begin{tabular}{|r|r|l|}
7461 \hline \textbf{key} & \textbf{uskey} & \textbf{Source of key} \\
7462 \hline NULL & NULL & Error, not supported \\
7463 \hline non-NULL & NULL & Use key, do a key schedule \\
7464 \hline NULL & non-NULL & Use uskey, key schedule not required \\
7465 \hline non-NULL & non-NULL & Use uskey, key schedule not required \\
7466 \hline
7467 \end{tabular}
7468 \end{small}
7469 \end{center}
7470
7471 \index{ccm\_memory()} This function is called when the user calls ccm\_memory().
7472
7473 \subsubsection{Accelerated GCM}
7474 \index{gcm\_memory()}
7475 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
7476 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().
7477
7478 \subsubsection{Accelerated OMAC}
7479 \index{omac\_memory()}
7480 This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_memory().
7481
7482 \subsubsection{Accelerated XCBC-MAC}
7483 \index{xcbc\_memory()}
7484 This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_memory().
7485
7486 \subsubsection{Accelerated F9}
7487 \index{f9\_memory()}
7488 This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory(). Like f9\_memory(), it requires
7489 the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.
7490
7491
7492 \mysection{One--Way Hashes}
7493 The hash functions are accessed through the ltc\_hash\_descriptor structure.
7494
7495 \begin{small}
7496 \begin{verbatim}
7497 struct ltc_hash_descriptor {
7498 /** name of hash */
7499 char *name;
7500
7501 /** internal ID */
7502 unsigned char ID;
7503
7504 /** Size of digest in octets */
7505 unsigned long hashsize;
7506
7507 /** Input block size in octets */
7508 unsigned long blocksize;
7509
7510 /** ASN.1 OID */
7511 unsigned long OID[16];
7512
7513 /** Length of DER encoding */
7514 unsigned long OIDlen;
7515
7516 /** Init a hash state
7517 @param hash The hash to initialize
7518 @return CRYPT_OK if successful
7519 */
7520 int (*init)(hash_state *hash);
7521
7522 /** Process a block of data
7523 @param hash The hash state
7524 @param in The data to hash
7525 @param inlen The length of the data (octets)
7526 @return CRYPT_OK if successful
7527 */
7528 int (*process)( hash_state *hash,
7529 const unsigned char *in,
7530 unsigned long inlen);
7531
7532 /** Produce the digest and store it
7533 @param hash The hash state
7534 @param out [out] The destination of the digest
7535 @return CRYPT_OK if successful
7536 */
7537 int (*done)( hash_state *hash,
7538 unsigned char *out);
7539
7540 /** Self-test
7541 @return CRYPT_OK if successful,
7542 CRYPT_NOP if self-tests have been disabled
7543 */
7544 int (*test)(void);
7545
7546 /* accelerated hmac callback: if you need to-do
7547 multiple packets just use the generic hmac_memory
7548 and provide a hash callback
7549 */
7550 int (*hmac_block)(const unsigned char *key,
7551 unsigned long keylen,
7552 const unsigned char *in,
7553 unsigned long inlen,
7554 unsigned char *out,
7555 unsigned long *outlen);
7556 };
7557 \end{verbatim}
7558 \end{small}
7559
7560 \subsection{Name}
7561 This is the name the hash is known by and what find\_hash() will look for.
7562
7563 \subsection{Internal ID}
7564 This is the internal ID byte used to distinguish the hash from other hashes.
7565
7566 \subsection{Digest Size}
7567 The \textit{hashsize} variable indicates the length of the output in octets.
7568
7569 \subsection{Block Size}
7570 The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
7571 invocation.
7572
7573 \subsection{OID Identifier}
7574 This is the universal ASN.1 Object Identifier for the hash.
7575
7576 \subsection{Initialization}
7577 The init function initializes the hash and prepares it to process message bytes.
7578
7579 \subsection{Process}
7580 This processes message bytes. The algorithm must accept any length of input that the hash would allow. The input is not
7581 guaranteed to be a multiple of the block size in length.
7582
7583 \subsection{Done}
7584 The done function terminates the hash and returns the message digest.
7585
7586 \subsection{Acceleration}
7587 A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.
7588
7589 \subsection{HMAC Acceleration}
7590 The hmac\_block() callback is meant for single--shot optimized HMAC implementations. It is called directly by hmac\_memory() if present. If you need
7591 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.
7592
7593 \mysection{Pseudo--Random Number Generators}
7594 The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.
7595
7596 \begin{small}
7597 \begin{verbatim}
7598 struct ltc_prng_descriptor {
7599 /** Name of the PRNG */
7600 char *name;
7601
7602 /** size in bytes of exported state */
7603 int export_size;
7604
7605 /** Start a PRNG state
7606 @param prng [out] The state to initialize
7607 @return CRYPT_OK if successful
7608 */
7609 int (*start)(prng_state *prng);
7610
7611 /** Add entropy to the PRNG
7612 @param in The entropy
7613 @param inlen Length of the entropy (octets)
7614 @param prng The PRNG state
7615 @return CRYPT_OK if successful
7616 */
7617 int (*add_entropy)(const unsigned char *in,
7618 unsigned long inlen,
7619 prng_state *prng);
7620
7621 /** Ready a PRNG state to read from
7622 @param prng The PRNG state to ready
7623 @return CRYPT_OK if successful
7624 */
7625 int (*ready)(prng_state *prng);
7626
7627 /** Read from the PRNG
7628 @param out [out] Where to store the data
7629 @param outlen Length of data desired (octets)
7630 @param prng The PRNG state to read from
7631 @return Number of octets read
7632 */
7633 unsigned long (*read)(unsigned char *out,
7634 unsigned long outlen,
7635 prng_state *prng);
7636
7637 /** Terminate a PRNG state
7638 @param prng The PRNG state to terminate
7639 @return CRYPT_OK if successful
7640 */
7641 int (*done)(prng_state *prng);
7642
7643 /** Export a PRNG state
7644 @param out [out] The destination for the state
7645 @param outlen [in/out] The max size and resulting size
7646 @param prng The PRNG to export
7647 @return CRYPT_OK if successful
7648 */
7649 int (*pexport)(unsigned char *out,
7650 unsigned long *outlen,
7651 prng_state *prng);
7652
7653 /** Import a PRNG state
7654 @param in The data to import
7655 @param inlen The length of the data to import (octets)
7656 @param prng The PRNG to initialize/import
7657 @return CRYPT_OK if successful
7658 */
7659 int (*pimport)(const unsigned char *in,
7660 unsigned long inlen,
7661 prng_state *prng);
7662
7663 /** Self-test the PRNG
7664 @return CRYPT_OK if successful,
7665 CRYPT_NOP if self-testing has been disabled
7666 */
7667 int (*test)(void);
7668 };
7669 \end{verbatim}
7670 \end{small}
7671
7672 \subsection{Name}
7673 The name by which find\_prng() will find the PRNG.
7674
7675 \subsection{Export Size}
7676 When an PRNG state is to be exported for future use you specify the space required in this variable.
7677
7678 \subsection{Start}
7679 Initialize the PRNG and make it ready to accept entropy.
7680
7681 \subsection{Entropy Addition}
7682 Add entropy to the PRNG state. The exact behaviour of this function depends on the particulars of the PRNG.
7683
7684 \subsection{Ready}
7685 This function makes the PRNG ready to read from by processing the entropy added. The behaviour of this function depends
7686 on the specific PRNG used.
7687
7688 \subsection{Read}
7689 Read from the PRNG and return the number of bytes read. This function does not have to fill the buffer but it is best
7690 if it does as many protocols do not retry reads and will fail on the first try.
7691
7692 \subsection{Done}
7693 Terminate a PRNG state. The behaviour of this function depends on the particular PRNG used.
7694
7695 \subsection{Exporting and Importing}
7696 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}
7697 but should at least maintain the same level of state entropy.
7698
7699 \mysection{BigNum Math Descriptors}
7700 The library also makes use of the math descriptors to access math functions. While bignum math libraries usually differ in implementation
7701 it hasn't proven hard to write \textit{glue} to use math libraries so far. The basic descriptor looks like.
7702
7703 \begin{small}
7704 \begin{verbatim}
7705 /** math descriptor */
7706 typedef struct {
7707 /** Name of the math provider */
7708 char *name;
7709
7710 /** Bits per digit, amount of bits must fit in an unsigned long */
7711 int bits_per_digit;
7712
7713 /* ---- init/deinit functions ---- */
7714
7715 /** initialize a bignum
7716 @param a The number to initialize
7717 @return CRYPT_OK on success
7718 */
7719 int (*init)(void **a);
7720
7721 /** init copy
7722 @param dst The number to initialize and write to
7723 @param src The number to copy from
7724 @return CRYPT_OK on success
7725 */
7726 int (*init_copy)(void **dst, void *src);
7727
7728 /** deinit
7729 @param a The number to free
7730 @return CRYPT_OK on success
7731 */
7732 void (*deinit)(void *a);
7733
7734 /* ---- data movement ---- */
7735
7736 /** negate
7737 @param src The number to negate
7738 @param dst The destination
7739 @return CRYPT_OK on success
7740 */
7741 int (*neg)(void *src, void *dst);
7742
7743 /** copy
7744 @param src The number to copy from
7745 @param dst The number to write to
7746 @return CRYPT_OK on success
7747 */
7748 int (*copy)(void *src, void *dst);
7749
7750 /* ---- trivial low level functions ---- */
7751
7752 /** set small constant
7753 @param a Number to write to
7754 @param n Source upto bits_per_digit (actually meant for very small constants)
7755 @return CRYPT_OK on success
7756 */
7757 int (*set_int)(void *a, unsigned long n);
7758
7759 /** get small constant
7760 @param a Small number to read,
7761 only fetches up to bits_per_digit from the number
7762 @return The lower bits_per_digit of the integer (unsigned)
7763 */
7764 unsigned long (*get_int)(void *a);
7765
7766 /** get digit n
7767 @param a The number to read from
7768 @param n The number of the digit to fetch
7769 @return The bits_per_digit sized n'th digit of a
7770 */
7771 ltc_mp_digit (*get_digit)(void *a, int n);
7772
7773 /** Get the number of digits that represent the number
7774 @param a The number to count
7775 @return The number of digits used to represent the number
7776 */
7777 int (*get_digit_count)(void *a);
7778
7779 /** compare two integers
7780 @param a The left side integer
7781 @param b The right side integer
7782 @return LTC_MP_LT if a < b,
7783 LTC_MP_GT if a > b and
7784 LTC_MP_EQ otherwise. (signed comparison)
7785 */
7786 int (*compare)(void *a, void *b);
7787
7788 /** compare against int
7789 @param a The left side integer
7790 @param b The right side integer (upto bits_per_digit)
7791 @return LTC_MP_LT if a < b,
7792 LTC_MP_GT if a > b and
7793 LTC_MP_EQ otherwise. (signed comparison)
7794 */
7795 int (*compare_d)(void *a, unsigned long n);
7796
7797 /** Count the number of bits used to represent the integer
7798 @param a The integer to count
7799 @return The number of bits required to represent the integer
7800 */
7801 int (*count_bits)(void * a);
7802
7803 /** Count the number of LSB bits which are zero
7804 @param a The integer to count
7805 @return The number of contiguous zero LSB bits
7806 */
7807 int (*count_lsb_bits)(void *a);
7808
7809 /** Compute a power of two
7810 @param a The integer to store the power in
7811 @param n The power of two you want to store (a = 2^n)
7812 @return CRYPT_OK on success
7813 */
7814 int (*twoexpt)(void *a , int n);
7815
7816 /* ---- radix conversions ---- */
7817
7818 /** read ascii string
7819 @param a The integer to store into
7820 @param str The string to read
7821 @param radix The radix the integer has been represented in (2-64)
7822 @return CRYPT_OK on success
7823 */
7824 int (*read_radix)(void *a, const char *str, int radix);
7825
7826 /** write number to string
7827 @param a The integer to store
7828 @param str The destination for the string
7829 @param radix The radix the integer is to be represented in (2-64)
7830 @return CRYPT_OK on success
7831 */
7832 int (*write_radix)(void *a, char *str, int radix);
7833
7834 /** get size as unsigned char string
7835 @param a The integer to get the size (when stored in array of octets)
7836 @return The length of the integer in octets
7837 */
7838 unsigned long (*unsigned_size)(void *a);
7839
7840 /** store an integer as an array of octets
7841 @param src The integer to store
7842 @param dst The buffer to store the integer in
7843 @return CRYPT_OK on success
7844 */
7845 int (*unsigned_write)(void *src, unsigned char *dst);
7846
7847 /** read an array of octets and store as integer
7848 @param dst The integer to load
7849 @param src The array of octets
7850 @param len The number of octets
7851 @return CRYPT_OK on success
7852 */
7853 int (*unsigned_read)( void *dst,
7854 unsigned char *src,
7855 unsigned long len);
7856
7857 /* ---- basic math ---- */
7858
7859 /** add two integers
7860 @param a The first source integer
7861 @param b The second source integer
7862 @param c The destination of "a + b"
7863 @return CRYPT_OK on success
7864 */
7865 int (*add)(void *a, void *b, void *c);
7866
7867 /** add two integers
7868 @param a The first source integer
7869 @param b The second source integer
7870 (single digit of upto bits_per_digit in length)
7871 @param c The destination of "a + b"
7872 @return CRYPT_OK on success
7873 */
7874 int (*addi)(void *a, unsigned long b, void *c);
7875
7876 /** subtract two integers
7877 @param a The first source integer
7878 @param b The second source integer
7879 @param c The destination of "a - b"
7880 @return CRYPT_OK on success
7881 */
7882 int (*sub)(void *a, void *b, void *c);
7883
7884 /** subtract two integers
7885 @param a The first source integer
7886 @param b The second source integer
7887 (single digit of upto bits_per_digit in length)
7888 @param c The destination of "a - b"
7889 @return CRYPT_OK on success
7890 */
7891 int (*subi)(void *a, unsigned long b, void *c);
7892
7893 /** multiply two integers
7894 @param a The first source integer
7895 @param b The second source integer
7896 (single digit of upto bits_per_digit in length)
7897 @param c The destination of "a * b"
7898 @return CRYPT_OK on success
7899 */
7900 int (*mul)(void *a, void *b, void *c);
7901
7902 /** multiply two integers
7903 @param a The first source integer
7904 @param b The second source integer
7905 (single digit of upto bits_per_digit in length)
7906 @param c The destination of "a * b"
7907 @return CRYPT_OK on success
7908 */
7909 int (*muli)(void *a, unsigned long b, void *c);
7910
7911 /** Square an integer
7912 @param a The integer to square
7913 @param b The destination
7914 @return CRYPT_OK on success
7915 */
7916 int (*sqr)(void *a, void *b);
7917
7918 /** Divide an integer
7919 @param a The dividend
7920 @param b The divisor
7921 @param c The quotient (can be NULL to signify don't care)
7922 @param d The remainder (can be NULL to signify don't care)
7923 @return CRYPT_OK on success
7924 */
7925 int (*mpdiv)(void *a, void *b, void *c, void *d);
7926
7927 /** divide by two
7928 @param a The integer to divide (shift right)
7929 @param b The destination
7930 @return CRYPT_OK on success
7931 */
7932 int (*div_2)(void *a, void *b);
7933
7934 /** Get remainder (small value)
7935 @param a The integer to reduce
7936 @param b The modulus (upto bits_per_digit in length)
7937 @param c The destination for the residue
7938 @return CRYPT_OK on success
7939 */
7940 int (*modi)(void *a, unsigned long b, unsigned long *c);
7941
7942 /** gcd
7943 @param a The first integer
7944 @param b The second integer
7945 @param c The destination for (a, b)
7946 @return CRYPT_OK on success
7947 */
7948 int (*gcd)(void *a, void *b, void *c);
7949
7950 /** lcm
7951 @param a The first integer
7952 @param b The second integer
7953 @param c The destination for [a, b]
7954 @return CRYPT_OK on success
7955 */
7956 int (*lcm)(void *a, void *b, void *c);
7957
7958 /** Modular multiplication
7959 @param a The first source
7960 @param b The second source
7961 @param c The modulus
7962 @param d The destination (a*b mod c)
7963 @return CRYPT_OK on success
7964 */
7965 int (*mulmod)(void *a, void *b, void *c, void *d);
7966
7967 /** Modular squaring
7968 @param a The first source
7969 @param b The modulus
7970 @param c The destination (a*a mod b)
7971 @return CRYPT_OK on success
7972 */
7973 int (*sqrmod)(void *a, void *b, void *c);
7974
7975 /** Modular inversion
7976 @param a The value to invert
7977 @param b The modulus
7978 @param c The destination (1/a mod b)
7979 @return CRYPT_OK on success
7980 */
7981 int (*invmod)(void *, void *, void *);
7982
7983 /* ---- reduction ---- */
7984
7985 /** setup Montgomery
7986 @param a The modulus
7987 @param b The destination for the reduction digit
7988 @return CRYPT_OK on success
7989 */
7990 int (*montgomery_setup)(void *a, void **b);
7991
7992 /** get normalization value
7993 @param a The destination for the normalization value
7994 @param b The modulus
7995 @return CRYPT_OK on success
7996 */
7997 int (*montgomery_normalization)(void *a, void *b);
7998
7999 /** reduce a number
8000 @param a The number [and dest] to reduce
8001 @param b The modulus
8002 @param c The value "b" from montgomery_setup()
8003 @return CRYPT_OK on success
8004 */
8005 int (*montgomery_reduce)(void *a, void *b, void *c);
8006
8007 /** clean up (frees memory)
8008 @param a The value "b" from montgomery_setup()
8009 @return CRYPT_OK on success
8010 */
8011 void (*montgomery_deinit)(void *a);
8012
8013 /* ---- exponentiation ---- */
8014
8015 /** Modular exponentiation
8016 @param a The base integer
8017 @param b The power (can be negative) integer
8018 @param c The modulus integer
8019 @param d The destination
8020 @return CRYPT_OK on success
8021 */
8022 int (*exptmod)(void *a, void *b, void *c, void *d);
8023
8024 /** Primality testing
8025 @param a The integer to test
8026 @param b The number of Miller-Rabin tests that shall be executed
8027 @param c The destination of the result (FP_YES if prime)
8028 @return CRYPT_OK on success
8029 */
8030 int (*isprime)(void *a, int b, int *c);
8031
8032 /* ---- (optional) ecc point math ---- */
8033
8034 /** ECC GF(p) point multiplication (from the NIST curves)
8035 @param k The integer to multiply the point by
8036 @param G The point to multiply
8037 @param R The destination for kG
8038 @param modulus The modulus for the field
8039 @param map Boolean indicated whether to map back to affine or not
8040 (can be ignored if you work in affine only)
8041 @return CRYPT_OK on success
8042 */
8043 int (*ecc_ptmul)( void *k,
8044 ecc_point *G,
8045 ecc_point *R,
8046 void *modulus,
8047 int map);
8048
8049 /** ECC GF(p) point addition
8050 @param P The first point
8051 @param Q The second point
8052 @param R The destination of P + Q
8053 @param modulus The modulus
8054 @param mp The "b" value from montgomery_setup()
8055 @return CRYPT_OK on success
8056 */
8057 int (*ecc_ptadd)(ecc_point *P,
8058 ecc_point *Q,
8059 ecc_point *R,
8060 void *modulus,
8061 void *mp);
8062
8063 /** ECC GF(p) point double
8064 @param P The first point
8065 @param R The destination of 2P
8066 @param modulus The modulus
8067 @param mp The "b" value from montgomery_setup()
8068 @return CRYPT_OK on success
8069 */
8070 int (*ecc_ptdbl)(ecc_point *P,
8071 ecc_point *R,
8072 void *modulus,
8073 void *mp);
8074
8075 /** ECC mapping from projective to affine,
8076 currently uses (x,y,z) => (x/z^2, y/z^3, 1)
8077 @param P The point to map
8078 @param modulus The modulus
8079 @param mp The "b" value from montgomery_setup()
8080 @return CRYPT_OK on success
8081 @remark The mapping can be different but keep in mind a
8082 ecc_point only has three integers (x,y,z) so if
8083 you use a different mapping you have to make it fit.
8084 */
8085 int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
8086
8087 /** Computes kA*A + kB*B = C using Shamir's Trick
8088 @param A First point to multiply
8089 @param kA What to multiple A by
8090 @param B Second point to multiply
8091 @param kB What to multiple B by
8092 @param C [out] Destination point (can overlap with A or B)
8093 @param modulus Modulus for curve
8094 @return CRYPT_OK on success
8095 */
8096 int (*ecc_mul2add)(ecc_point *A, void *kA,
8097 ecc_point *B, void *kB,
8098 ecc_point *C,
8099 void *modulus);
8100
8101 /* ---- (optional) rsa optimized math (for internal CRT) ---- */
8102
8103 /** RSA Key Generation
8104 @param prng An active PRNG state
8105 @param wprng The index of the PRNG desired
8106 @param size The size of the key in octets
8107 @param e The "e" value (public key).
8108 e==65537 is a good choice
8109 @param key [out] Destination of a newly created private key pair
8110 @return CRYPT_OK if successful, upon error all allocated ram is freed
8111 */
8112 int (*rsa_keygen)(prng_state *prng,
8113 int wprng,
8114 int size,
8115 long e,
8116 rsa_key *key);
8117
8118 /** RSA exponentiation
8119 @param in The octet array representing the base
8120 @param inlen The length of the input
8121 @param out The destination (to be stored in an octet array format)
8122 @param outlen The length of the output buffer and the resulting size
8123 (zero padded to the size of the modulus)
8124 @param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
8125 @param key The RSA key to use
8126 @return CRYPT_OK on success
8127 */
8128 int (*rsa_me)(const unsigned char *in, unsigned long inlen,
8129 unsigned char *out, unsigned long *outlen, int which,
8130 rsa_key *key);
8131
8132 /* ---- basic math continued ---- */
8133
8134 /** Modular addition
8135 @param a The first source
8136 @param b The second source
8137 @param c The modulus
8138 @param d The destination (a + b mod c)
8139 @return CRYPT_OK on success
8140 */
8141 int (*addmod)(void *a, void *b, void *c, void *d);
8142
8143 /** Modular substraction
8144 @param a The first source
8145 @param b The second source
8146 @param c The modulus
8147 @param d The destination (a - b mod c)
8148 @return CRYPT_OK on success
8149 */
8150 int (*submod)(void *a, void *b, void *c, void *d);
8151
8152 /* ---- misc stuff ---- */
8153
8154 /** Make a pseudo-random mpi
8155 @param a The mpi to make random
8156 @param size The desired length
8157 @return CRYPT_OK on success
8158 */
8159 int (*rand)(void *a, int size);
8160 } ltc_math_descriptor;
8161 \end{verbatim}
8162 \end{small}
8163
8164 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.
8165
8166 \subsection{Conventions}
8167
8168 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
8169 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
8170 free the bignum as well as the structure you allocated to place it in.
8171
8172 All functions except the Montgomery reductions work from left to right with the arguments. For example, mul(a, b, c) computes $c \leftarrow ab$.
8173
8174 All functions (except where noted otherwise) return \textbf{CRYPT\_OK} to signify a successful operation. All error codes must be valid LibTomCrypt error codes.
8175
8176 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
8177 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.
8178
8179 \subsubsection{ltc\_mp\_digit}
8180 \index{ltc\_mp\_digit}
8181
8182 Depending on the archtitecture \textit{ltc\_mp\_digit} is either a $32$- or $64$-bit long \textit{unsigned} data type.
8183
8184 \subsection{ECC Functions}
8185 The ECC system in LibTomCrypt is based off of the NIST recommended curves over $GF(p)$ and is used to implement EC-DSA and EC-DH. The ECC functions work with
8186 the \textbf{ecc\_point} structure and assume the points are stored in Jacobian projective format.
8187
8188 \begin{verbatim}
8189 /** A point on a ECC curve, stored in Jacobian format such
8190 that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */
8191 typedef struct {
8192 /** The x co-ordinate */
8193 void *x;
8194 /** The y co-ordinate */
8195 void *y;
8196 /** The z co-ordinate */
8197 void *z;
8198 } ecc_point;
8199 \end{verbatim}
8200
8201 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
8202 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
8203 could point to anything you want. The only further exception is the export functions which expects the values to be in affine format.
8204
8205 \subsubsection{Point Multiply}
8206 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.
8207
8208 \subsubsection{Point Addition}
8209 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
8210 may be in either affine (with $z = 1$) or projective format and the output point is always projective.
8211
8212 \subsubsection{Point Mapping}
8213 This will map the point $P$ back from projective to affine. The output point $P$ must be of the form $(x, y, 1)$.
8214
8215 \subsubsection{Shamir's Trick}
8216 \index{Shamir's Trick}
8217 \index{ltc\_ecc\_mul2add()}
8218 To accelerate EC--DSA verification the library provides a built--in function called ltc\_ecc\_mul2add(). This performs two point multiplications and an addition in
8219 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
8220 overlap (e.g., $A \leftarrow k_1A + k_2B$) and must return the final point in affine format.
8221
8222
8223 \subsection{RSA Functions}
8224 The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations. In particular for
8225 private key operations it uses the CRT approach to lower the time required. It is passed an RSA key with the following format.
8226
8227 \begin{verbatim}
8228 /** RSA PKCS style key */
8229 typedef struct Rsa_key {
8230 /** Type of key, PK_PRIVATE or PK_PUBLIC */
8231 int type;
8232 /** The public exponent */
8233 void *e;
8234 /** The private exponent */
8235 void *d;
8236 /** The modulus */
8237 void *N;
8238 /** The p factor of N */
8239 void *p;
8240 /** The q factor of N */
8241 void *q;
8242 /** The 1/q mod p CRT param */
8243 void *qP;
8244 /** The d mod (p - 1) CRT param */
8245 void *dP;
8246 /** The d mod (q - 1) CRT param */
8247 void *dQ;
8248 } rsa_key;
8249 \end{verbatim}
8250
8251 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
8252 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,
8253 for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.
8254
8255 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.
8256
8257 \newpage
8258 \markboth{Index}{Index}
8259 \input{crypt.ind}
8260
8261 \end{document}
8262
8263 % ref: $Format:%D$
8264 % git commit: $Format:%H$
8265 % commit time: $Format:%ai$