forked from libtom/libtomcrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.tex
6868 lines (5711 loc) · 305 KB
/
crypt.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[synpaper]{book}
\usepackage[dvips]{geometry}
\usepackage{hyperref}
\usepackage{makeidx}
\usepackage{amssymb}
\usepackage{color}
\usepackage{alltt}
\usepackage{graphicx}
\usepackage{layout}
\usepackage{fancyhdr}
\def\union{\cup}
\def\intersect{\cap}
\def\getsrandom{\stackrel{\rm R}{\gets}}
\def\cross{\times}
\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
\def\catn{$\|$}
\def\divides{\hspace{0.3em} | \hspace{0.3em}}
\def\nequiv{\not\equiv}
\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
\def\lcm{{\rm lcm}}
\def\gcd{{\rm gcd}}
\def\log{{\rm log}}
\def\ord{{\rm ord}}
\def\abs{{\mathit abs}}
\def\rep{{\mathit rep}}
\def\mod{{\mathit\ mod\ }}
\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
\def\Or{{\rm\ or\ }}
\def\And{{\rm\ and\ }}
\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
\def\implies{\Rightarrow}
\def\undefined{{\rm \textit{undefined}}}
\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
\let\oldphi\phi
\def\phi{\varphi}
\def\Pr{{\rm Pr}}
\newcommand{\str}[1]{{\mathbf{#1}}}
\def\F{{\mathbb F}}
\def\N{{\mathbb N}}
\def\Z{{\mathbb Z}}
\def\R{{\mathbb R}}
\def\C{{\mathbb C}}
\def\Q{{\mathbb Q}}
\definecolor{DGray}{gray}{0.5}
\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
\def\gap{\vspace{0.5ex}}
\makeindex
\newcommand{\mysection}[1] % Re-define the chaptering command to use
{ % THESE headers.
\section{#1}
\markboth{\textsf{www.libtom.org}}{\thesection ~ {#1}}
}
\newcommand{\mystarsection}[1] % Re-define the chaptering command to use
{ % THESE headers.
\section*{#1}
\markboth{\textsf{www.libtom.org}}{{#1}}
}
\pagestyle{empty}
\begin{document}
\frontmatter
\pagestyle{empty}
~
\vspace{2in}
~
\begin{center}
\begin{Huge}LibTomCrypt\end{Huge}
~
\begin{large}Developer Manual\end{large}
~
\vspace{15mm}
\begin{tabular}{c}
Tom St Denis \\
LibTom Projects
\end{tabular}
\end{center}
\vfil
\newpage
This document is part of the LibTomCrypt package and is hereby released into the public domain.
~
Open Source. Open Academia. Open Minds.
~
\begin{flushright}
Tom St Denis
~
Ottawa, Ontario
~
Canada
~
\vfil
\end{flushright}
\newpage
\tableofcontents
\listoffigures
\pagestyle{myheadings}
\mainmatter
\chapter{Introduction}
\mysection{What is the LibTomCrypt?}
LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
designing cryptosystems. It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
public key cryptography (via PKCS \#1 RSA, DH or ECCDH), and a plethora of support routines.
The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
(and helper API functions) are able to use the new designs automatically. There exists self-check functions for each
block cipher and hash function to ensure that they compile and execute to the published design specifications. The library
also performs extensive parameter error checking to prevent any number of run-time exploits or errors.
\subsection{What the library IS for?}
The library serves as a toolkit for developers who have to solve cryptographic problems. Out of the box LibTomCrypt
does not process SSL or OpenPGP messages, it doesn't read X.509 certificates, or write PEM encoded data. It does, however,
provide all of the tools required to build such functionality. LibTomCrypt was designed to be a flexible library that
was not tied to any particular cryptographic problem.
\mysection{Why did I write it?}
You may be wondering, \textit{Tom, why did you write a crypto library. I already have one.} Well the reason falls into
two categories:
\begin{enumerate}
\item I am too lazy to figure out someone else's API. I'd rather invent my own simpler API and use that.
\item It was (still is) good coding practice.
\end{enumerate}
The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc. I'm trying to write my
{\bf own} crypto library and hopefully along the way others will appreciate the work.
With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition. They all load
and store data in a format independent of the platform. This means if you encrypt with Blowfish on a PPC it should decrypt
on an x86 with zero problems. The consistent API also means that if you learn how to use Blowfish with the library you
know how to use Safer+, RC6, or Serpent as well. With all of the core functions there are central descriptor tables
that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time. That means your
application can support all ciphers/hashes/prngs/bignum without changing the source code.
Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
configurable in terms of its build options. Out of the box the library will build with any modern version of GCC
without having to use configure scripts. This means that the library will work with platforms where development
tools may be limited (e.g. no autoconf).
On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
robustness and efficiency. LibTomCrypt traps and returns a series of errors ranging from invalid
arguments to buffer overflows/overruns. It is mostly thread safe and has been clocked on various platforms
with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
Crypto++.
\subsection{Modular}
The LibTomCrypt package has also been written to be very modular. The block ciphers, one--way hashes,
pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
are essentially structures with pointers to functions. While you can still call particular functions
directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
usage of the library.
For example, consider a hardware platform with a specialized RNG device. Obviously one would like to tap
that for the PRNG needs within the library (\textit{e.g. making a RSA key}). All the developer has to do
is write a descriptor and the few support routines required for the device. After that the rest of the
API can make use of it without change. Similarly imagine a few years down the road when AES2
(\textit{or whatever they call it}) has been invented. It can be added to the library and used within applications
with zero modifications to the end applications provided they are written properly.
This flexibility within the library means it can be used with any combination of primitive algorithms and
unlike libraries like OpenSSL is not tied to direct routines. For instance, in OpenSSL there are CBC block
mode routines for every single cipher. That means every time you add or remove a cipher from the library
you have to update the associated support code as well. In LibTomCrypt the associated code (\textit{chaining modes in this case})
are not directly tied to the ciphers. That is a new cipher can be added to the library by simply providing
the key setup, ECB decrypt and encrypt and test vector routines. After that all five chaining mode routines
can make use of the cipher right away.
\mysection{License}
The project is hereby released as public domain.
\mysection{Patent Disclosure}
The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice. To the best
of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}. The rest
of the ciphers and hashes are patent free or under patents that have since expired.
The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations. This means you can use
the ciphers you just can't advertise that you are doing so.
\mysection{Thanks}
I would like to give thanks to the following people (in no particular order) for helping me develop this project from
early on:
\begin{enumerate}
\item Richard van de Laarschot
\item Richard Heathfield
\item Ajay K. Agrawal
\item Brian Gladman
\item Svante Seleborg
\item Clay Culver
\item Jason Klapste
\item Dobes Vandermeer
\item Daniel Richards
\item Wayne Scott
\item Andrew Tyler
\item Sky Schulz
\item Christopher Imes
\end{enumerate}
There have been quite a few other people as well. Please check the change log to see who else has contributed from
time to time.
\chapter{The Application Programming Interface (API)}
\mysection{Introduction}
\index{CRYPT\_ERROR} \index{CRYPT\_OK}
In general the API is very simple to memorize and use. Most of the functions return either {\bf void} or {\bf int}. Functions
that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
if it failed. Certain functions that return int will return $-1$ to indicate an error. These functions will be explicitly
commented upon. When a function does return a CRYPT error code it can be translated into a string with
\index{error\_to\_string()}
\begin{verbatim}
const char *error_to_string(int err);
\end{verbatim}
An example of handling an error is:
\begin{small}
\begin{verbatim}
void somefunc(void)
{
int err;
/* call a cryptographic function */
if ((err = some_crypto_function(...)) != CRYPT_OK) {
printf("A crypto error occurred, %s\n", error_to_string(err));
/* perform error handling */
}
/* continue on if no error occurred */
}
\end{verbatim}
\end{small}
There is no initialization routine for the library and for the most part the code is thread safe. The only thread
related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads. Normally
that is not an issue.
To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
return 0;
}
\end{verbatim}
\end{small}
The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.
\mysection{Macros}
There are a few helper macros to make the coding process a bit easier. The first set are related to loading and storing
32/64-bit words in little/big endian format. The macros are:
\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
\newpage
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|}
\hline STORE32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
\hline STORE64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
\hline LOAD32L(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
\hline LOAD64L(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
\hline STORE32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
\hline STORE64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
\hline LOAD32H(x, y) & {\bf unsigned long} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
\hline LOAD64H(x, y) & {\bf unsigned long long} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
\hline BSWAP(x) & {\bf unsigned long} x & Swap bytes \\
\hline
\end{tabular}
\caption{Load And Store Macros}
\end{center}
\end{small}
\end{figure}
There are 32 and 64-bit cyclic rotations as well:
\index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|}
\hline ROL(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 31$ \\
\hline ROLc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 31$ \\
\hline ROR(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 31$ \\
\hline RORc(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 31$ \\
\hline && \\
\hline ROL64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x << y, 0 \le y \le 63$ \\
\hline ROL64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x << y, 0 \le y \le 63$ \\
\hline ROR64(x, y) & {\bf unsigned long} x, {\bf unsigned long} y & $x >> y, 0 \le y \le 63$ \\
\hline ROR64c(x, y) & {\bf unsigned long} x, {\bf const unsigned long} y & $x >> y, 0 \le y \le 63$ \\
\hline
\end{tabular}
\caption{Rotate Macros}
\end{center}
\end{small}
\end{figure}
\mysection{Functions with Variable Length Output}
Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length. To prevent buffer overflows you
must pass it the length of the buffer where the output will be stored. For example:
\index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
rsa_key key;
unsigned char buffer[1024];
unsigned long x;
int err;
/* ... Make up the RSA key somehow ... */
/* lets export the key, set x to the size of the
* output buffer */
x = sizeof(buffer);
if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
printf("Export error: %s\n", error_to_string(err));
return -1;
}
/* if rsa_export() was successful then x will have
* the size of the output */
printf("RSA exported key takes %d bytes\n", x);
/* ... do something with the buffer */
return 0;
}
\end{verbatim}
\end{small}
In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
indicating a buffer overflow would have occurred. If the function succeeds, it stores the length of the output back into
\textit{x} so that the calling application will know how many bytes were used.
As of v1.13, most functions will update your length on failure to indicate the size required by the function. Not all functions
support this so please check the source before you rely on it doing that.
\mysection{Functions that need a PRNG}
\index{Pseudo Random Number Generator} \index{PRNG}
Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG). These functions do not setup
the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.
Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example). The \textit{prng\_state} argument
may be passed as \textbf{NULL} in such situations.
\index{register\_prng()} \index{rsa\_make\_key()}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
rsa_key key;
int err;
/* register the system RNG */
register_prng(&sprng_desc)
/* make a 1024-bit RSA key with the system RNG */
if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key))
!= CRYPT_OK) {
printf("make_key error: %s\n", error_to_string(err));
return -1;
}
/* use the key ... */
return 0;
}
\end{verbatim}
\end{small}
\mysection{Functions that use Arrays of Octets}
Most functions require inputs that are arrays of the data type \textit{unsigned char}. Whether it is a symmetric key, IV
for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
lower eight bits contain data. For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
must pass in (a pointer to) an array of 32 \textit{unsigned char} variables. Certain routines (such as SAFER+) take
special care to work properly on platforms where an \textit{unsigned char} is not eight bits.
For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word. Typically an array of
type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}
\chapter{Symmetric Block Ciphers}
\mysection{Core Functions}
LibTomCrypt provides several block ciphers with an ECB block mode interface. It is important to first note that you
should never use the ECB modes directly to encrypt data. Instead you should use the ECB functions to make a chaining mode,
or use one of the provided chaining modes. All of the ciphers are written as ECB interfaces since it allows the rest of
the API to grow in a modular fashion.
\subsection{Key Scheduling}
All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}. This allows all ciphers to
have the same prototype and store their keys as naturally as possible. This also removes the need for dynamic memory
allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys. All ciphers must provide six visible
functions which are (given that XXX is the name of the cipher) the following:
\index{Cipher Setup}
\begin{verbatim}
int XXX_setup(const unsigned char *key,
int keylen,
int rounds,
symmetric_key *skey);
\end{verbatim}
The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
The number of rounds can be set to zero to use the default, which is generally a good idea.
If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it. It's important to note
that you should only used this scheduled key with the intended cipher. For example, if you call \textit{blowfish\_setup()} do not
pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}. All built--in setup functions do not allocate memory off the heap so
when you are done with a key you can simply discard it (e.g. they can be on the stack). However, to maintain proper coding
practices you should always call the respective XXX\_done() function. This allows for quicker porting to applications with
externally supplied plugins.
\subsection{ECB Encryption and Decryption}
To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
\index{Cipher Encrypt} \index{Cipher Decrypt}
\begin{verbatim}
int XXX_ecb_encrypt(const unsigned char *pt,
unsigned char *ct,
symmetric_key *skey);
int XXX_ecb_decrypt(const unsigned char *ct,
unsigned char *pt,
symmetric_key *skey);
\end{verbatim}
These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.). It is possible that the input and output buffer are
the same buffer. For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
\textit{ct}\footnote{ct stands for ciphertext.} is the output. For the decryption function it's the opposite. They both
return \textbf{CRYPT\_OK} on success. To test a particular cipher against test vectors\footnote{As published in their design papers.}
call the following self-test function.
\subsection{Self--Testing}
\index{Cipher Testing}
\begin{verbatim}
int XXX_test(void);
\end{verbatim}
This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
based upon.
\subsection{Key Sizing}
For each cipher there is a function which will help find a desired key size. It is specified as follows:
\index{Key Sizing}
\begin{verbatim}
int XXX_keysize(int *keysize);
\end{verbatim}
Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size. This function
will return {\bf CRYPT\_OK} if the key size specified is acceptable. For example:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
int keysize, err;
/* now given a 20 byte key what keysize does Twofish want to use? */
keysize = 20;
if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
printf("Error getting key size: %s\n", error_to_string(err));
return -1;
}
printf("Twofish suggested a key size of %d\n", keysize);
return 0;
}
\end{verbatim}
\end{small}
This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}
\subsection{Cipher Termination}
When you are finished with a cipher you can de--initialize it with the done function.
\begin{verbatim}
void XXX_done(symmetric_key *skey);
\end{verbatim}
For the software based ciphers within LibTomCrypt, these functions will not do anything. However, user supplied
cipher descriptors may require to be called for resource management purposes. To be compliant, all functions which call a cipher
setup function must also call the respective cipher done function when finished.
\subsection{Simple Encryption Demonstration}
An example snippet that encodes a block with Blowfish in ECB mode.
\index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
unsigned char pt[8], ct[8], key[8];
symmetric_key skey;
int err;
/* ... key is loaded appropriately in key ... */
/* ... load a block of plaintext in pt ... */
/* schedule the key */
if ((err = blowfish_setup(key, /* the key we will use */
8, /* key is 8 bytes (64-bits) long */
0, /* 0 == use default # of rounds */
&skey) /* where to put the scheduled key */
) != CRYPT_OK) {
printf("Setup error: %s\n", error_to_string(err));
return -1;
}
/* encrypt the block */
blowfish_ecb_encrypt(pt, /* encrypt this 8-byte array */
ct, /* store encrypted data here */
&skey); /* our previously scheduled key */
/* now ct holds the encrypted version of pt */
/* decrypt the block */
blowfish_ecb_decrypt(ct, /* decrypt this 8-byte array */
pt, /* store decrypted data here */
&skey); /* our previously scheduled key */
/* now we have decrypted ct to the original plaintext in pt */
/* Terminate the cipher context */
blowfish_done(&skey);
return 0;
}
\end{verbatim}
\end{small}
\mysection{Key Sizes and Number of Rounds}
\index{Symmetric Keys}
As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it. Only a few of the ciphers support smaller
keys (mainly for test vectors anyways). Ideally, your application should be making at least 256 bit keys. This is not
because you are to be paranoid. It is because if your PRNG has a bias of any sort the more bits the better. For
example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$. So if $\gamma$
were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
only 53 bits of entropy.
The number of rounds of most ciphers is not an option you can change. Only RC5 allows you to change the number of
rounds. By passing zero as the number of rounds all ciphers will use their default number of rounds. Generally the
ciphers are configured such that the default number of rounds provide adequate security for the given block and key
size.
\mysection{The Cipher Descriptors}
\index{Cipher Descriptor}
To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}. An element
of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):
\begin{small}
\begin{verbatim}
struct _cipher_descriptor {
/** name of cipher */
char *name;
/** internal ID */
unsigned char ID;
/** min keysize (octets) */
int min_key_length,
/** max keysize (octets) */
max_key_length,
/** block size (octets) */
block_length,
/** default number of rounds */
default_rounds;
...<snip>...
};
\end{verbatim}
\end{small}
Where \textit{name} is the lower case ASCII version of the name. The fields \textit{min\_key\_length} and \textit{max\_key\_length}
are the minimum and maximum key sizes in bytes. The \textit{block\_length} member is the block size of the cipher
in bytes. As a good rule of thumb it is assumed that the cipher supports
the min and max key lengths but not always everything in between. The \textit{default\_rounds} field is the default number
of rounds that will be used.
For a plugin to be compliant it must provide at least each function listed before the accelerators begin. Accelerators are optional,
and if missing will be emulated in software.
The remaining fields are all pointers to the core functions for each cipher. The end of the cipher\_descriptor array is
marked when \textit{name} equals {\bf NULL}.
As of this release the current cipher\_descriptors elements are the following:
\vfil
\index{Cipher descriptor table}
\index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
\index{des\_desc} \index{des3\_desc} \index{noekeon\_desc} \index{skipjack\_desc} \index{anubis\_desc} \index{khazad\_desc} \index{kseed\_desc} \index{kasumi\_desc}
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|c|c|c|}
\hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} \\
\hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
\hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
\hline RC2 & rc2\_desc & 8 & 8 $\ldots$ 128 & 16 \\
\hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
\hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
\hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
\hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
& aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
\hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
\hline DES & des\_desc & 8 & 8 & 16 \\
\hline 3DES (EDE mode) & des3\_desc & 8 & 16, 24 & 16 \\
\hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
\hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
\hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
\hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
\hline Khazad & khazad\_desc & 8 & 16 & 8 \\
\hline SEED & kseed\_desc & 16 & 16 & 16 \\
\hline KASUMI & kasumi\_desc & 8 & 16 & 8 \\
\hline
\end{tabular}
\end{center}
\end{small}
\caption{Built--In Software Ciphers}
\end{figure}
\subsection{Notes}
\begin{small}
\begin{enumerate}
\item
For AES, (also known as Rijndael) there are four descriptors which complicate issues a little. The descriptors
rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}. The descriptors aes\_desc and
aes\_enc\_desc provide the cipher name \textit{aes}. Functionally both \textit{rijndael} and \textit{aes} are the same cipher. The
only difference is when you call find\_cipher() you have to pass the correct name. The cipher descriptors with \textit{enc}
in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
and tables. The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
should not be called.
The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher. Algorithms such
as EAX, PMAC and OMAC only require the encryption function. So far this \textit{encrypt only} functionality has only been implemented for
Rijndael as it makes the most sense for this cipher.
\item
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
fact used for the purposes of encryption. My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
byte string from the real 7/21 byte key.
\item
Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time. These options are found in
the file \textit{tomcrypt\_cfg.h}. The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes. This means that a scheduled
key will require less ram but the resulting cipher will be slower. The second option is \textit{TWOFISH\_TABLES} which when
defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
by the polynomials 5B and EF used in the MDS multiplication. As a result the code is faster and slightly larger. The
speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
Twofish round function.
\begin{figure}[hpbt]
\index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
\begin{small}
\begin{center}
\begin{tabular}{|l|l|l|}
\hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
\hline undefined & undefined & Very fast, 4.2KB of ram. \\
\hline undefined & defined & Faster key setup, larger code. \\
\hline defined & undefined & Very slow, 0.2KB of ram. \\
\hline defined & defined & Faster, 0.2KB of ram, larger code. \\
\hline
\end{tabular}
\end{center}
\end{small}
\caption{Twofish Build Options}
\label{fig:twofishopts}
\end{figure}
\end{enumerate}
\end{small}
To work with the cipher\_descriptor array there is a function:
\index{find\_cipher()}
\begin{verbatim}
int find_cipher(char *name)
\end{verbatim}
Which will search for a given name in the array. It returns $-1$ if the cipher is not found, otherwise it returns
the location in the array where the cipher was found. For example, to indirectly setup Blowfish you can also use:
\begin{small}
\index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
unsigned char key[8];
symmetric_key skey;
int err;
/* you must register a cipher before you use it */
if (register_cipher(&blowfish_desc)) == -1) {
printf("Unable to register Blowfish cipher.");
return -1;
}
/* generic call to function (assuming the key
* in key[] was already setup) */
if ((err =
cipher_descriptor[find_cipher("blowfish")].
setup(key, 8, 0, &skey)) != CRYPT_OK) {
printf("Error setting up Blowfish: %s\n", error_to_string(err));
return -1;
}
/* ... use cipher ... */
}
\end{verbatim}
\end{small}
A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function. In order
to use a cipher with the descriptor table you must register it first using:
\index{register\_cipher()}
\begin{verbatim}
int register_cipher(const struct _cipher_descriptor *cipher);
\end{verbatim}
Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs such
as there is no more room (it can have 32 ciphers at most) it will return {\bf{-1}}. If you try to add the same cipher more
than once it will just return the index of the first copy. To remove a cipher call:
\index{unregister\_cipher()}
\begin{verbatim}
int unregister_cipher(const struct _cipher_descriptor *cipher);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
int err;
/* register the cipher */
if (register_cipher(&rijndael_desc) == -1) {
printf("Error registering Rijndael\n");
return -1;
}
/* use Rijndael */
/* remove it */
if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
printf("Error removing Rijndael: %s\n", error_to_string(err));
return -1;
}
return 0;
}
\end{verbatim}
\end{small}
This snippet is a small program that registers Rijndael.
\mysection{Symmetric Modes of Operations}
\subsection{Background}
A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
size of the cipher. Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
$P$ under the key $k$ as $E_k(P)$. In some modes there exists an initial vector denoted as $C_{-1}$.
\subsubsection{ECB Mode}
\index{ECB mode}
ECB or Electronic Codebook Mode is the simplest method to use. It is given as:
\begin{equation}
C_i = E_k(P_i)
\end{equation}
This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
than once.
\subsubsection{CBC Mode}
\index{CBC mode}
CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
It is given as:
\begin{equation}
C_i = E_k(P_i \oplus C_{i - 1})
\end{equation}
It is important that the initial vector be unique and preferably random for each message encrypted under the same key.
\subsubsection{CTR Mode}
\index{CTR mode}
CTR or Counter Mode is a mode which only uses the encryption function of the cipher. Given a initial vector which is
treated as a large binary counter the CTR mode is given as:
\begin{eqnarray}
C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
C_i = P_i \oplus E_k(C_{-1})
\end{eqnarray}
Where $W$ is the size of a block in bits (e.g. 64 for Blowfish). As long as the initial vector is random for each message
encrypted under the same key replay and swap attacks are infeasible. CTR mode may look simple but it is as secure
as the block cipher is under a chosen plaintext attack (provided the initial vector is unique).
\subsubsection{CFB Mode}
\index{CFB mode}
CFB or Ciphertext Feedback Mode is a mode akin to CBC. It is given as:
\begin{eqnarray}
C_i = P_i \oplus C_{-1} \nonumber \\
C_{-1} = E_k(C_i)
\end{eqnarray}
Note that in this library the output feedback width is equal to the size of the block cipher. That is this mode is used
to encrypt whole blocks at a time. However, the library will buffer data allowing the user to encrypt or decrypt partial
blocks without a delay. When this mode is first setup it will initially encrypt the initial vector as required.
\subsubsection{OFB Mode}
\index{OFB mode}
OFB or Output Feedback Mode is a mode akin to CBC as well. It is given as:
\begin{eqnarray}
C_{-1} = E_k(C_{-1}) \nonumber \\
C_i = P_i \oplus C_{-1}
\end{eqnarray}
Like the CFB mode the output width in CFB mode is the same as the width of the block cipher. OFB mode will also
buffer the output which will allow you to encrypt or decrypt partial blocks without delay.
\subsection{Choice of Mode}
My personal preference is for the CTR mode since it has several key benefits:
\begin{enumerate}
\item No short cycles which is possible in the OFB and CFB modes.
\item Provably as secure as the block cipher being used under a chosen plaintext attack.
\item Technically does not require the decryption routine of the cipher.
\item Allows random access to the plaintext.
\item Allows the encryption of block sizes that are not equal to the size of the block cipher.
\end{enumerate}
The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size. They
accomplish this by buffering the data required to complete a block. This allows you to encrypt or decrypt any size
block of memory with either of the three modes.
The ECB and CBC modes process blocks of the same size as the cipher at a time. Therefore, they are less flexible than the
other modes.
\subsection{Ciphertext Stealing}
\index{Ciphertext stealing}
Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length. This is accomplished
by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext. LibTomCrypt does not
support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.
The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.
\subsection{Initialization}
\index{CBC Mode} \index{CTR Mode}
\index{OFB Mode} \index{CFB Mode}
The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages. Assuming the mode
you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
use that mode. They have identical setup routines (except CTR and ECB mode):
\index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
\begin{verbatim}
int XXX_start( int cipher,
const unsigned char *IV,
const unsigned char *key,
int keylen,
int num_rounds,
symmetric_XXX *XXX);
int ctr_start( int cipher,
const unsigned char *IV,
const unsigned char *key,
int keylen,
int num_rounds,
int ctr_mode,
symmetric_CTR *ctr);
int ecb_start( int cipher,
const unsigned char *key,
int keylen,
int num_rounds,
symmetric_ECB *ecb);
\end{verbatim}
In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use. The \textit{IV} value is
the initialization vector to be used with the cipher. You must fill the IV yourself and it is assumed they are the same
length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
of the cipher you choose. It is important that the IV be random for each unique message you want to encrypt. The
parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call. The final parameter
is a pointer to the structure you want to hold the information for the mode of operation.
The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.
\subsubsection{CTR Mode}
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.
If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value. Otherwise, if
\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value. As of v1.15 the RFC 3686 style of
increment then encrypt is also supported. By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
the counter before encrypting it for the first time.
As of V1.17, the library supports variable length counters for CTR mode. The (optional) counter length is specified by OR'ing the octet
length of the counter against the \textit{ctr\_mode} parameter. The default, zero, indicates that a full block length counter will be used. This also
ensures backwards compatibility with software that uses older versions of the library.
\begin{small}
\begin{verbatim}
symmetric_CTR ctr;
int err;
unsigned char IV[16], key[16];
/* use a 32-bit little endian counter */
if ((err = ctr_start(find_cipher("aes"),
IV, key, 16, 0,
CTR_COUNTER_LITTLE_ENDIAN | 4,
&ctr)) != CRYPT_OK) {
handle_error(err);
}
\end{verbatim}
\end{small}
Changing the counter size has little (really no) effect on the performance of the CTR chaining mode. It is provided for compatibility
with other software (and hardware) which have smaller fixed sized counters.
\subsection{Encryption and Decryption}
To actually encrypt or decrypt the following routines are provided:
\index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
\index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
\begin{verbatim}
int XXX_encrypt(const unsigned char *pt,
unsigned char *ct,
unsigned long len,
symmetric_YYY *YYY);
int XXX_decrypt(const unsigned char *ct,
unsigned char *pt,
unsigned long len,
symmetric_YYY *YYY);
\end{verbatim}
Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.
In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt. The CTR, OFB and CFB modes are order sensitive but not
chunk sensitive. That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
and end up with the same ciphertext. However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts. All
five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.
In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size. In the CBC case, you must manually pad the end of your message (either with
zeroes or with whatever your protocol requires).
To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.
\subsection{IV Manipulation}
To change or read the IV of a previously initialized chaining mode use the following two functions.
\index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
\index{ctr\_setiv()} \index{ctr\_getiv()}
\begin{verbatim}
int XXX_getiv(unsigned char *IV,
unsigned long *len,
symmetric_XXX *XXX);
int XXX_setiv(const unsigned char *IV,
unsigned long len,
symmetric_XXX *XXX);
\end{verbatim}
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
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
of the IV passed in must be the size of the ciphers block size.
The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.
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
were the last ciphertext block. In CFB mode, the IV is encrypted as if it were the prior encrypted pad. In CTR mode, the IV is encrypted without
first incrementing it (regardless of the LTC\_RFC\_3686 flag presence). In F8 mode, the IV is encrypted and becomes the new pad. It does not change
the salted IV, and is only meant to allow seeking within a session. In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
seeking within the session. In OFB mode, the IV is encrypted and becomes the new pad.
\subsection{Stream Termination}
To terminate an open stream call the done function.
\index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
\begin{verbatim}
int XXX_done(symmetric_XXX *XXX);
\end{verbatim}
This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.
\newpage
\subsection{Examples}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
unsigned char key[16], IV[16], buffer[512];
symmetric_CTR ctr;
int x, err;
/* register twofish first */
if (register_cipher(&twofish_desc) == -1) {
printf("Error registering cipher.\n");
return -1;
}
/* somehow fill out key and IV */
/* start up CTR mode */
if ((err = ctr_start(
find_cipher("twofish"), /* index of desired cipher */
IV, /* the initial vector */
key, /* the secret key */