Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

added libtommath-0.28

  • Loading branch information...
commit 455bb4db20b0ac195325b8103a25e723a7270bb9 1 parent c343371
authored December 24, 2003 sjaeckel committed July 15, 2010

Showing 83 changed files with 40,210 additions and 1,362 deletions. Show diff stats Hide diff stats

  1. 6  bn.ilg
  2. 56  bn.ind
  3. BIN  bn.pdf
  4. 1,998  bn.tex
  5. 7  bn_fast_mp_invmod.c
  6. 26  bn_fast_mp_montgomery_reduce.c
  7. 16  bn_fast_s_mp_sqr.c
  8. 3  bn_mp_add.c
  9. 2  bn_mp_clear.c
  10. 3  bn_mp_cmp_d.c
  11. 3  bn_mp_cmp_mag.c
  12. 3  bn_mp_div.c
  13. 3  bn_mp_div_2.c
  14. 3  bn_mp_div_2d.c
  15. 2  bn_mp_div_d.c
  16. 2  bn_mp_exch.c
  17. 3  bn_mp_expt_d.c
  18. 3  bn_mp_exptmod.c
  19. 8  bn_mp_fwrite.c
  20. 3  bn_mp_gcd.c
  21. 6  bn_mp_grow.c
  22. 5  bn_mp_init.c
  23. 3  bn_mp_init_copy.c
  24. 5  bn_mp_init_size.c
  25. 3  bn_mp_invmod.c
  26. 3  bn_mp_jacobi.c
  27. 3  bn_mp_lcm.c
  28. 3  bn_mp_lshd.c
  29. 8  bn_mp_montgomery_reduce.c
  30. 3  bn_mp_mul.c
  31. 3  bn_mp_mul_2.c
  32. 3  bn_mp_mul_2d.c
  33. 1  bn_mp_mulmod.c
  34. 3  bn_mp_n_root.c
  35. 3  bn_mp_neg.c
  36. 3  bn_mp_or.c
  37. 7  bn_mp_prime_fermat.c
  38. 7  bn_mp_prime_is_divisible.c
  39. 11  bn_mp_prime_is_prime.c
  40. 7  bn_mp_prime_miller_rabin.c
  41. 4  bn_mp_prime_next_prime.c
  42. 74  bn_mp_prime_random.c
  43. 10  bn_mp_radix_size.c
  44. 17  bn_mp_reduce_is_2k.c
  45. 3  bn_mp_rshd.c
  46. 3  bn_mp_set.c
  47. 3  bn_mp_set_int.c
  48. 7  bn_mp_shrink.c
  49. 12  bn_mp_toradix.c
  50. 69  bn_prime_sizes_tab.c
  51. 14  bn_s_mp_sqr.c
  52. 21  changes.txt
  53. 39  demo/demo.c
  54. 2  etc/2kprime.1
  55. 9  etc/drprimes.txt
  56. 5  etc/makefile
  57. 32  logs/add.log
  58. 7  logs/expt.log
  59. 6  logs/expt_2k.log
  60. 7  logs/expt_dr.log
  61. 34  logs/mult.log
  62. 34  logs/sqr.log
  63. 17  logs/sqr.old
  64. 34  logs/sqr_kara.log
  65. 32  logs/sub.log
  66. 38  makefile
  67. 2  makefile.bcc
  68. 47  makefile.cygwin_dll
  69. 4  makefile.msvc
  70. 23  mtest/test.c~
  71. BIN  pics/design_process.tif
  72. BIN  pics/expt_state.tif
  73. BIN  pics/primality.tif
  74. BIN  pics/radix.sxd
  75. BIN  pics/sliding_window.tif
  76. BIN  poster.pdf
  77. 1  poster.tex
  78. 404  pre_gen/mpi.c
  79. 53  tommath.h
  80. 139  tommath.out
  81. 21,175  tommath.pdf
  82. 6,268  tommath.src
  83. 10,683  tommath.tex
6  bn.ilg
... ...
@@ -0,0 +1,6 @@
  1
+This is makeindex, version 2.14 [02-Oct-2002] (kpathsea + Thai support).
  2
+Scanning input file bn.idx....done (53 entries accepted, 0 rejected).
  3
+Sorting entries....done (317 comparisons).
  4
+Generating output file bn.ind....done (56 lines written, 0 warnings).
  5
+Output written in bn.ind.
  6
+Transcript written in bn.ilg.
56  bn.ind
... ...
@@ -0,0 +1,56 @@
  1
+\begin{theindex}
  2
+
  3
+  \item mp\_add, \hyperpage{23}
  4
+  \item mp\_and, \hyperpage{23}
  5
+  \item mp\_clear, \hyperpage{7}
  6
+  \item mp\_clear\_multi, \hyperpage{8}
  7
+  \item mp\_cmp, \hyperpage{18}
  8
+  \item mp\_cmp\_d, \hyperpage{20}
  9
+  \item mp\_cmp\_mag, \hyperpage{17}
  10
+  \item mp\_div, \hyperpage{29}
  11
+  \item mp\_div\_2, \hyperpage{21}
  12
+  \item mp\_div\_2d, \hyperpage{22}
  13
+  \item MP\_EQ, \hyperpage{17}
  14
+  \item mp\_error\_to\_string, \hyperpage{6}
  15
+  \item mp\_expt\_d, \hyperpage{31}
  16
+  \item mp\_exptmod, \hyperpage{31}
  17
+  \item mp\_gcd, \hyperpage{39}
  18
+  \item mp\_grow, \hyperpage{12}
  19
+  \item MP\_GT, \hyperpage{17}
  20
+  \item mp\_init, \hyperpage{7}
  21
+  \item mp\_init\_copy, \hyperpage{9}
  22
+  \item mp\_init\_multi, \hyperpage{8}
  23
+  \item mp\_init\_size, \hyperpage{10}
  24
+  \item mp\_int, \hyperpage{6}
  25
+  \item mp\_invmod, \hyperpage{40}
  26
+  \item mp\_jacobi, \hyperpage{39}
  27
+  \item mp\_lcm, \hyperpage{39}
  28
+  \item mp\_lshd, \hyperpage{23}
  29
+  \item MP\_LT, \hyperpage{17}
  30
+  \item MP\_MEM, \hyperpage{5}
  31
+  \item mp\_mul, \hyperpage{25}
  32
+  \item mp\_mul\_2, \hyperpage{21}
  33
+  \item mp\_mul\_2d, \hyperpage{22}
  34
+  \item mp\_n\_root, \hyperpage{31}
  35
+  \item mp\_neg, \hyperpage{24}
  36
+  \item MP\_NO, \hyperpage{5}
  37
+  \item MP\_OKAY, \hyperpage{5}
  38
+  \item mp\_or, \hyperpage{23}
  39
+  \item mp\_prime\_fermat, \hyperpage{33}
  40
+  \item mp\_prime\_is\_divisible, \hyperpage{33}
  41
+  \item mp\_prime\_is\_prime, \hyperpage{34}
  42
+  \item mp\_prime\_miller\_rabin, \hyperpage{33}
  43
+  \item mp\_prime\_next\_prime, \hyperpage{34}
  44
+  \item mp\_prime\_rabin\_miller\_trials, \hyperpage{34}
  45
+  \item mp\_prime\_random, \hyperpage{35}
  46
+  \item mp\_rshd, \hyperpage{23}
  47
+  \item mp\_set, \hyperpage{15}
  48
+  \item mp\_set\_int, \hyperpage{16}
  49
+  \item mp\_shrink, \hyperpage{11}
  50
+  \item mp\_sqr, \hyperpage{25}
  51
+  \item mp\_sub, \hyperpage{23}
  52
+  \item MP\_VAL, \hyperpage{5}
  53
+  \item mp\_xor, \hyperpage{23}
  54
+  \item MP\_YES, \hyperpage{5}
  55
+
  56
+\end{theindex}
BIN  bn.pdf
Binary file not shown
1,998  bn.tex
... ...
@@ -1,1063 +1,1219 @@
1  
-\documentclass[]{article}
  1
+\documentclass[b5paper]{book}
  2
+\usepackage{hyperref}
  3
+\usepackage{makeidx}
  4
+\usepackage{amssymb}
  5
+\usepackage{color}
  6
+\usepackage{alltt}
  7
+\usepackage{graphicx}
  8
+\usepackage{layout}
  9
+\def\union{\cup}
  10
+\def\intersect{\cap}
  11
+\def\getsrandom{\stackrel{\rm R}{\gets}}
  12
+\def\cross{\times}
  13
+\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
  14
+\def\catn{$\|$}
  15
+\def\divides{\hspace{0.3em} | \hspace{0.3em}}
  16
+\def\nequiv{\not\equiv}
  17
+\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
  18
+\def\lcm{{\rm lcm}}
  19
+\def\gcd{{\rm gcd}}
  20
+\def\log{{\rm log}}
  21
+\def\ord{{\rm ord}}
  22
+\def\abs{{\mathit abs}}
  23
+\def\rep{{\mathit rep}}
  24
+\def\mod{{\mathit\ mod\ }}
  25
+\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
  26
+\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
  27
+\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
  28
+\def\Or{{\rm\ or\ }}
  29
+\def\And{{\rm\ and\ }}
  30
+\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
  31
+\def\implies{\Rightarrow}
  32
+\def\undefined{{\rm ``undefined"}}
  33
+\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
  34
+\let\oldphi\phi
  35
+\def\phi{\varphi}
  36
+\def\Pr{{\rm Pr}}
  37
+\newcommand{\str}[1]{{\mathbf{#1}}}
  38
+\def\F{{\mathbb F}}
  39
+\def\N{{\mathbb N}}
  40
+\def\Z{{\mathbb Z}}
  41
+\def\R{{\mathbb R}}
  42
+\def\C{{\mathbb C}}
  43
+\def\Q{{\mathbb Q}}
  44
+\definecolor{DGray}{gray}{0.5}
  45
+\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
  46
+\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
  47
+\def\gap{\vspace{0.5ex}}
  48
+\makeindex
2 49
 \begin{document}
3  
-
4  
-\title{LibTomMath v0.27 \\ A Free Multiple Precision Integer Library \\ http://math.libtomcrypt.org }
  50
+\frontmatter
  51
+\pagestyle{empty}
  52
+\title{LibTomMath User Manual \\ v0.28}
5 53
 \author{Tom St Denis \\ tomstdenis@iahu.ca}
6 54
 \maketitle
7  
-\newpage
8  
-
9  
-\section{Introduction}
10  
-``LibTomMath'' is a free and open source library that provides multiple-precision integer functions required to form a 
11  
-basis of a public key cryptosystem.  LibTomMath is written entire in portable ISO C source code and designed to have an 
12  
-application interface much like that of MPI from Michael Fromberger.  
13  
-
14  
-LibTomMath was written from scratch by Tom St Denis but designed to be  drop in replacement for the MPI package.  The 
15  
-algorithms within the library are derived from descriptions as provided in the Handbook of Applied Cryptography and Knuth's
16  
-``The Art of Computer Programming''.  The library has been extensively optimized and should provide quite comparable 
17  
-timings as compared to many free and commercial libraries.
18  
-
19  
-LibTomMath was designed with the following goals in mind:
20  
-\begin{enumerate}
21  
-\item Be a drop in replacement for MPI.
22  
-\item Be much faster than MPI.
23  
-\item Be written entirely in portable C.
24  
-\end{enumerate}
25  
-
26  
-All three goals have been achieved to one extent or another (actual figures depend on what platform you are using).
27  
-
28  
-Being compatible with MPI means that applications that already use it can be ported fairly quickly.  Currently there are 
29  
-a few differences but there are many similarities.  In fact the average MPI based application can be ported in under 15
30  
-minutes.  
31  
-
32  
-Thanks goes to Michael Fromberger for answering a couple questions and Colin Percival for having the patience and courtesy to
33  
-help debug and suggest optimizations.  They were both of great help!
34  
-
35  
-\section{Building Against LibTomMath}
36  
-
37  
-As of v0.12 LibTomMath is not a simple single source file project like MPI.  LibTomMath retains the exact same API as MPI
38  
-but is implemented differently.  To build LibTomMath you will need a copy of GNU cc and GNU make.  Both are free so if you 
39  
-don't have a copy don't whine to me about it.
40  
-
41  
-To build the library type 
42  
-
43  
-\begin{verbatim}
44  
-make
45  
-\end{verbatim}
46  
-
47  
-This will build the library file libtommath.a.  If you want to build the library and also install it (in /usr/bin and /usr/include) then
48  
-type 
49  
-
50  
-\begin{verbatim}
51  
-make install
52  
-\end{verbatim}
53  
-
54  
-Now within your application include ``tommath.h'' and link against libtommath.a to get MPI-like functionality.
55  
-
56  
-\subsection{Microsoft Visual C++}
57  
-A makefile is also provided for MSVC (\textit{tested against MSVC 6.00 with SP5}) which allows the library to be used
58  
-with that compiler as well.  To build the library type
59  
-
60  
-\begin{verbatim}
61  
-nmake -f makefile.msvc
62  
-\end{verbatim}
63  
-
64  
-Which will build ``tommath.lib''.  
65  
-
66  
-\section{Programming with LibTomMath}
67  
-
68  
-\subsection{The mp\_int Structure}
69  
-All multiple precision integers are stored in a structure called \textbf{mp\_int}.  A multiple precision integer is
70  
-essentially an array of \textbf{mp\_digit}.  mp\_digit is defined at the top of ``tommath.h''.  The type can be changed 
71  
-to suit a particular platform.  
72  
-
73  
-For example, when \textbf{MP\_8BIT} is defined a mp\_digit is a unsigned char and holds seven bits.  Similarly 
74  
-when \textbf{MP\_16BIT} is defined a mp\_digit is a unsigned short and holds 15 bits.   By default a mp\_digit is a 
75  
-unsigned long and holds 28 bits which is optimal for most 32 and 64 bit processors.
76  
-
77  
-The choice of digit is particular to the platform at hand and what available multipliers are provided.  For 
78  
-MP\_8BIT either a $8 \times 8 \Rightarrow 16$ or $16 \times 16 \Rightarrow 16$ multiplier is optimal.  When 
79  
-MP\_16BIT is defined either a $16 \times 16 \Rightarrow 32$ or $32 \times 32 \Rightarrow 32$ multiplier is optimal.  By
80  
-default a $32 \times 32 \Rightarrow 64$ or $64 \times 64 \Rightarrow 64$ multiplier is optimal.  
81  
-
82  
-This gives the library some flexibility.  For example, a i8051 has a $8 \times 8 \Rightarrow 16$ multiplier.  The 
83  
-16-bit x86 instruction set has a $16 \times 16 \Rightarrow 32$ multiplier.  In practice this library is not particularly
84  
-designed for small devices like an i8051 due to the size.  It is possible to strip out functions which are not required 
85  
-to drop the code size.  More realistically the library is well suited to 32 and 64-bit processors that have decent
86  
-integer multipliers.  The AMD Athlon XP and Intel Pentium 4 processors are examples of well suited processors.
87  
-
88  
-Throughout the discussions there will be references to a \textbf{used} and \textbf{alloc} members of an integer.  The
89  
-used member refers to how many digits are actually used in the representation of the integer.  The alloc member refers
90  
-to how many digits have been allocated off the heap.  There is also the $\beta$ quantity which is equal to $2^W$ where 
91  
-$W$ is the number of bits in a digit (default is 28).  
92  
-
93  
-\subsection{Calling Functions}
94  
-Most functions expect pointers to mp\_int's as parameters.   To save on memory usage it is possible to have source
95  
-variables as destinations.  The arguements are read left to right so to compute $x + y = z$ you would pass the arguments
96  
-in the order $x, y, z$.  For example:
97  
-\begin{verbatim}
98  
-   mp_add(&x, &y, &x);           /* x = x + y */
99  
-   mp_mul(&y, &x, &z);           /* z = y * x */
100  
-   mp_div_2(&x, &y);             /* y = x / 2 */
101  
-\end{verbatim}
102  
-
103  
-\subsection{Various Optimizations}
104  
-Various routines come in several ``flavours'' which are optimized for particular cases of inputs.  For instance
105  
-the multiplicative inverse function ``mp\_invmod()'' has a routine for odd and even moduli.  Similarly the
106  
-``mp\_exptmod()'' function has several variants depending on the modulus as well.  Several lower level
107  
-functions such as multiplication, squaring and reductions come in ``comba'' and ``baseline'' variants.
108  
-
109  
-The design of LibTomMath is such that the end user does not have to concern themselves too much with these
110  
-details.  This is why the functions provided will determine \textit{automatically} when an appropriate
111  
-optimal function can be used.  For example, when you call ``mp\_mul()'' the routines will first determine
112  
-if the Karatsuba multiplier should be used.  If not it will determine if the ``comba'' method can be used
113  
-and finally call the standard catch-all ``baseline'' method.
114  
-
115  
-Throughout the rest of this manual several variants for various functions will be referenced to as
116  
-the ``comba'', ``baseline'', etc... method.  Keep in mind you call one function to use any of the optimal
117  
-variants.
118  
-
119  
-\subsection{Return Values}
120  
-All functions that return errors will return \textbf{MP\_OKAY} if the function was succesful.  It will return 
121  
-\textbf{MP\_MEM} if it ran out of heap memory or \textbf{MP\_VAL} if one of the arguements is out of range.  
122  
-
123  
-\subsection{Basic Functionality}
124  
-Before an mp\_int can be used it must be initialized with 
125  
-
126  
-\begin{verbatim}
127  
-int mp_init(mp_int *a);
128  
-\end{verbatim}
129  
-
130  
-For example, consider the following.
131  
-
132  
-\begin{verbatim}
133  
-#include "tommath.h"
134  
-int main(void)
135  
-{
136  
-   mp_int num;
137  
-   if (mp_init(&num) != MP_OKAY) {
138  
-      printf("Error initializing a mp_int.\n");
139  
-   }
140  
-   return 0;
141  
-}   
142  
-\end{verbatim}
143  
-
144  
-A mp\_int can be freed from memory with
145  
-
146  
-\begin{verbatim}
147  
-void mp_clear(mp_int *a);
148  
-\end{verbatim}
149  
-
150  
-This will zero the memory and free the allocated data.  There are a set of trivial functions to manipulate the 
151  
-value of an mp\_int.  
152  
-
153  
-\begin{verbatim}
154  
-/* set to zero */
155  
-void mp_zero(mp_int *a);
  55
+This text, the library and the accompanying textbook are all hereby placed in the public domain.  This book has been 
  56
+formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package.
156 57
 
157  
-/* set to a digit */
158  
-void mp_set(mp_int *a, mp_digit b);
  58
+\vspace{10cm}
159 59
 
160  
-/* set a 32-bit const */
161  
-int mp_set_int(mp_int *a, unsigned long b);
  60
+\begin{flushright}Open Source.  Open Academia.  Open Minds.
162 61
 
163  
-/* init to a given number of digits */
164  
-int mp_init_size(mp_int *a, int size);
  62
+\mbox{ }
165 63
 
166  
-/* copy, b = a */
167  
-int mp_copy(mp_int *a, mp_int *b);
  64
+Tom St Denis,
168 65
 
169  
-/* inits and copies, a = b */
170  
-int mp_init_copy(mp_int *a, mp_int *b);
171  
-\end{verbatim}
  66
+Ontario, Canada
  67
+\end{flushright}
172 68
 
173  
-The \textbf{mp\_zero} function will clear the contents of a mp\_int and set it to positive.  The \textbf{mp\_set} function 
174  
-will zero the integer and set the first digit to a value specified.  The \textbf{mp\_set\_int} function will zero the 
175  
-integer and set the first 32-bits to a given value.  It is important to note that using mp\_set can have unintended 
176  
-side effects when either the  MP\_8BIT or MP\_16BIT defines are enabled.  By default the library will accept the 
177  
-ranges of values MPI will (and more).
  69
+\tableofcontents
  70
+\listoffigures
  71
+\mainmatter
  72
+\pagestyle{headings}
  73
+\chapter{Introduction}
  74
+\section{What is LibTomMath?}
  75
+LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
  76
+large integer numbers.  It was written in portable ISO C source code so that it will build on any platform with a conforming
  77
+C compiler.  
178 78
 
179  
-The \textbf{mp\_init\_size} function will initialize the integer and set the allocated size to a given value.  The 
180  
-allocated digits are zero'ed by default but not marked as used.  The \textbf{mp\_copy} function will copy the digits
181  
-(and sign) of the first parameter into the integer specified by the second parameter.  The \textbf{mp\_init\_copy} will
182  
-initialize the first integer specified and copy the second one into it.  Note that the order is reversed from that of
183  
-mp\_copy.  This odd ``bug'' was kept to maintain compatibility with MPI.
  79
+In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
  80
+to implement ``bignum'' math.  However, the resulting code has proven to be very useful.  It has been used by numerous 
  81
+universities, commercial and open source software developers.  It has been used on a variety of platforms ranging from
  82
+Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.  
184 83
 
185  
-\subsection{Digit Manipulations}
  84
+\section{License}
  85
+As of the v0.25 the library source code has been placed in the public domain with every new release.  As of the v0.28
  86
+release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
  87
+release as well.  This textbook is meant to compliment the project by providing a more solid walkthrough of the development
  88
+algorithms used in the library.
186 89
 
187  
-There are a class of functions that provide simple digit manipulations such as shifting and modulo reduction of powers
188  
-of two.  
  90
+Since both\footnote{Note that the MPI files under mtest/ are copyrighted by Michael Fromberger.} are in the 
  91
+public domain everyone is entitled to do with them as they see fit.
189 92
 
190  
-\begin{verbatim}
191  
-/* right shift by "b" digits */
192  
-void mp_rshd(mp_int *a, int b);
  93
+\section{Building LibTomMath}
193 94
 
194  
-/* left shift by "b" digits */
195  
-int mp_lshd(mp_int *a, int b);
  95
+LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC.  However, the library will
  96
+also build in MSVC, Borland C out of the box.  For any other ISO C compiler a makefile will have to be made by the end
  97
+developer.  
196 98
 
197  
-/* c = a / 2^b */
198  
-int mp_div_2d(mp_int *a, int b, mp_int *c);
  99
+To build the library for GCC simply issue the 
199 100
 
200  
-/* b = a/2 */
201  
-int mp_div_2(mp_int *a, mp_int *b);
202  
-
203  
-/* c = a * 2^b */
204  
-int mp_mul_2d(mp_int *a, int b, mp_int *c);
205  
-
206  
-/* b = a*2 */
207  
-int mp_mul_2(mp_int *a, mp_int *b);
208  
-
209  
-/* c = a mod 2^d */
210  
-int mp_mod_2d(mp_int *a, int b, mp_int *c);
211  
-
212  
-/* computes a = 2^b */
213  
-int mp_2expt(mp_int *a, int b);
214  
-
215  
-/* makes a pseudo-random int of a given size */
216  
-int mp_rand(mp_int *a, int digits);
217  
-
218  
-\end{verbatim}
219  
-
220  
-\subsection{Binary Operations}
  101
+\begin{alltt}
  102
+make
  103
+\end{alltt}
221 104
 
222  
-\begin{verbatim}
  105
+command.  This will build the library and archive the object files in ``libtommath.a''.  Now you simply link against that
  106
+and include ``tommath.h'' within your programs.  
223 107
 
224  
-/* c = a XOR b  */
225  
-int mp_xor(mp_int *a, mp_int *b, mp_int *c);
  108
+Alternatively to build with MSVC type
226 109
 
227  
-/* c = a OR b */
228  
-int mp_or(mp_int *a, mp_int *b, mp_int *c);
  110
+\begin{alltt}
  111
+nmake -f makefile.msvc
  112
+\end{alltt}
229 113
 
230  
-/* c = a AND b */
231  
-int mp_and(mp_int *a, mp_int *b, mp_int *c);
  114
+This will build the library and archive the object files in ``tommath.lib''.  This has been tested with MSVC version 6.00
  115
+with service pack 5.  
232 116
 
233  
-\end{verbatim}
  117
+Tbere is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_dll'' makefile.  It requires Cygwin
  118
+to work with since it requires the auto-export/import functionality.  The resulting DLL and imprt library ``libtomcrypt.dll.a''
  119
+can be used to link LibTomMath dynamically to any Windows program using Cygwin.
234 120
 
235  
-\subsection{Basic Arithmetic}
  121
+\subsection{Testing}
  122
+To build the library and the test harness type
236 123
 
237  
-Next are the class of functions which provide basic arithmetic.
  124
+\begin{alltt}
  125
+make test
  126
+\end{alltt}
238 127
 
239  
-\begin{verbatim}
240  
-/* b = -a */
241  
-int mp_neg(mp_int *a, mp_int *b);
  128
+This will build the library, ``test'' and ``mtest/mtest''.  The ``test'' program will accept test vectors and verify the
  129
+results.  ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote{A copy of MPI
  130
+is included in the package}.  Simply pipe mtest into test using
242 131
 
243  
-/* b = |a| */
244  
-int mp_abs(mp_int *a, mp_int *b);
  132
+\begin{alltt}
  133
+mtest/mtest | test
  134
+\end{alltt}
245 135
 
246  
-/* compare a to b */
247  
-int mp_cmp(mp_int *a, mp_int *b);
  136
+If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into 
  137
+mtest.  For example, if your PRNG program is called ``myprng'' simply invoke
248 138
 
249  
-/* compare |a| to |b| */
250  
-int mp_cmp_mag(mp_int *a, mp_int *b);
  139
+\begin{alltt}
  140
+myprng | mtest/mtest | test
  141
+\end{alltt}
251 142
 
252  
-/* c = a + b */
253  
-int mp_add(mp_int *a, mp_int *b, mp_int *c);
  143
+This will output a row of numbers that are increasing.  Each column is a different test (such as addition, multiplication, etc)
  144
+that is being performed.  The numbers represent how many times the test was invoked.  If an error is detected the program
  145
+will exit with a dump of the relevent numbers it was working with.
254 146
 
255  
-/* c = a - b */
256  
-int mp_sub(mp_int *a, mp_int *b, mp_int *c);
  147
+\section{Purpose of LibTomMath}
  148
+Unlike  GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with 
  149
+bleeding edge performance in mind.  First and foremost LibTomMath was written to be entirely open.  Not only is the 
  150
+source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
  151
+source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
  152
+arithmetic techniques. 
257 153
 
258  
-/* c = a * b */
259  
-int mp_mul(mp_int *a, mp_int *b, mp_int *c);
  154
+LibTomMath was written to be an instructive collection of source code.  This is why there are many comments, only one
  155
+function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
  156
+increase.
260 157
 
261  
-/* b = a^2 */
262  
-int mp_sqr(mp_int *a, mp_int *b);
  158
+Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
  159
+the library (beat that!).
263 160
 
264  
-/* a/b => cb + d == a */
265  
-int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  161
+So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe.  Let me tabulate what I think
  162
+are the pros and cons of LibTomMath by comparing it to the math routines from GnuPG\footnote{GnuPG v1.2.3 versus LibTomMath v0.28}.
266 163
 
267  
-/* c = a mod b, 0 <= c < b  */
268  
-int mp_mod(mp_int *a, mp_int *b, mp_int *c);
269  
-\end{verbatim}
  164
+\newpage\begin{figure}[here]
  165
+\begin{small}
  166
+\begin{center}
  167
+\begin{tabular}{|l|c|c|l|}
  168
+\hline \textbf{Criteria} & \textbf{Pro} & \textbf{Con} & \textbf{Notes} \\
  169
+\hline Few lines of code per file & X & & GnuPG $ = 300.9$, LibTomMath  $ = 76.04$ \\
  170
+\hline Commented function prototypes & X && GnuPG function names are cryptic. \\
  171
+\hline Speed && X & LibTomMath is slower.  \\
  172
+\hline Totally free & X & & GPL has unfavourable restrictions.\\
  173
+\hline Large function base & X & & GnuPG is barebones. \\
  174
+\hline Four modular reduction algorithms & X & & Faster modular exponentiation. \\
  175
+\hline Portable & X & & GnuPG requires configuration to build. \\
  176
+\hline
  177
+\end{tabular}
  178
+\end{center}
  179
+\end{small}
  180
+\caption{LibTomMath Valuation}
  181
+\end{figure}
270 182
 
271  
-\subsection{Single Digit Functions}
  183
+It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application. 
  184
+However, LibTomMath was written with cryptography in mind.  It provides essentially all of the functions a cryptosystem
  185
+would require when working with large integers.  
272 186
 
273  
-\begin{verbatim}
274  
-/* compare against a single digit */
275  
-int mp_cmp_d(mp_int *a, mp_digit b);
  187
+So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
  188
+own application but I think there are reasons not to.  While LibTomMath is slower than libraries such as GnuMP it is
  189
+not normally significantly slower.  On x86 machines the difference is normally a factor of two when performing modular
  190
+exponentiations.
276 191
 
277  
-/* c = a + b */
278  
-int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
  192
+Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern.
279 193
 
280  
-/* c = a - b */
281  
-int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
  194
+\chapter{Getting Started with LibTomMath}
  195
+\section{Building Programs}
  196
+In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically 
  197
+libtommath.a).  There is no library initialization required and the entire library is thread safe.
282 198
 
283  
-/* c = a * b */
284  
-int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
  199
+\section{Return Codes}
  200
+There are three possible return codes a function may return.
285 201
 
286  
-/* a/b => cb + d == a */
287  
-int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
  202
+\index{MP\_OKAY}\index{MP\_YES}\index{MP\_NO}\index{MP\_VAL}\index{MP\_MEM}
  203
+\begin{figure}[here!]
  204
+\begin{center}
  205
+\begin{small}
  206
+\begin{tabular}{|l|l|}
  207
+\hline \textbf{Code} & \textbf{Meaning} \\
  208
+\hline MP\_OKAY & The function succeeded. \\
  209
+\hline MP\_VAL  & The function input was invalid. \\
  210
+\hline MP\_MEM  & Heap memory exhausted. \\
  211
+\hline &\\
  212
+\hline MP\_YES  & Response is yes. \\
  213
+\hline MP\_NO   & Response is no. \\
  214
+\hline
  215
+\end{tabular}
  216
+\end{small}
  217
+\end{center}
  218
+\caption{Return Codes}
  219
+\end{figure}
288 220
 
289  
-/* c = a^b */
290  
-int mp_expt_d(mp_int *a, mp_digit b, mp_int *c);
  221
+The last two codes listed are not actually ``return'ed'' by a function.  They are placed in an integer (the caller must
  222
+provide the address of an integer it can store to) which the caller can access.  To convert one of the three return codes
  223
+to a string use the following function.
291 224
 
292  
-/* c = a mod b, 0 <= c < b  */
293  
-int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
294  
-\end{verbatim}
  225
+\index{mp\_error\_to\_string}
  226
+\begin{alltt}
  227
+char *mp_error_to_string(int code);
  228
+\end{alltt}
295 229
 
296  
-Note that care should be taken for the value of the digit passed.  By default, any 28-bit integer is a valid digit that can
297  
-be passed into the function.  However, if MP\_8BIT or MP\_16BIT is defined only 7 or 15-bit (respectively) integers 
298  
-can be passed into it.
  230
+This will return a pointer to a string which describes the given error code.  It will not work for the return codes 
  231
+MP\_YES and MP\_NO.  
299 232
 
300  
-\subsection{Modular Arithmetic}
  233
+\section{Data Types}
  234
+The basic ``multiple precision integer'' type is known as the ``mp\_int'' within LibTomMath.  This data type is used to
  235
+organize all of the data required to manipulate the integer it represents.  Within LibTomMath it has been prototyped
  236
+as the following.
301 237
 
302  
-There are some trivial modular arithmetic functions.
  238
+\index{mp\_int}
  239
+\begin{alltt}
  240
+typedef struct  \{
  241
+    int used, alloc, sign;
  242
+    mp_digit *dp;
  243
+\} mp_int;
  244
+\end{alltt}
303 245
 
304  
-\begin{verbatim}
305  
-/* d = a + b (mod c) */
306  
-int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  246
+Where ``mp\_digit'' is a data type that represents individual digits of the integer.  By default, an mp\_digit is the
  247
+ISO C ``unsigned long'' data type and each digit is $28-$bits long.  The mp\_digit type can be configured to suit other
  248
+platforms by defining the appropriate macros.  
307 249
 
308  
-/* d = a - b (mod c) */
309  
-int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  250
+All LTM functions that use the mp\_int type will expect a pointer to mp\_int structure.  You must allocate memory to
  251
+hold the structure itself by yourself (whether off stack or heap it doesn't matter).  The very first thing that must be
  252
+done to use an mp\_int is that it must be initialized.
310 253
 
311  
-/* d = a * b (mod c) */
312  
-int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  254
+\section{Function Organization}
313 255
 
314  
-/* c = a * a (mod b) */
315  
-int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c);
  256
+The arithmetic functions of the library are all organized to have the same style prototype.  That is source operands
  257
+are passed on the left and the destination is on the right.  For instance,
316 258
 
317  
-/* c = 1/a (mod b) */
318  
-int mp_invmod(mp_int *a, mp_int *b, mp_int *c);
  259
+\begin{alltt}
  260
+mp_add(&a, &b, &c);       /* c = a + b */
  261
+mp_mul(&a, &a, &c);       /* c = a * a */
  262
+mp_div(&a, &b, &c, &d);   /* c = [a/b], d = a mod b */
  263
+\end{alltt}
319 264
 
320  
-/* c = (a, b) */
321  
-int mp_gcd(mp_int *a, mp_int *b, mp_int *c);
  265
+Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
  266
+For instance,
322 267
 
323  
-/* c = [a, b] or (a*b)/(a, b) */
324  
-int mp_lcm(mp_int *a, mp_int *b, mp_int *c);
  268
+\begin{alltt}
  269
+mp_add(&a, &b, &b);       /* b = a + b */
  270
+mp_div(&a, &b, &a, &c);   /* a = [a/b], c = a mod b */
  271
+\end{alltt}
325 272
 
326  
-/* find the b'th root of a  */
327  
-int mp_n_root(mp_int *a, mp_digit b, mp_int *c);
  273
+This allows operands to be re-used which can make programming simpler.
328 274
 
329  
-/* computes the jacobi c = (a | n) (or Legendre if b is prime)  */
330  
-int mp_jacobi(mp_int *a, mp_int *n, int *c);
  275
+\section{Initialization}
  276
+\subsection{Single Initialization}
  277
+A single mp\_int can be initialized with the ``mp\_init'' function. 
331 278
 
332  
-/* used to setup the Barrett reduction for a given modulus b */
333  
-int mp_reduce_setup(mp_int *a, mp_int *b);
  279
+\index{mp\_init}
  280
+\begin{alltt}
  281
+int mp_init (mp_int * a);
  282
+\end{alltt}
334 283
 
335  
-/* Barrett Reduction, computes a (mod b) with a precomputed value c  
336  
- *
337  
- * Assumes that 0 < a <= b^2, note if 0 > a > -(b^2) then you can merely
338  
- * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code].
339  
- */
340  
-int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
  284
+This function expects a pointer to an mp\_int structure and will initialize the members of the structure so the mp\_int
  285
+represents the default integer which is zero.  If the functions returns MP\_OKAY then the mp\_int is ready to be used
  286
+by the other LibTomMath functions.
341 287
 
342  
-/* setups the montgomery reduction */
343  
-int mp_montgomery_setup(mp_int *a, mp_digit *mp);
  288
+\begin{small} \begin{alltt}
  289
+int main(void)
  290
+\{
  291
+   mp_int number;
  292
+   int result;
  293
+
  294
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  295
+      printf("Error initializing the number.  \%s", 
  296
+             mp_error_to_string(result));
  297
+      return EXIT_FAILURE;
  298
+   \}
  299
+ 
  300
+   /* use the number */
  301
+
  302
+   return EXIT_SUCCESS;
  303
+\}
  304
+\end{alltt} \end{small}
  305
+
  306
+\subsection{Single Free}
  307
+When you are finished with an mp\_int it is ideal to return the heap it used back to the system.  The following function 
  308
+provides this functionality.
  309
+
  310
+\index{mp\_clear}
  311
+\begin{alltt}
  312
+void mp_clear (mp_int * a);
  313
+\end{alltt}
  314
+
  315
+The function expects a pointer to a previously initialized mp\_int structure and frees the heap it uses.  It sets the 
  316
+pointer\footnote{The ``dp'' member.} within the mp\_int to \textbf{NULL} which is used to prevent double free situations. 
  317
+Is is legal to call mp\_clear() twice on the same mp\_int in a row.  
  318
+
  319
+\begin{small} \begin{alltt}
  320
+int main(void)
  321
+\{
  322
+   mp_int number;
  323
+   int result;
  324
+
  325
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  326
+      printf("Error initializing the number.  \%s", 
  327
+             mp_error_to_string(result));
  328
+      return EXIT_FAILURE;
  329
+   \}
  330
+ 
  331
+   /* use the number */
  332
+
  333
+   /* We're done with it. */
  334
+   mp_clear(&number);
  335
+
  336
+   return EXIT_SUCCESS;
  337
+\}
  338
+\end{alltt} \end{small}
  339
+
  340
+\subsection{Multiple Initializations}
  341
+Certain algorithms require more than one large integer.  In these instances it is ideal to initialize all of the mp\_int
  342
+variables in an ``all or nothing'' fashion.  That is, they are either all initialized successfully or they are all
  343
+not initialized.
  344
+
  345
+The  mp\_init\_multi() function provides this functionality.
  346
+
  347
+\index{mp\_init\_multi} \index{mp\_clear\_multi}
  348
+\begin{alltt}
  349
+int mp_init_multi(mp_int *mp, ...);
  350
+\end{alltt}
  351
+
  352
+It accepts a \textbf{NULL} terminated list of pointers to mp\_int structures.  It will attempt to initialize them all
  353
+at once.  If the function returns MP\_OKAY then all of the mp\_int variables are ready to use, otherwise none of them
  354
+are available for use.  A complementary mp\_clear\_multi() function allows multiple mp\_int variables to be free'd 
  355
+from the heap at the same time.  
  356
+
  357
+\begin{small} \begin{alltt}
  358
+int main(void)
  359
+\{
  360
+   mp_int num1, num2, num3;
  361
+   int result;
  362
+
  363
+   if ((result = mp_init_multi(&num1, 
  364
+                               &num2,
  365
+                               &num3, NULL)) != MP\_OKAY) \{      
  366
+      printf("Error initializing the numbers.  \%s", 
  367
+             mp_error_to_string(result));
  368
+      return EXIT_FAILURE;
  369
+   \}
  370
+ 
  371
+   /* use the numbers */
  372
+
  373
+   /* We're done with them. */
  374
+   mp_clear_multi(&num1, &num2, &num3, NULL);
  375
+
  376
+   return EXIT_SUCCESS;
  377
+\}
  378
+\end{alltt} \end{small}
  379
+
  380
+\subsection{Other Initializers}
  381
+To initialized and make a copy of an mp\_int the mp\_init\_copy() function has been provided.  
  382
+
  383
+\index{mp\_init\_copy}
  384
+\begin{alltt}
  385
+int mp_init_copy (mp_int * a, mp_int * b);
  386
+\end{alltt}
  387
+
  388
+This function will initialize ``a'' and make it a copy of ``b'' if all goes well.
  389
+
  390
+\begin{small} \begin{alltt}
  391
+int main(void)
  392
+\{
  393
+   mp_int num1, num2;
  394
+   int result;
344 395
 
345  
-/* computes xR^-1 == x (mod N) via Montgomery Reduction */
346  
-int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
  396
+   /* initialize and do work on num1 ... */
347 397
 
348  
-/* returns 1 if a is a valid DR modulus */
349  
-int mp_dr_is_modulus(mp_int *a);
  398
+   /* We want a copy of num1 in num2 now */
  399
+   if ((result = mp_init_copy(&num2, &num1)) != MP_OKAY) \{
  400
+     printf("Error initializing the copy.  \%s", 
  401
+             mp_error_to_string(result));
  402
+      return EXIT_FAILURE;
  403
+   \}
  404
+ 
  405
+   /* now num2 is ready and contains a copy of num1 */
350 406
 
351  
-/* sets the value of "d" required for mp_dr_reduce */
352  
-void mp_dr_setup(mp_int *a, mp_digit *d);
  407
+   /* We're done with them. */
  408
+   mp_clear_multi(&num1, &num2, NULL);
353 409
 
354  
-/* reduces a modulo b using the Diminished Radix method */
355  
-int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
  410
+   return EXIT_SUCCESS;
  411
+\}
  412
+\end{alltt} \end{small}
356 413
 
357  
-/* d = a^b (mod c) */
358  
-int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
359  
-\end{verbatim}
  414
+Another less common initializer is mp\_init\_size() which allows the user to initialize an mp\_int with a given
  415
+default number of digits.  By default, all initializers allocate \textbf{MP\_PREC} digits.  This function lets
  416
+you override this behaviour.
360 417
 
361  
-\subsection{Primality Routines}
362  
-\begin{verbatim}
363  
-/* ---> Primes <--- */
364  
-/* table of first 256 primes */
365  
-extern const mp_digit __prime_tab[];
  418
+\index{mp\_init\_size}
  419
+\begin{alltt}
  420
+int mp_init_size (mp_int * a, int size);
  421
+\end{alltt}
366 422
 
367  
-/* result=1 if a is divisible by one of the first 256 primes */
368  
-int mp_prime_is_divisible(mp_int *a, int *result);
  423
+The ``size'' parameter must be greater than zero.  If the function succeeds the mp\_int ``a'' will be initialized
  424
+to have ``size'' digits (which are all initially zero).  
369 425
 
370  
-/* performs one Fermat test of "a" using base "b".  
371  
- * Sets result to 0 if composite or 1 if probable prime 
372  
- */
373  
-int mp_prime_fermat(mp_int *a, mp_int *b, int *result);
  426
+\begin{small} \begin{alltt}
  427
+int main(void)
  428
+\{
  429
+   mp_int number;
  430
+   int result;
  431
+
  432
+   /* we need a 60-digit number */
  433
+   if ((result = mp_init_size(&number, 60)) != MP_OKAY) \{
  434
+      printf("Error initializing the number.  \%s", 
  435
+             mp_error_to_string(result));
  436
+      return EXIT_FAILURE;
  437
+   \}
  438
+ 
  439
+   /* use the number */
  440
+
  441
+   return EXIT_SUCCESS;
  442
+\}
  443
+\end{alltt} \end{small}
  444
+
  445
+\section{Maintenance Functions}
  446
+
  447
+\subsection{Reducing Memory Usage}
  448
+When an mp\_int is in a state where it won't be changed again\footnote{A Diffie-Hellman modulus for instance.} excess
  449
+digits can be removed to return memory to the heap with the mp\_shrink() function.
  450
+
  451
+\index{mp\_shrink}
  452
+\begin{alltt}
  453
+int mp_shrink (mp_int * a);
  454
+\end{alltt}
  455
+
  456
+This will remove excess digits of the mp\_int ``a''.  If the operation fails the mp\_int should be intact without the
  457
+excess digits being removed.  Note that you can use a shrunk mp\_int in further computations, however, such operations
  458
+will require heap operations which can be slow.  It is not ideal to shrink mp\_int variables that you will further
  459
+modify in the system (unless you are seriously low on memory).  
  460
+
  461
+\begin{small} \begin{alltt}
  462
+int main(void)
  463
+\{
  464
+   mp_int number;
  465
+   int result;
374 466
 
375  
-/* performs one Miller-Rabin test of "a" using base "b".
376  
- * Sets result to 0 if composite or 1 if probable prime 
377  
- */
378  
-int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result);
  467
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  468
+      printf("Error initializing the number.  \%s", 
  469
+             mp_error_to_string(result));
  470
+      return EXIT_FAILURE;
  471
+   \}
  472
+ 
  473
+   /* use the number [e.g. pre-computation]  */
379 474
 
380  
-/* performs t rounds of Miller-Rabin on "a" using the first
381  
- * t prime bases.  Also performs an initial sieve of trial
382  
- * division.  Determines if "a" is prime with probability
383  
- * of error no more than (1/4)^t.
384  
- *
385  
- * Sets result to 1 if probably prime, 0 otherwise
386  
- */
387  
-int mp_prime_is_prime(mp_int *a, int t, int *result);
  475
+   /* We're done with it for now. */
  476
+   if ((result = mp_shrink(&number)) != MP_OKAY) \{
  477
+      printf("Error shrinking the number.  \%s", 
  478
+             mp_error_to_string(result));
  479
+      return EXIT_FAILURE;
  480
+   \}
388 481
 
389  
-/* finds the next prime after the number "a" using "t" trials
390  
- * of Miller-Rabin.
391  
- */
392  
-int mp_prime_next_prime(mp_int *a, int t, int bbs_style);
393  
-\end{verbatim}
  482
+   /* use it .... */
394 483
 
395  
-\subsection{Radix Conversions}
396  
-To read or store integers in other formats there are the following functions.
397 484
 
398  
-\begin{verbatim}
399  
-int mp_unsigned_bin_size(mp_int *a);
400  
-int mp_read_unsigned_bin(mp_int *a, unsigned char *b, int c);
401  
-int mp_to_unsigned_bin(mp_int *a, unsigned char *b);
  485
+   /* we're done with it. */ 
  486
+   mp_clear(&number);
402 487
 
403  
-int mp_signed_bin_size(mp_int *a);
404  
-int mp_read_signed_bin(mp_int *a, unsigned char *b, int c);
405  
-int mp_to_signed_bin(mp_int *a, unsigned char *b);
  488
+   return EXIT_SUCCESS;
  489
+\}
  490
+\end{alltt} \end{small}
406 491
 
407  
-int mp_read_radix(mp_int *a, unsigned char *str, int radix);
408  
-int mp_toradix(mp_int *a, unsigned char *str, int radix);
409  
-int mp_radix_size(mp_int *a, int radix);
410  
-\end{verbatim}
  492
+\subsection{Adding additional digits}
411 493
 
412  
-The integers are stored in big endian format as most libraries (and MPI) expect.  The \textbf{mp\_read\_radix} and 
413  
-\textbf{mp\_toradix} functions read and write (respectively) null terminated ASCII strings in a given radix.  Valid values
414  
-for the radix are between 2 and 64 (inclusively).  
  494
+Within the mp\_int structure are two parameters which control the limitations of the array of digits that represent
  495
+the integer the mp\_int is meant to equal.   The \textit{used} parameter dictates how many digits are significant, that is,
  496
+contribute to the value of the mp\_int.  The \textit{alloc} parameter dictates how many digits are currently available in
  497
+the array.  If you need to perform an operation that requires more digits you will have to mp\_grow() the mp\_int to
  498
+your desired size.  
415 499
 
416  
-\section{Function Analysis}
  500
+\index{mp\_grow}
  501
+\begin{alltt}
  502
+int mp_grow (mp_int * a, int size);
  503
+\end{alltt}
417 504
 
418  
-Throughout the function analysis the variable $N$ will denote the average size of an input to a function as measured 
419  
-by the number of digits it has.  The variable $W$ will denote the number of bits per word and $c$ will denote a small
420  
-constant amount of work.  The big-oh notation will be abused slightly to consider numbers that do not grow to infinity.
421  
-That is we shall consider $O(N/2) \ne O(N)$ which is an abuse of the notation.
  505
+This will grow the array of digits of ``a'' to ``size''.  If the \textit{alloc} parameter is already bigger than
  506
+``size'' the function will not do anything.
422 507
 
423  
-\subsection{Digit Manipulation Functions}
424  
-The class of digit manipulation functions such as \textbf{mp\_rshd}, \textbf{mp\_lshd} and \textbf{mp\_mul\_2} are all
425  
-very simple functions to analyze.  
  508
+\begin{small} \begin{alltt}
  509
+int main(void)
  510
+\{
  511
+   mp_int number;
  512
+   int result;
426 513
 
427  
-\subsubsection{mp\_rshd(mp\_int *a, int b)}
428  
-Shifts $a$ by given number of digits to the right and is equivalent to dividing by $\beta^b$.  The work is performed
429  
-in-place which means the input and output are the same.  If the shift count $b$ is less than or equal to zero 
430  
-the function returns without doing any work.  If the the shift count is larger than the number of digits in $a$ 
431  
-then $a$ is simply zeroed without shifting digits.
  514
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  515
+      printf("Error initializing the number.  \%s", 
  516
+             mp_error_to_string(result));
  517
+      return EXIT_FAILURE;
  518
+   \}
  519
+ 
  520
+   /* use the number */
432 521
 
433  
-This function requires no additional memory and $O(N)$ time.
  522
+   /* We need to add 20 digits to the number  */
  523
+   if ((result = mp_grow(&number, number.alloc + 20)) != MP_OKAY) \{
  524
+      printf("Error growing the number.  \%s", 
  525
+             mp_error_to_string(result));
  526
+      return EXIT_FAILURE;
  527
+   \}
434 528
 
435  
-\subsubsection{mp\_lshd(mp\_int *a, int b)}
436  
-Shifts $a$ by a given number of digits to the left and is equivalent to multiplying by $\beta^b$.  The work
437  
-is performed in-place which means the input and output are the same.  If the shift count $b$ is less than or equal 
438  
-to zero the function returns success without doing any work.
439 529
 
440  
-This function requires $O(b)$ additional digits of memory and $O(N)$ time.
  530
+   /* use the number */
441 531
 
442  
-\subsubsection{mp\_div\_2d(mp\_int *a, int b, mp\_int *c, mp\_int *d)}
443  
-Shifts $a$ by a given number of \textbf{bits} to the right and is equivalent to dividing by $2^b$.  The shifted number is stored
444  
-in the $c$ parameter.  The remainder of $a/2^b$ is optionally stored in $d$ (if it is not passed as NULL).  
445  
-If the shift count $b$ is less than or equal to zero the function places $a$ in $c$ and returns success.  
  532
+   /* we're done with it. */ 
  533
+   mp_clear(&number);
446 534
 
447  
-This function requires $O(2 \cdot N)$ additional digits of memory and $O(2 \cdot N)$ time.
  535
+   return EXIT_SUCCESS;
  536
+\}
  537
+\end{alltt} \end{small}
448 538
 
449  
-\subsubsection{mp\_mul\_2d(mp\_int *a, int b, mp\_int *c)}
450  
-Shifts $a$ by a given number of bits to the left and is equivalent to multiplying by $2^b$.  The shifted number
451  
-is placed in the $c$ parameter.  If the shift count $b$ is less than or equal to zero the function places $a$
452  
-in $c$ and returns success.  
  539
+\chapter{Basic Operations}
  540
+\section{Small Constants}
  541
+Setting mp\_ints to small constants is a relatively common operation.  To accomodate these instances there are two
  542
+small constant assignment functions.  The first function is used to set a single digit constant while the second sets
  543
+an ISO C style ``unsigned long'' constant.  The reason for both functions is efficiency.  Setting a single digit is quick but the
  544
+domain of a digit can change (it's always at least $0 \ldots 127$).  
453 545
 
454  
-This function requires $O(N)$ additional digits of memory and $O(2 \cdot N)$ time.
  546
+\subsection{Single Digit}
455 547
 
456  
-\subsubsection{mp\_mul\_2(mp\_int *a, mp\_int *b)}
457  
-Multiplies $a$ by two and stores in $b$.  This function is hard coded todo a shift by one place so it is faster
458  
-than calling mp\_mul\_2d with a count of one.  
  548
+Setting a single digit can be accomplished with the following function.
459 549
 
460  
-This function requires $O(N)$ additional digits of memory and $O(N)$ time.
  550
+\index{mp\_set}
  551
+\begin{alltt}
  552
+void mp_set (mp_int * a, mp_digit b);
  553
+\end{alltt}
461 554
 
462  
-\subsubsection{mp\_div\_2(mp\_int *a, mp\_int *b)}
463  
-Divides $a$ by two and stores in $b$.  This function is hard coded todo a shift by one place so it is faster
464  
-than calling mp\_div\_2d with a count of one.
  555
+This will zero the contents of ``a'' and make it represent an integer equal to the value of ``b''.  Note that this
  556
+function has a return type of \textbf{void}.  It cannot cause an error so it is safe to assume the function
  557
+succeeded.
465 558
 
466  
-This function requires $O(N)$ additional digits of memory and $O(N)$ time.
  559
+\begin{small} \begin{alltt}
  560
+int main(void)
  561
+\{
  562
+   mp_int number;
  563
+   int result;
467 564
 
468  
-\subsubsection{mp\_mod\_2d(mp\_int *a, int b, mp\_int *c)}
469  
-Performs the action of reducing $a$ modulo $2^b$ and stores the result in $c$.  If the shift count $b$ is less than 
470  
-or equal to zero the function places $a$ in $c$ and returns success.  
  565
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  566
+      printf("Error initializing the number.  \%s", 
  567
+             mp_error_to_string(result));
  568
+      return EXIT_FAILURE;
  569
+   \}
  570
+ 
  571
+   /* set the number to 5 */
  572
+   mp_set(&number, 5);
471 573
 
472  
-This function requires $O(N)$ additional digits of memory and $O(2 \cdot N)$ time.
  574
+   /* we're done with it. */ 
  575
+   mp_clear(&number);
473 576
 
474  
-\subsubsection{mp\_2expt(mp\_int *a, int b)}
475  
-Computes $a = 2^b$ by first setting $a$ to zero then OR'ing the correct bit to get the right value.
  577
+   return EXIT_SUCCESS;
  578
+\}
  579
+\end{alltt} \end{small}
476 580
 
477  
-\subsubsection{mp\_rand(mp\_int *a, int digits)}
478  
-Computes a pseudo-random (\textit{via rand()}) integer that is always ``$digits$'' digits in length.  Not for
479  
-cryptographic use.
  581
+\subsection{Long Constant}
480 582
 
481  
-\subsection{Binary Arithmetic}
482  
-\subsubsection{mp\_xor(mp\_int *a, mp\_int *b, mp\_int *c)}
483  
-Computes $c = a \oplus b$, pseudo-extends with zeroes whichever of $a$ or $b$ is shorter such that the length
484  
-of $c$ is the maximum length of the two inputs.
  583
+When you want to set a constant that is the size of an ISO C ``unsigned long'' and larger than a single
  584
+digit the following function is provided.
485 585
 
486  
-\subsubsection{mp\_or(mp\_int *a, mp\_int *b, mp\_int *c)}
487  
-Computes $c = a \lor b$, pseudo-extends with zeroes whichever of $a$ or $b$ is shorter such that the length
488  
-of $c$ is the maximum length of the two inputs.
  586
+\index{mp\_set\_int}
  587
+\begin{alltt}
  588
+int mp_set_int (mp_int * a, unsigned long b);
  589
+\end{alltt}
489 590
 
490  
-\subsubsection{mp\_and(mp\_int *a, mp\_int *b, mp\_int *c)}
491  
-Computes $c = a \land b$, pseudo-extends with zeroes whichever of $a$ or $b$ is shorter such that the length
492  
-of $c$ is the maximum length of the two inputs.
  591
+This will assign the value of the 32-bit variable ``b'' to the mp\_int ``a''.  Unlike mp\_set() this function will always
  592
+accept a 32-bit input regardless of the size of a single digit.  However, since the value may span several digits 
  593
+this function can fail if it runs out of heap memory.
493 594
 
494  
-\subsection{Basic Arithmetic}
  595
+\begin{small} \begin{alltt}
  596
+int main(void)
  597
+\{
  598
+   mp_int number;
  599
+   int result;
  600
+
  601
+   if ((result = mp_init(&number)) != MP_OKAY) \{
  602
+      printf("Error initializing the number.  \%s", 
  603
+             mp_error_to_string(result));
  604
+      return EXIT_FAILURE;
  605
+   \}
  606
+ 
  607
+   /* set the number to 654321 (note this is bigger than 127) */
  608
+   if ((result = mp_set_int(&number, 654321)) != MP_OKAY) \{
  609
+      printf("Error setting the value of the number.  \%s", 
  610
+             mp_error_to_string(result));
  611
+      return EXIT_FAILURE;
  612
+   \}
  613
+   /* we're done with it. */ 
  614
+   mp_clear(&number);
  615
+
  616
+   return EXIT_SUCCESS;
  617
+\}
  618
+\end{alltt} \end{small}
  619
+
  620
+\section{Comparisons}
  621
+
  622
+Comparisons in LibTomMath are always performed in a ``left to right'' fashion.  There are three possible return codes
  623
+for any comparison.
  624
+
  625
+\index{MP\_GT} \index{MP\_EQ} \index{MP\_LT}
  626
+\begin{figure}[here]
  627
+\begin{center}
  628
+\begin{tabular}{|c|c|}
  629
+\hline \textbf{Result Code} & \textbf{Meaning} \\
  630
+\hline MP\_GT & $a > b$ \\
  631
+\hline MP\_EQ & $a = b$ \\
  632
+\hline MP\_LT & $a < b$ \\
  633
+\hline
  634
+\end{tabular}
  635
+\end{center}
  636
+\caption{Comparison Codes for $a, b$}
  637
+\label{fig:CMP}
  638
+\end{figure}
495 639
 
496  
-\subsubsection{mp\_cmp(mp\_int *a, mp\_int *b)}
497  
-Performs a \textbf{signed} comparison between $a$ and $b$ returning \textbf{MP\_GT} if $a$ is larger than $b$.
  640
+In figure \ref{fig:CMP} two integers $a$ and $b$ are being compared.  In this case $a$ is said to be ``to the left'' of 
  641
+$b$.  
498 642
 
499  
-This function requires no additional memory and $O(N)$ time.
  643
+\subsection{Unsigned comparison}
500 644
 
501  
-\subsubsection{mp\_cmp\_mag(mp\_int *a, mp\_int *b)}
502  
-Performs a \textbf{unsigned} comparison between $a$ and $b$ returning \textbf{MP\_GT} is $a$ is larger than $b$.  Note 
503  
-that this comparison is unsigned which means it will report, for example, $-5 > 3$.  By comparison mp\_cmp will 
504  
-report $-5 < 3$.
  645
+An unsigned comparison considers only the digits themselves and not the associated \textit{sign} flag of the 
  646
+mp\_int structures.  This is analogous to an absolute comparison.  The function mp\_cmp\_mag() will compare two
  647
+mp\_int variables based on their digits only.
505 648
 
506  
-This function requires no additional memory and $O(N)$ time.
  649
+\index{mp\_cmp\_mag}
  650
+\begin{alltt}
  651
+int mp_cmp(mp_int * a, mp_int * b);
  652
+\end{alltt}
  653
+This will compare ``a'' to ``b'' placing ``a'' to the left of ``b''.  This function cannot fail and will return one of the
  654
+three compare codes listed in figure \ref{fig:CMP}.
507 655
 
508  
-\subsubsection{mp\_add(mp\_int *a, mp\_int *b, mp\_int *c)}
509  
-Computes $c = a + b$ using signed arithmetic.  Handles the sign of the numbers which means it will subtract as 
510  
-required, e.g. $a + -b$ turns into $a - b$.
  656
+\begin{small} \begin{alltt}
  657
+int main(void)
  658
+\{
  659
+   mp_int number1, number2;
  660
+   int result;
  661
+
  662
+   if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
  663
+      printf("Error initializing the numbers.  \%s", 
  664
+             mp_error_to_string(result));
  665
+      return EXIT_FAILURE;
  666
+   \}
  667
+ 
  668
+   /* set the number1 to 5 */
  669
+   mp_set(&number1, 5);
  670
+  
  671
+   /* set the number2 to -6 */
  672
+   mp_set(&number2, 6);
  673
+   if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
  674
+      printf("Error negating number2.  \%s", 
  675
+             mp_error_to_string(result));
  676
+      return EXIT_FAILURE;
  677
+   \}
  678
+
  679
+   switch(mp_cmp_mag(&number1, &number2)) \{
  680
+       case MP_GT:  printf("|number1| > |number2|"); break;
  681
+       case MP_EQ:  printf("|number1| = |number2|"); break;
  682
+       case MP_LT:  printf("|number1| < |number2|"); break;
  683
+   \}
  684
+
  685
+   /* we're done with it. */ 
  686
+   mp_clear_multi(&number1, &number2, NULL);
  687
+
  688
+   return EXIT_SUCCESS;
  689
+\}
  690
+\end{alltt} \end{small}
  691
+
  692
+If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes 
  693
+successfully it should print the following.
  694
+
  695
+\begin{alltt}
  696
+|number1| < |number2|
  697
+\end{alltt}
  698
+
  699
+This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
  700
+
  701
+\subsection{Signed comparison}
  702
+
  703
+To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
  704
+
  705
+\index{mp\_cmp}
  706
+\begin{alltt}
  707
+int mp_cmp(mp_int * a, mp_int * b);
  708
+\end{alltt}
  709
+
  710
+This will compare ``a'' to the left of ``b''.  It will first compare the signs of the two mp\_int variables.  If they
  711
+differ it will return immediately based on their signs.  If the signs are equal then it will compare the digits
  712
+individually.  This function will return one of the compare conditions codes listed in figure \ref{fig:CMP}.
  713
+
  714
+\begin{small} \begin{alltt}
  715
+int main(void)
  716
+\{
  717
+   mp_int number1, number2;