1\documentclass[synpaper]{book}
2\usepackage{hyperref}
3\usepackage{makeidx}
4\usepackage{amssymb}
5\usepackage{color}
6\usepackage{alltt}
7\usepackage{graphicx}
8\usepackage{layout}
9\usepackage{appendix}
10\def\union{\cup}
11\def\intersect{\cap}
12\def\getsrandom{\stackrel{\rm R}{\gets}}
13\def\cross{\times}
14\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
15\def\catn{$\|$}
16\def\divides{\hspace{0.3em} | \hspace{0.3em}}
17\def\nequiv{\not\equiv}
18\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
19\def\lcm{{\rm lcm}}
20\def\gcd{{\rm gcd}}
21\def\log{{\rm log}}
22\def\ord{{\rm ord}}
23\def\abs{{\mathit abs}}
24\def\rep{{\mathit rep}}
25\def\mod{{\mathit\ mod\ }}
26\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
27\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
28\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
29\def\Or{{\rm\ or\ }}
30\def\And{{\rm\ and\ }}
31\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
32\def\implies{\Rightarrow}
33\def\undefined{{\rm ``undefined"}}
34\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
35\let\oldphi\phi
36\def\phi{\varphi}
37\def\Pr{{\rm Pr}}
38\newcommand{\str}[1]{{\mathbf{#1}}}
39\def\F{{\mathbb F}}
40\def\N{{\mathbb N}}
41\def\Z{{\mathbb Z}}
42\def\R{{\mathbb R}}
43\def\C{{\mathbb C}}
44\def\Q{{\mathbb Q}}
45\definecolor{DGray}{gray}{0.5}
46\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
47\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
48\def\gap{\vspace{0.5ex}}
49\makeindex
50\begin{document}
51\frontmatter
52\pagestyle{empty}
53\title{LibTomMath User Manual \\ v1.2.0}
54\author{LibTom Projects \\ www.libtom.net}
55\maketitle
56This text, the library and the accompanying textbook are all hereby placed in the public domain.  This book has been
57formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package.
58
59\vspace{10cm}
60
61\begin{flushright}Open Source.  Open Academia.  Open Minds.
62
63\mbox{ }
64LibTom Projects
65
66\& originally
67
68Tom St Denis,
69
70Ontario, Canada
71\end{flushright}
72
73\tableofcontents
74\listoffigures
75\mainmatter
76\pagestyle{headings}
77\chapter{Introduction}
78\section{What is LibTomMath?}
79LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
80large integer numbers.  It was written in portable ISO C source code so that it will build on any platform with a conforming
81C compiler.
82
83In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
84to implement ``bignum'' math.  However, the resulting code has proven to be very useful.  It has been used by numerous
85universities, commercial and open source software developers.  It has been used on a variety of platforms ranging from
86Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.
87
88\section{License}
89As of the v0.25 the library source code has been placed in the public domain with every new release.  As of the v0.28
90release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
91release as well.  This textbook is meant to compliment the project by providing a more solid walkthrough of the development
92algorithms used in the library.
93
94Since both\footnote{Note that the MPI files under mtest/ are copyrighted by Michael Fromberger.  They are not required to use LibTomMath.} are in the
95public domain everyone is entitled to do with them as they see fit.
96
97\section{Building LibTomMath}
98
99LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC.  However, the library will
100also 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
101developer. Please consider to commit such a makefile to the LibTomMath developers, currently residing at
102\url{http://github.com/libtom/libtommath}, if successfully done so.
103
104Intel's C-compiler (ICC) is sufficiently compatible with GCC, at least the newer versions, to replace GCC for building the static and the shared library. Editing the makefiles is not needed, just set the shell variable \texttt{CC} as shown below.
105\begin{alltt}
106CC=/home/czurnieden/intel/bin/icc make
107\end{alltt}
108
109ICC does not know all options available for GCC and LibTomMath uses two diagnostics \texttt{-Wbad-function-cast} and \texttt{-Wcast-align} that are not supported by ICC resulting in the warnings:
110\begin{alltt}
111icc: command line warning #10148: option '-Wbad-function-cast' not supported
112icc: command line warning #10148: option '-Wcast-align' not supported
113\end{alltt}
114It is possible to mute this ICC warning with the compiler flag \texttt{-diag-disable=10148}\footnote{It is not recommended to suppress warnings without a very good reason but there is no harm in doing so in this very special case.}.
115
116\subsection{Static Libraries}
117To build as a static library for GCC issue the following
118\begin{alltt}
119make
120\end{alltt}
121
122command.  This will build the library and archive the object files in ``libtommath.a''.  Now you link against
123that and include ``tommath.h'' within your programs.  Alternatively to build with MSVC issue the following
124\begin{alltt}
125nmake -f makefile.msvc
126\end{alltt}
127
128This will build the library and archive the object files in ``tommath.lib''.  This has been tested with MSVC
129version 6.00 with service pack 5.
130
131To run a program to adapt the Toom-Cook cut-off values to your architecture type
132\begin{alltt}
133make tune
134\end{alltt}
135This will take some time.
136
137\subsection{Shared Libraries}
138\subsubsection{GNU based Operating Systems}
139To build as a shared library for GCC issue the following
140\begin{alltt}
141make -f makefile.shared
142\end{alltt}
143This requires the ``libtool'' package (common on most Linux/BSD systems).  It will build LibTomMath as both shared
144and static then install (by default) into /usr/lib as well as install the header files in /usr/include.  The shared
145library (resource) will be called ``libtommath.la'' while the static library called ``libtommath.a''.  Generally
146you use libtool to link your application against the shared object.
147
148To run a program to adapt the Toom-Cook cut-off values to your architecture type
149\begin{alltt}
150make -f makefile.shared tune
151\end{alltt}
152This will take some time.
153
154\subsubsection{Microsoft Windows based Operating Systems}
155There is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_dll'' makefile.  It requires
156Cygwin to work with since it requires the auto-export/import functionality.  The resulting DLL and import library
157``libtommath.dll.a'' can be used to link LibTomMath dynamically to any Windows program using Cygwin.
158\subsubsection{OpenBSD}
159OpenBSD replaced some of their GNU-tools, especially \texttt{libtool} with their own, slightly different versions. To ease the workload of LibTomMath's developer team, only a static library can be build with the included \texttt{makefile.unix}.
160
161The wrong \texttt{make} will result in errors like:
162\begin{alltt}
163*** Parse error in /home/user/GITHUB/libtommath: Need an operator in 'LIBNAME' )
164*** Parse error: Need an operator in 'endif' (makefile.shared:8)
165*** Parse error: Need an operator in 'CROSS_COMPILE' (makefile_include.mk:16)
166*** Parse error: Need an operator in 'endif' (makefile_include.mk:18)
167*** Parse error: Missing dependency operator (makefile_include.mk:22)
168*** Parse error: Missing dependency operator (makefile_include.mk:23)
169...
170\end{alltt}
171The wrong \texttt{libtool} will build it all fine but when it comes to the final linking fails with
172\begin{alltt}
173...
174cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
175cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
176cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
177libtool --mode=link --tag=CC cc  bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_mo
178libtool: link: cc bn_error.lo bn_s_mp_invmod_fast.lo bn_s_mp_montgomery_reduce_fast0
179bn_error.lo: file not recognized: File format not recognized
180cc: error: linker command failed with exit code 1 (use -v to see invocation)
181Error while executing cc bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_montgomery0
182gmake: *** [makefile.shared:64: libtommath.la] Error 1
183\end{alltt}
184
185To build a shared library with OpenBSD\footnote{Tested with OpenBSD version 6.4} the GNU versions of \texttt{make} and \texttt{libtool} are needed.
186\begin{alltt}
187$ sudo pkg_add gmake libtool
188\end{alltt}
189At this time two versions of \texttt{libtool} are installed and both are named \texttt{libtool}, unfortunately but GNU \texttt{libtool} has been placed in \texttt{/usr/local/bin/} and the native version in \texttt{/usr/bin/}. The path might be different in other versions of OpenBSD but both programms differ in the output of \texttt{libtool --version}
190\begin{alltt}
191$ /usr/local/bin/libtool --version
192libtool (GNU libtool) 2.4.2
193Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
194
195Copyright (C) 2011 Free Software Foundation, Inc.
196This is free software; see the source for copying conditions.  There is NO
197warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
198$ libtool --version
199libtool (not (GNU libtool)) 1.5.26
200\end{alltt}
201
202The shared library should build now with
203\begin{alltt}
204LIBTOOL="/usr/local/bin/libtool" gmake -f makefile.shared
205\end{alltt}
206You might need to run a \texttt{gmake -f makefile.shared clean} first.
207
208\subsubsection{NetBSD}
209NetBSD is not as strict as OpenBSD but still needs \texttt{gmake} to build the shared library. \texttt{libtool} may also not exist in a fresh install.
210\begin{alltt}
211pkg_add gmake libtool
212\end{alltt}
213Please check with \texttt{libtool --version} that installed libtool is indeed a GNU libtool.
214Build the shared library by typing:
215\begin{alltt}
216gmake -f makefile.shared
217\end{alltt}
218
219\subsection{Testing}
220To build the library and the test harness type
221
222\begin{alltt}
223make test
224\end{alltt}
225
226This will build the library, ``test'' and ``mtest/mtest''.  The ``test'' program will accept test vectors and verify the
227results.  ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote{A copy of MPI
228is included in the package}.  Simply pipe mtest into test using
229
230\begin{alltt}
231mtest/mtest | test
232\end{alltt}
233
234If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into
235mtest.  For example, if your PRNG program is called ``myprng'' simply invoke
236
237\begin{alltt}
238myprng | mtest/mtest | test
239\end{alltt}
240
241This will output a row of numbers that are increasing.  Each column is a different test (such as addition, multiplication, etc)
242that is being performed.  The numbers represent how many times the test was invoked.  If an error is detected the program
243will exit with a dump of the relevant numbers it was working with.
244
245\section{Build Configuration}
246LibTomMath can configured at build time in three phases we shall call ``depends'', ``tweaks'' and ``trims''.
247Each phase changes how the library is built and they are applied one after another respectively.
248
249To make the system more powerful you can tweak the build process.  Classes are defined in the file
250``tommath\_superclass.h''.  By default, the symbol ``LTM\_ALL'' shall be defined which simply
251instructs the system to build all of the functions.  This is how LibTomMath used to be packaged.  This will give you
252access to every function LibTomMath offers.
253
254However, there are cases where such a build is not optional.  For instance, you want to perform RSA operations.  You
255don't need the vast majority of the library to perform these operations.  Aside from LTM\_ALL there is
256another pre--defined class ``SC\_RSA\_1'' which works in conjunction with the RSA from LibTomCrypt.  Additional
257classes can be defined base on the need of the user.
258
259\subsection{Build Depends}
260In the file tommath\_class.h you will see a large list of C ``defines'' followed by a series of ``ifdefs''
261which further define symbols.  All of the symbols (technically they're macros $\ldots$) represent a given C source
262file.  For instance, BN\_MP\_ADD\_C represents the file ``bn\_mp\_add.c''.  When a define has been enabled the
263function in the respective file will be compiled and linked into the library.  Accordingly when the define
264is absent the file will not be compiled and not contribute any size to the library.
265
266You will also note that the header tommath\_class.h is actually recursively included (it includes itself twice).
267This is to help resolve as many dependencies as possible.  In the last pass the symbol LTM\_LAST will be defined.
268This is useful for ``trims''.
269
270\subsection{Build Tweaks}
271A tweak is an algorithm ``alternative''.  For example, to provide tradeoffs (usually between size and space).
272They can be enabled at any pass of the configuration phase.
273
274\begin{small}
275\begin{center}
276\begin{tabular}{|l|l|}
277\hline \textbf{Define} & \textbf{Purpose} \\
278\hline BN\_MP\_DIV\_SMALL & Enables a slower, smaller and equally \\
279                          & functional mp\_div() function \\
280\hline
281\end{tabular}
282\end{center}
283\end{small}
284
285\subsection{Build Trims}
286A trim is a manner of removing functionality from a function that is not required.  For instance, to perform
287RSA cryptography you only require exponentiation with odd moduli so even moduli support can be safely removed.
288Build trims are meant to be defined on the last pass of the configuration which means they are to be defined
289only if LTM\_LAST has been defined.
290
291\subsubsection{Moduli Related}
292\begin{small}
293\begin{center}
294\begin{tabular}{|l|l|}
295\hline \textbf{Restriction} & \textbf{Undefine} \\
296\hline Exponentiation with odd moduli only & BN\_S\_MP\_EXPTMOD\_C \\
297                                           & BN\_MP\_REDUCE\_C \\
298                                           & BN\_MP\_REDUCE\_SETUP\_C \\
299                                           & BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
300                                           & BN\_FAST\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
301\hline Exponentiation with random odd moduli & (The above plus the following) \\
302                                           & BN\_MP\_REDUCE\_2K\_C \\
303                                           & BN\_MP\_REDUCE\_2K\_SETUP\_C \\
304                                           & BN\_MP\_REDUCE\_IS\_2K\_C \\
305                                           & BN\_MP\_DR\_IS\_MODULUS\_C \\
306                                           & BN\_MP\_DR\_REDUCE\_C \\
307                                           & BN\_MP\_DR\_SETUP\_C \\
308\hline Modular inverse odd moduli only     & BN\_MP\_INVMOD\_SLOW\_C \\
309\hline Modular inverse (both, smaller/slower) & BN\_FAST\_MP\_INVMOD\_C \\
310\hline
311\end{tabular}
312\end{center}
313\end{small}
314
315\subsubsection{Operand Size Related}
316\begin{small}
317\begin{center}
318\begin{tabular}{|l|l|}
319\hline \textbf{Restriction} & \textbf{Undefine} \\
320\hline Moduli $\le 2560$ bits              & BN\_MP\_MONTGOMERY\_REDUCE\_C \\
321                                           & BN\_S\_MP\_MUL\_DIGS\_C \\
322                                           & BN\_S\_MP\_MUL\_HIGH\_DIGS\_C \\
323                                           & BN\_S\_MP\_SQR\_C \\
324\hline Polynomial Schmolynomial            & BN\_MP\_KARATSUBA\_MUL\_C \\
325                                           & BN\_MP\_KARATSUBA\_SQR\_C \\
326                                           & BN\_MP\_TOOM\_MUL\_C \\
327                                           & BN\_MP\_TOOM\_SQR\_C \\
328
329\hline
330\end{tabular}
331\end{center}
332\end{small}
333
334
335\section{Purpose of LibTomMath}
336Unlike  GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with
337bleeding edge performance in mind.  First and foremost LibTomMath was written to be entirely open.  Not only is the
338source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
339source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
340arithmetic techniques.
341
342LibTomMath was written to be an instructive collection of source code.  This is why there are many comments, only one
343function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
344increase.
345
346Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
347the library (beat that!).
348
349So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe.  Let me tabulate what I think
350are the pros and cons of LibTomMath by comparing it to the math routines from GnuPG\footnote{GnuPG v1.2.3 versus LibTomMath v0.28}.
351
352\newpage\begin{figure}[h]
353\begin{small}
354\begin{center}
355\begin{tabular}{|l|c|c|l|}
356\hline \textbf{Criteria} & \textbf{Pro} & \textbf{Con} & \textbf{Notes} \\
357\hline Few lines of code per file & X & & GnuPG $ = 300.9$, LibTomMath  $ = 71.97$ \\
358\hline Commented function prototypes & X && GnuPG function names are cryptic. \\
359\hline Speed && X & LibTomMath is slower.  \\
360\hline Totally free & X & & GPL has unfavourable restrictions.\\
361\hline Large function base & X & & GnuPG is barebones. \\
362\hline Five modular reduction algorithms & X & & Faster modular exponentiation for a variety of moduli. \\
363\hline Portable & X & & GnuPG requires configuration to build. \\
364\hline
365\end{tabular}
366\end{center}
367\end{small}
368\caption{LibTomMath Valuation}
369\end{figure}
370
371It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application.
372However, LibTomMath was written with cryptography in mind.  It provides essentially all of the functions a cryptosystem
373would require when working with large integers.
374
375So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
376own application but I think there are reasons not to.  While LibTomMath is slower than libraries such as GnuMP it is
377not normally significantly slower.  On x86 machines the difference is normally a factor of two when performing modular
378exponentiations.  It depends largely on the processor, compiler and the moduli being used.
379
380Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern.  However,
381on the other side of the coin LibTomMath offers you a totally free (public domain) well structured math library
382that is very flexible, complete and performs well in resource constrained environments.  Fast RSA for example can
383be performed with as little as 8KB of ram for data (again depending on build options).
384
385\chapter{Getting Started with LibTomMath}
386\section{Building Programs}
387In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically
388libtommath.a).  There is no library initialization required and the entire library is thread safe.
389
390\section{Return Codes}
391There are three possible return codes a function may return.
392
393\index{MP\_OKAY}\index{MP\_YES}\index{MP\_NO}\index{MP\_VAL}\index{MP\_MEM}
394\begin{figure}[h!]
395\begin{center}
396\begin{small}
397\begin{tabular}{|l|l|}
398\hline \textbf{Code} & \textbf{Meaning} \\
399\hline MP\_OKAY & The function succeeded. \\
400\hline MP\_VAL  & The function input was invalid. \\
401\hline MP\_MEM  & Heap memory exhausted. \\
402\hline &\\
403\hline MP\_YES  & Response is yes. \\
404\hline MP\_NO   & Response is no. \\
405\hline
406\end{tabular}
407\end{small}
408\end{center}
409\caption{Return Codes}
410\end{figure}
411
412The last two codes listed are not actually ``return'ed'' by a function.  They are placed in an integer (the caller must
413provide the address of an integer it can store to) which the caller can access.  To convert one of the three return codes
414to a string use the following function.
415
416\index{mp\_error\_to\_string}
417\begin{alltt}
418char *mp_error_to_string(int code);
419\end{alltt}
420
421This will return a pointer to a string which describes the given error code.  It will not work for the return codes
422MP\_YES and MP\_NO.
423
424\section{Data Types}
425The basic ``multiple precision integer'' type is known as the ``mp\_int'' within LibTomMath.  This data type is used to
426organize all of the data required to manipulate the integer it represents.  Within LibTomMath it has been prototyped
427as the following.
428
429\index{mp\_int}
430\begin{alltt}
431typedef struct  \{
432    int used, alloc, sign;
433    mp_digit *dp;
434\} mp_int;
435\end{alltt}
436
437Where ``mp\_digit'' is a data type that represents individual digits of the integer.  By default, an mp\_digit is the
438ISO C ``unsigned long'' data type and each digit is $28-$bits long.  The mp\_digit type can be configured to suit other
439platforms by defining the appropriate macros.
440
441All LTM functions that use the mp\_int type will expect a pointer to mp\_int structure.  You must allocate memory to
442hold the structure itself by yourself (whether off stack or heap it doesn't matter).  The very first thing that must be
443done to use an mp\_int is that it must be initialized.
444
445\section{Function Organization}
446
447The arithmetic functions of the library are all organized to have the same style prototype.  That is source operands
448are passed on the left and the destination is on the right.  For instance,
449
450\begin{alltt}
451mp_add(&a, &b, &c);       /* c = a + b */
452mp_mul(&a, &a, &c);       /* c = a * a */
453mp_div(&a, &b, &c, &d);   /* c = [a/b], d = a mod b */
454\end{alltt}
455
456Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
457For instance,
458
459\begin{alltt}
460mp_add(&a, &b, &b);       /* b = a + b */
461mp_div(&a, &b, &a, &c);   /* a = [a/b], c = a mod b */
462\end{alltt}
463
464This allows operands to be re-used which can make programming simpler.
465
466\section{Initialization}
467\subsection{Single Initialization}
468A single mp\_int can be initialized with the ``mp\_init'' function.
469
470\index{mp\_init}
471\begin{alltt}
472int mp_init (mp_int * a);
473\end{alltt}
474
475This function expects a pointer to an mp\_int structure and will initialize the members of the structure so the mp\_int
476represents the default integer which is zero.  If the functions returns MP\_OKAY then the mp\_int is ready to be used
477by the other LibTomMath functions.
478
479\begin{small} \begin{alltt}
480int main(void)
481\{
482   mp_int number;
483   int result;
484
485   if ((result = mp_init(&number)) != MP_OKAY) \{
486      printf("Error initializing the number.  \%s",
487             mp_error_to_string(result));
488      return EXIT_FAILURE;
489   \}
490
491   /* use the number */
492
493   return EXIT_SUCCESS;
494\}
495\end{alltt} \end{small}
496
497\subsection{Single Free}
498When you are finished with an mp\_int it is ideal to return the heap it used back to the system.  The following function
499provides this functionality.
500
501\index{mp\_clear}
502\begin{alltt}
503void mp_clear (mp_int * a);
504\end{alltt}
505
506The function expects a pointer to a previously initialized mp\_int structure and frees the heap it uses.  It sets the
507pointer\footnote{The ``dp'' member.} within the mp\_int to \textbf{NULL} which is used to prevent double free situations.
508Is is legal to call mp\_clear() twice on the same mp\_int in a row.
509
510\begin{small} \begin{alltt}
511int main(void)
512\{
513   mp_int number;
514   int result;
515
516   if ((result = mp_init(&number)) != MP_OKAY) \{
517      printf("Error initializing the number.  \%s",
518             mp_error_to_string(result));
519      return EXIT_FAILURE;
520   \}
521
522   /* use the number */
523
524   /* We're done with it. */
525   mp_clear(&number);
526
527   return EXIT_SUCCESS;
528\}
529\end{alltt} \end{small}
530
531\subsection{Multiple Initializations}
532Certain algorithms require more than one large integer.  In these instances it is ideal to initialize all of the mp\_int
533variables in an ``all or nothing'' fashion.  That is, they are either all initialized successfully or they are all
534not initialized.
535
536The  mp\_init\_multi() function provides this functionality.
537
538\index{mp\_init\_multi} \index{mp\_clear\_multi}
539\begin{alltt}
540int mp_init_multi(mp_int *mp, ...);
541\end{alltt}
542
543It accepts a \textbf{NULL} terminated list of pointers to mp\_int structures.  It will attempt to initialize them all
544at once.  If the function returns MP\_OKAY then all of the mp\_int variables are ready to use, otherwise none of them
545are available for use.  A complementary mp\_clear\_multi() function allows multiple mp\_int variables to be free'd
546from the heap at the same time.
547
548\begin{small} \begin{alltt}
549int main(void)
550\{
551   mp_int num1, num2, num3;
552   int result;
553
554   if ((result = mp_init_multi(&num1,
555                               &num2,
556                               &num3, NULL)) != MP\_OKAY) \{
557      printf("Error initializing the numbers.  \%s",
558             mp_error_to_string(result));
559      return EXIT_FAILURE;
560   \}
561
562   /* use the numbers */
563
564   /* We're done with them. */
565   mp_clear_multi(&num1, &num2, &num3, NULL);
566
567   return EXIT_SUCCESS;
568\}
569\end{alltt} \end{small}
570
571\subsection{Other Initializers}
572To initialized and make a copy of an mp\_int the mp\_init\_copy() function has been provided.
573
574\index{mp\_init\_copy}
575\begin{alltt}
576int mp_init_copy (mp_int * a, mp_int * b);
577\end{alltt}
578
579This function will initialize $a$ and make it a copy of $b$ if all goes well.
580
581\begin{small} \begin{alltt}
582int main(void)
583\{
584   mp_int num1, num2;
585   int result;
586
587   /* initialize and do work on num1 ... */
588
589   /* We want a copy of num1 in num2 now */
590   if ((result = mp_init_copy(&num2, &num1)) != MP_OKAY) \{
591     printf("Error initializing the copy.  \%s",
592             mp_error_to_string(result));
593      return EXIT_FAILURE;
594   \}
595
596   /* now num2 is ready and contains a copy of num1 */
597
598   /* We're done with them. */
599   mp_clear_multi(&num1, &num2, NULL);
600
601   return EXIT_SUCCESS;
602\}
603\end{alltt} \end{small}
604
605Another less common initializer is mp\_init\_size() which allows the user to initialize an mp\_int with a given
606default number of digits.  By default, all initializers allocate \textbf{MP\_PREC} digits.  This function lets
607you override this behaviour.
608
609\index{mp\_init\_size}
610\begin{alltt}
611int mp_init_size (mp_int * a, int size);
612\end{alltt}
613
614The $size$ parameter must be greater than zero.  If the function succeeds the mp\_int $a$ will be initialized
615to have $size$ digits (which are all initially zero).
616
617\begin{small} \begin{alltt}
618int main(void)
619\{
620   mp_int number;
621   int result;
622
623   /* we need a 60-digit number */
624   if ((result = mp_init_size(&number, 60)) != MP_OKAY) \{
625      printf("Error initializing the number.  \%s",
626             mp_error_to_string(result));
627      return EXIT_FAILURE;
628   \}
629
630   /* use the number */
631
632   return EXIT_SUCCESS;
633\}
634\end{alltt} \end{small}
635
636\section{Maintenance Functions}
637\subsection{Clear Leading Zeros}
638
639This is used to ensure that leading zero digits are trimed and the leading "used" digit will be non-zero.
640It also fixes the sign if there are no more leading digits.
641
642\index{mp\_clamp}
643\begin{alltt}
644void mp_clamp(mp_int *a);
645\end{alltt}
646
647\subsection{Zero Out}
648
649This function will set the ``bigint'' to zeros without changing the amount of allocated memory.
650
651\index{mp\_zero}
652\begin{alltt}
653void mp_zero(mp_int *a);
654\end{alltt}
655
656
657\subsection{Reducing Memory Usage}
658When an mp\_int is in a state where it won't be changed again\footnote{A Diffie-Hellman modulus for instance.} excess
659digits can be removed to return memory to the heap with the mp\_shrink() function.
660
661\index{mp\_shrink}
662\begin{alltt}
663int mp_shrink (mp_int * a);
664\end{alltt}
665
666This will remove excess digits of the mp\_int $a$.  If the operation fails the mp\_int should be intact without the
667excess digits being removed.  Note that you can use a shrunk mp\_int in further computations, however, such operations
668will require heap operations which can be slow.  It is not ideal to shrink mp\_int variables that you will further
669modify in the system (unless you are seriously low on memory).
670
671\begin{small} \begin{alltt}
672int main(void)
673\{
674   mp_int number;
675   int result;
676
677   if ((result = mp_init(&number)) != MP_OKAY) \{
678      printf("Error initializing the number.  \%s",
679             mp_error_to_string(result));
680      return EXIT_FAILURE;
681   \}
682
683   /* use the number [e.g. pre-computation]  */
684
685   /* We're done with it for now. */
686   if ((result = mp_shrink(&number)) != MP_OKAY) \{
687      printf("Error shrinking the number.  \%s",
688             mp_error_to_string(result));
689      return EXIT_FAILURE;
690   \}
691
692   /* use it .... */
693
694
695   /* we're done with it. */
696   mp_clear(&number);
697
698   return EXIT_SUCCESS;
699\}
700\end{alltt} \end{small}
701
702\subsection{Adding additional digits}
703
704Within the mp\_int structure are two parameters which control the limitations of the array of digits that represent
705the integer the mp\_int is meant to equal.   The \textit{used} parameter dictates how many digits are significant, that is,
706contribute to the value of the mp\_int.  The \textit{alloc} parameter dictates how many digits are currently available in
707the array.  If you need to perform an operation that requires more digits you will have to mp\_grow() the mp\_int to
708your desired size.
709
710\index{mp\_grow}
711\begin{alltt}
712int mp_grow (mp_int * a, int size);
713\end{alltt}
714
715This will grow the array of digits of $a$ to $size$.  If the \textit{alloc} parameter is already bigger than
716$size$ the function will not do anything.
717
718\begin{small} \begin{alltt}
719int main(void)
720\{
721   mp_int number;
722   int result;
723
724   if ((result = mp_init(&number)) != MP_OKAY) \{
725      printf("Error initializing the number.  \%s",
726             mp_error_to_string(result));
727      return EXIT_FAILURE;
728   \}
729
730   /* use the number */
731
732   /* We need to add 20 digits to the number  */
733   if ((result = mp_grow(&number, number.alloc + 20)) != MP_OKAY) \{
734      printf("Error growing the number.  \%s",
735             mp_error_to_string(result));
736      return EXIT_FAILURE;
737   \}
738
739
740   /* use the number */
741
742   /* we're done with it. */
743   mp_clear(&number);
744
745   return EXIT_SUCCESS;
746\}
747\end{alltt} \end{small}
748
749\chapter{Basic Operations}
750\section{Copying}
751
752A so called ``deep copy'', where new memory is allocated and all contents of $a$ are copied verbatim into $b$ such that $b = a$ at the end.
753
754\index{mp\_copy}
755\begin{alltt}
756int mp_copy (mp_int * a, mp_int *b);
757\end{alltt}
758
759You can also just swap $a$ and $b$. It does the normal pointer changing with a temporary pointer variable, just that you do not have to.
760
761\index{mp\_exch}
762\begin{alltt}
763void mp_exch (mp_int * a, mp_int *b);
764\end{alltt}
765
766\section{Bit Counting}
767
768To get the position of the lowest bit set (LSB, the Lowest Significant Bit; the number of bits which are zero before the first zero bit )
769
770\index{mp\_cnt\_lsb}
771\begin{alltt}
772int mp_cnt_lsb(const mp_int *a);
773\end{alltt}
774
775To get the position of the highest bit set (MSB, the Most Significant Bit; the number of bits in teh ``bignum'')
776
777\index{mp\_count\_bits}
778\begin{alltt}
779int mp_count_bits(const mp_int *a);
780\end{alltt}
781
782
783\section{Small Constants}
784Setting mp\_ints to small constants is a relatively common operation.  To accommodate these instances there is a
785small constant assignment function.  This function is used to set a single digit constant.
786The reason for this function is efficiency.  Setting a single digit is quick but the
787domain of a digit can change (it's always at least $0 \ldots 127$).
788
789\subsection{Single Digit}
790
791Setting a single digit can be accomplished with the following function.
792
793\index{mp\_set}
794\begin{alltt}
795void mp_set (mp_int * a, mp_digit b);
796\end{alltt}
797
798This will zero the contents of $a$ and make it represent an integer equal to the value of $b$.  Note that this
799function has a return type of \textbf{void}.  It cannot cause an error so it is safe to assume the function
800succeeded.
801
802\begin{small} \begin{alltt}
803int main(void)
804\{
805   mp_int number;
806   int result;
807
808   if ((result = mp_init(&number)) != MP_OKAY) \{
809      printf("Error initializing the number.  \%s",
810             mp_error_to_string(result));
811      return EXIT_FAILURE;
812   \}
813
814   /* set the number to 5 */
815   mp_set(&number, 5);
816
817   /* we're done with it. */
818   mp_clear(&number);
819
820   return EXIT_SUCCESS;
821\}
822\end{alltt} \end{small}
823
824\subsection{Int32 and Int64 Constants}
825
826These functions can be used to set a constant with 32 or 64 bits.
827
828\index{mp\_set\_i32} \index{mp\_set\_u32}
829\index{mp\_set\_i64} \index{mp\_set\_u64}
830\begin{alltt}
831void mp_set_i32 (mp_int * a, int32_t b);
832void mp_set_u32 (mp_int * a, uint32_t b);
833void mp_set_i64 (mp_int * a, int64_t b);
834void mp_set_u64 (mp_int * a, uint64_t b);
835\end{alltt}
836
837These functions assign the sign and value of the input \texttt{b} to \texttt{mp\_int a}.
838The value can be obtained again by calling the following functions.
839
840\index{mp\_get\_i32} \index{mp\_get\_u32} \index{mp\_get\_mag\_u32}
841\index{mp\_get\_i64} \index{mp\_get\_u64} \index{mp\_get\_mag\_u64}
842\begin{alltt}
843int32_t mp_get_i32 (mp_int * a);
844uint32_t mp_get_u32 (mp_int * a);
845uint32_t mp_get_mag_u32 (mp_int * a);
846int64_t mp_get_i64 (mp_int * a);
847uint64_t mp_get_u64 (mp_int * a);
848uint64_t mp_get_mag_u64 (mp_int * a);
849\end{alltt}
850
851These functions return the 32 or 64 least significant bits of $a$ respectively. The unsigned functions
852return negative values in a twos complement representation. The absolute value or magnitude can be obtained using the mp\_get\_mag functions.
853
854\begin{small} \begin{alltt}
855int main(void)
856\{
857   mp_int number;
858   int result;
859
860   if ((result = mp_init(&number)) != MP_OKAY) \{
861      printf("Error initializing the number.  \%s",
862             mp_error_to_string(result));
863      return EXIT_FAILURE;
864   \}
865
866   /* set the number to 654321 (note this is bigger than 127) */
867   mp_set_u32(&number, 654321);
868
869   printf("number == \%" PRIi32, mp_get_i32(&number));
870
871   /* we're done with it. */
872   mp_clear(&number);
873
874   return EXIT_SUCCESS;
875\}
876\end{alltt} \end{small}
877
878This should output the following if the program succeeds.
879
880\begin{alltt}
881number == 654321
882\end{alltt}
883
884\subsection{Long Constants - platform dependant}
885
886\index{mp\_set\_l} \index{mp\_set\_ul}
887\begin{alltt}
888void mp_set_l (mp_int * a, long b);
889void mp_set_ul (mp_int * a, unsigned long b);
890\end{alltt}
891
892This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
893
894To retrieve the value, the following functions can be used.
895
896\index{mp\_get\_l} \index{mp\_get\_ul} \index{mp\_get\_mag\_ul}
897\begin{alltt}
898long mp_get_l (mp_int * a);
899unsigned long mp_get_ul (mp_int * a);
900unsigned long mp_get_mag_ul (mp_int * a);
901\end{alltt}
902
903This will return the least significant bits of the mp\_int $a$ that fit into a ``long''.
904
905\subsection{Long Long Constants - platform dependant}
906
907\index{mp\_set\_ll} \index{mp\_set\_ull}
908\begin{alltt}
909void mp_set_ll (mp_int * a, long long b);
910void mp_set_ull (mp_int * a, unsigned long long b);
911\end{alltt}
912
913This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
914
915To retrieve the value, the following functions can be used.
916
917\index{mp\_get\_ll}
918\index{mp\_get\_ull}
919\index{mp\_get\_mag\_ull}
920\begin{alltt}
921long long mp_get_ll (mp_int * a);
922unsigned long long mp_get_ull (mp_int * a);
923unsigned long long mp_get_mag_ull (mp_int * a);
924\end{alltt}
925
926This will return the least significant bits of the mp\_int $a$ that fit into a ``long long''.
927
928\subsection{Initialize and Setting Constants}
929To both initialize and set small constants the following two functions are available.
930\index{mp\_init\_set} \index{mp\_init\_set\_int}
931\begin{alltt}
932int mp_init_set (mp_int * a, mp_digit b);
933int mp_init_i32 (mp_int * a, int32_t b);
934int mp_init_u32 (mp_int * a, uint32_t b);
935int mp_init_i64 (mp_int * a, int64_t b);
936int mp_init_u64 (mp_int * a, uint64_t b);
937int mp_init_l   (mp_int * a, long b);
938int mp_init_ul  (mp_int * a, unsigned long b);
939int mp_init_ll  (mp_int * a, long long b);
940int mp_init_ull (mp_int * a, unsigned long long b);
941\end{alltt}
942
943Both functions work like the previous counterparts except they first mp\_init $a$ before setting the values.
944
945\begin{alltt}
946int main(void)
947\{
948   mp_int number1, number2;
949   int    result;
950
951   /* initialize and set a single digit */
952   if ((result = mp_init_set(&number1, 100)) != MP_OKAY) \{
953      printf("Error setting number1: \%s",
954             mp_error_to_string(result));
955      return EXIT_FAILURE;
956   \}
957
958   /* initialize and set a long */
959   if ((result = mp_init_l(&number2, 1023)) != MP_OKAY) \{
960      printf("Error setting number2: \%s",
961             mp_error_to_string(result));
962      return EXIT_FAILURE;
963   \}
964
965   /* display */
966   printf("Number1, Number2 == \%" PRIi32 ", \%" PRIi32,
967          mp_get_i32(&number1), mp_get_i32(&number2));
968
969   /* clear */
970   mp_clear_multi(&number1, &number2, NULL);
971
972   return EXIT_SUCCESS;
973\}
974\end{alltt}
975
976If this program succeeds it shall output.
977\begin{alltt}
978Number1, Number2 == 100, 1023
979\end{alltt}
980
981\section{Comparisons}
982
983Comparisons in LibTomMath are always performed in a ``left to right'' fashion.  There are three possible return codes
984for any comparison.
985
986\index{MP\_GT} \index{MP\_EQ} \index{MP\_LT}
987\begin{figure}[h]
988\begin{center}
989\begin{tabular}{|c|c|}
990\hline \textbf{Result Code} & \textbf{Meaning} \\
991\hline MP\_GT & $a > b$ \\
992\hline MP\_EQ & $a = b$ \\
993\hline MP\_LT & $a < b$ \\
994\hline
995\end{tabular}
996\end{center}
997\caption{Comparison Codes for $a, b$}
998\label{fig:CMP}
999\end{figure}
1000
1001In figure \ref{fig:CMP} two integers $a$ and $b$ are being compared.  In this case $a$ is said to be ``to the left'' of
1002$b$.
1003
1004\subsection{Unsigned comparison}
1005
1006An unsigned comparison considers only the digits themselves and not the associated \textit{sign} flag of the
1007mp\_int structures.  This is analogous to an absolute comparison.  The function mp\_cmp\_mag() will compare two
1008mp\_int variables based on their digits only.
1009
1010\index{mp\_cmp\_mag}
1011\begin{alltt}
1012int mp_cmp_mag(mp_int * a, mp_int * b);
1013\end{alltt}
1014This will compare $a$ to $b$ placing $a$ to the left of $b$.  This function cannot fail and will return one of the
1015three compare codes listed in figure \ref{fig:CMP}.
1016
1017\begin{small} \begin{alltt}
1018int main(void)
1019\{
1020   mp_int number1, number2;
1021   int result;
1022
1023   if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
1024      printf("Error initializing the numbers.  \%s",
1025             mp_error_to_string(result));
1026      return EXIT_FAILURE;
1027   \}
1028
1029   /* set the number1 to 5 */
1030   mp_set(&number1, 5);
1031
1032   /* set the number2 to -6 */
1033   mp_set(&number2, 6);
1034   if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
1035      printf("Error negating number2.  \%s",
1036             mp_error_to_string(result));
1037      return EXIT_FAILURE;
1038   \}
1039
1040   switch(mp_cmp_mag(&number1, &number2)) \{
1041       case MP_GT:  printf("|number1| > |number2|"); break;
1042       case MP_EQ:  printf("|number1| = |number2|"); break;
1043       case MP_LT:  printf("|number1| < |number2|"); break;
1044   \}
1045
1046   /* we're done with it. */
1047   mp_clear_multi(&number1, &number2, NULL);
1048
1049   return EXIT_SUCCESS;
1050\}
1051\end{alltt} \end{small}
1052
1053If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
1054successfully it should print the following.
1055
1056\begin{alltt}
1057|number1| < |number2|
1058\end{alltt}
1059
1060This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
1061
1062\subsection{Signed comparison}
1063
1064To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
1065
1066\index{mp\_cmp}
1067\begin{alltt}
1068int mp_cmp(mp_int * a, mp_int * b);
1069\end{alltt}
1070
1071This will compare $a$ to the left of $b$.  It will first compare the signs of the two mp\_int variables.  If they
1072differ it will return immediately based on their signs.  If the signs are equal then it will compare the digits
1073individually.  This function will return one of the compare conditions codes listed in figure \ref{fig:CMP}.
1074
1075\begin{small} \begin{alltt}
1076int main(void)
1077\{
1078   mp_int number1, number2;
1079   int result;
1080
1081   if ((result = mp_init_multi(&number1, &number2, NULL)) != MP_OKAY) \{
1082      printf("Error initializing the numbers.  \%s",
1083             mp_error_to_string(result));
1084      return EXIT_FAILURE;
1085   \}
1086
1087   /* set the number1 to 5 */
1088   mp_set(&number1, 5);
1089
1090   /* set the number2 to -6 */
1091   mp_set(&number2, 6);
1092   if ((result = mp_neg(&number2, &number2)) != MP_OKAY) \{
1093      printf("Error negating number2.  \%s",
1094             mp_error_to_string(result));
1095      return EXIT_FAILURE;
1096   \}
1097
1098   switch(mp_cmp(&number1, &number2)) \{
1099       case MP_GT:  printf("number1 > number2"); break;
1100       case MP_EQ:  printf("number1 = number2"); break;
1101       case MP_LT:  printf("number1 < number2"); break;
1102   \}
1103
1104   /* we're done with it. */
1105   mp_clear_multi(&number1, &number2, NULL);
1106
1107   return EXIT_SUCCESS;
1108\}
1109\end{alltt} \end{small}
1110
1111If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
1112successfully it should print the following.
1113
1114\begin{alltt}
1115number1 > number2
1116\end{alltt}
1117
1118\subsection{Single Digit}
1119
1120To compare a single digit against an mp\_int the following function has been provided.
1121
1122\index{mp\_cmp\_d}
1123\begin{alltt}
1124int mp_cmp_d(mp_int * a, mp_digit b);
1125\end{alltt}
1126
1127This will compare $a$ to the left of $b$ using a signed comparison.  Note that it will always treat $b$ as
1128positive.  This function is rather handy when you have to compare against small values such as $1$ (which often
1129comes up in cryptography).  The function cannot fail and will return one of the tree compare condition codes
1130listed in figure \ref{fig:CMP}.
1131
1132
1133\begin{small} \begin{alltt}
1134int main(void)
1135\{
1136   mp_int number;
1137   int result;
1138
1139   if ((result = mp_init(&number)) != MP_OKAY) \{
1140      printf("Error initializing the number.  \%s",
1141             mp_error_to_string(result));
1142      return EXIT_FAILURE;
1143   \}
1144
1145   /* set the number to 5 */
1146   mp_set(&number, 5);
1147
1148   switch(mp_cmp_d(&number, 7)) \{
1149       case MP_GT:  printf("number > 7"); break;
1150       case MP_EQ:  printf("number = 7"); break;
1151       case MP_LT:  printf("number < 7"); break;
1152   \}
1153
1154   /* we're done with it. */
1155   mp_clear(&number);
1156
1157   return EXIT_SUCCESS;
1158\}
1159\end{alltt} \end{small}
1160
1161If this program functions properly it will print out the following.
1162
1163\begin{alltt}
1164number < 7
1165\end{alltt}
1166
1167\section{Logical Operations}
1168
1169Logical operations are operations that can be performed either with simple shifts or boolean operators such as
1170AND, XOR and OR directly.  These operations are very quick.
1171
1172\subsection{Multiplication by two}
1173
1174Multiplications and divisions by any power of two can be performed with quick logical shifts either left or
1175right depending on the operation.
1176
1177When multiplying or dividing by two a special case routine can be used which are as follows.
1178\index{mp\_mul\_2} \index{mp\_div\_2}
1179\begin{alltt}
1180int mp_mul_2(mp_int * a, mp_int * b);
1181int mp_div_2(mp_int * a, mp_int * b);
1182\end{alltt}
1183
1184The former will assign twice $a$ to $b$ while the latter will assign half $a$ to $b$.  These functions are fast
1185since the shift counts and maskes are hardcoded into the routines.
1186
1187\begin{small} \begin{alltt}
1188int main(void)
1189\{
1190   mp_int number;
1191   int result;
1192
1193   if ((result = mp_init(&number)) != MP_OKAY) \{
1194      printf("Error initializing the number.  \%s",
1195             mp_error_to_string(result));
1196      return EXIT_FAILURE;
1197   \}
1198
1199   /* set the number to 5 */
1200   mp_set(&number, 5);
1201
1202   /* multiply by two */
1203   if ((result = mp\_mul\_2(&number, &number)) != MP_OKAY) \{
1204      printf("Error multiplying the number.  \%s",
1205             mp_error_to_string(result));
1206      return EXIT_FAILURE;
1207   \}
1208   switch(mp_cmp_d(&number, 7)) \{
1209       case MP_GT:  printf("2*number > 7"); break;
1210       case MP_EQ:  printf("2*number = 7"); break;
1211       case MP_LT:  printf("2*number < 7"); break;
1212   \}
1213
1214   /* now divide by two */
1215   if ((result = mp\_div\_2(&number, &number)) != MP_OKAY) \{
1216      printf("Error dividing the number.  \%s",
1217             mp_error_to_string(result));
1218      return EXIT_FAILURE;
1219   \}
1220   switch(mp_cmp_d(&number, 7)) \{
1221       case MP_GT:  printf("2*number/2 > 7"); break;
1222       case MP_EQ:  printf("2*number/2 = 7"); break;
1223       case MP_LT:  printf("2*number/2 < 7"); break;
1224   \}
1225
1226   /* we're done with it. */
1227   mp_clear(&number);
1228
1229   return EXIT_SUCCESS;
1230\}
1231\end{alltt} \end{small}
1232
1233If this program is successful it will print out the following text.
1234
1235\begin{alltt}
12362*number > 7
12372*number/2 < 7
1238\end{alltt}
1239
1240Since $10 > 7$ and $5 < 7$.
1241
1242To multiply by a power of two the following function can be used.
1243
1244\index{mp\_mul\_2d}
1245\begin{alltt}
1246int mp_mul_2d(mp_int * a, int b, mp_int * c);
1247\end{alltt}
1248
1249This will multiply $a$ by $2^b$ and store the result in ``c''.  If the value of $b$ is less than or equal to
1250zero the function will copy $a$ to ``c'' without performing any further actions.  The multiplication itself
1251is implemented as a right-shift operation of $a$ by $b$ bits.
1252
1253To divide by a power of two use the following.
1254
1255\index{mp\_div\_2d}
1256\begin{alltt}
1257int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d);
1258\end{alltt}
1259Which will divide $a$ by $2^b$, store the quotient in ``c'' and the remainder in ``d'.  If $b \le 0$ then the
1260function simply copies $a$ over to ``c'' and zeroes $d$.  The variable $d$ may be passed as a \textbf{NULL}
1261value to signal that the remainder is not desired.  The division itself is implemented as a left-shift
1262operation of $a$ by $b$ bits.
1263
1264It is also not very uncommon to need just the power of two $2^b$;  for example the startvalue for the Newton method.
1265
1266\index{mp\_2expt}
1267\begin{alltt}
1268int mp_2expt(mp_int *a, int b);
1269\end{alltt}
1270It is faster than doing it by shifting $1$ with \texttt{mp\_mul\_2d}.
1271
1272\subsection{Polynomial Basis Operations}
1273
1274Strictly speaking the organization of the integers within the mp\_int structures is what is known as a
1275``polynomial basis''.  This simply means a field element is stored by divisions of a radix.  For example, if
1276$f(x) = \sum_{i=0}^{k} y_ix^k$ for any vector $\vec y$ then the array of digits in $\vec y$ are said to be
1277the polynomial basis representation of $z$ if $f(\beta) = z$ for a given radix $\beta$.
1278
1279To multiply by the polynomial $g(x) = x$ all you have todo is shift the digits of the basis left one place.  The
1280following function provides this operation.
1281
1282\index{mp\_lshd}
1283\begin{alltt}
1284int mp_lshd (mp_int * a, int b);
1285\end{alltt}
1286
1287This will multiply $a$ in place by $x^b$ which is equivalent to shifting the digits left $b$ places and inserting zeroes
1288in the least significant digits.  Similarly to divide by a power of $x$ the following function is provided.
1289
1290\index{mp\_rshd}
1291\begin{alltt}
1292void mp_rshd (mp_int * a, int b)
1293\end{alltt}
1294This will divide $a$ in place by $x^b$ and discard the remainder.  This function cannot fail as it performs the operations
1295in place and no new digits are required to complete it.
1296
1297\subsection{AND, OR, XOR and COMPLEMENT Operations}
1298
1299While AND, OR and XOR operations compute arbitrary-precision bitwise operations. Negative numbers
1300are treated as if they are in two-complement representation, while internally they are sign-magnitude however.
1301
1302\index{mp\_or} \index{mp\_and} \index{mp\_xor} \index{mp\_complement}
1303\begin{alltt}
1304int mp_or  (mp_int * a, mp_int * b, mp_int * c);
1305int mp_and (mp_int * a, mp_int * b, mp_int * c);
1306int mp_xor (mp_int * a, mp_int * b, mp_int * c);
1307int mp_complement(const mp_int *a, mp_int *b);
1308int mp_signed_rsh(mp_int * a, int b, mp_int * c, mp_int * d);
1309\end{alltt}
1310
1311The function \texttt{mp\_complement} computes a two-complement $b = \sim a$. The function \texttt{mp\_signed\_rsh} performs
1312sign extending right shift. For positive numbers it is equivalent to \texttt{mp\_div\_2d}.
1313
1314\subsection{Bit Picking}
1315\index{mp\_get\_bit}
1316\begin{alltt}
1317int mp_get_bit(mp_int *a, int b)
1318\end{alltt}
1319
1320Pick a bit: returns \texttt{MP\_YES} if the bit at position $b$ (0-index) is set, that is if it is 1 (one), \texttt{MP\_NO}
1321if the bit is 0 (zero) and \texttt{MP\_VAL} if $b < 0$.
1322
1323\section{Addition and Subtraction}
1324
1325To compute an addition or subtraction the following two functions can be used.
1326
1327\index{mp\_add} \index{mp\_sub}
1328\begin{alltt}
1329int mp_add (mp_int * a, mp_int * b, mp_int * c);
1330int mp_sub (mp_int * a, mp_int * b, mp_int * c)
1331\end{alltt}
1332
1333Which perform $c = a \odot b$ where $\odot$ is one of signed addition or subtraction.  The operations are fully sign
1334aware.
1335
1336\section{Sign Manipulation}
1337\subsection{Negation}
1338\label{sec:NEG}
1339Simple integer negation can be performed with the following.
1340
1341\index{mp\_neg}
1342\begin{alltt}
1343int mp_neg (mp_int * a, mp_int * b);
1344\end{alltt}
1345
1346Which assigns $-a$ to $b$.
1347
1348\subsection{Absolute}
1349Simple integer absolutes can be performed with the following.
1350
1351\index{mp\_abs}
1352\begin{alltt}
1353int mp_abs (mp_int * a, mp_int * b);
1354\end{alltt}
1355
1356Which assigns $\vert a \vert$ to $b$.
1357
1358\section{Integer Division and Remainder}
1359To perform a complete and general integer division with remainder use the following function.
1360
1361\index{mp\_div}
1362\begin{alltt}
1363int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d);
1364\end{alltt}
1365
1366This divides $a$ by $b$ and stores the quotient in $c$ and $d$.  The signed quotient is computed such that
1367$bc + d = a$.  Note that either of $c$ or $d$ can be set to \textbf{NULL} if their value is not required.  If
1368$b$ is zero the function returns \textbf{MP\_VAL}.
1369
1370
1371\chapter{Multiplication and Squaring}
1372\section{Multiplication}
1373A full signed integer multiplication can be performed with the following.
1374\index{mp\_mul}
1375\begin{alltt}
1376int mp_mul (mp_int * a, mp_int * b, mp_int * c);
1377\end{alltt}
1378Which assigns the full signed product $ab$ to $c$.  This function actually breaks into one of four cases which are
1379specific multiplication routines optimized for given parameters.  First there are the Toom-Cook multiplications which
1380should only be used with very large inputs.  This is followed by the Karatsuba multiplications which are for moderate
1381sized inputs.  Then followed by the Comba and baseline multipliers.
1382
1383Fortunately for the developer you don't really need to know this unless you really want to fine tune the system.  mp\_mul()
1384will determine on its own\footnote{Some tweaking may be required but \texttt{make tune} will put some reasonable values in \texttt{bncore.c}} what routine to use automatically when it is called.
1385
1386\begin{alltt}
1387int main(void)
1388\{
1389   mp_int number1, number2;
1390   int result;
1391
1392   /* Initialize the numbers */
1393   if ((result = mp_init_multi(&number1,
1394                               &number2, NULL)) != MP_OKAY) \{
1395      printf("Error initializing the numbers.  \%s",
1396             mp_error_to_string(result));
1397      return EXIT_FAILURE;
1398   \}
1399
1400   /* set the terms */
1401   mp_set_i32(&number, 257);
1402   mp_set_i32(&number2, 1023);
1403
1404   /* multiply them */
1405   if ((result = mp_mul(&number1, &number2,
1406                        &number1)) != MP_OKAY) \{
1407      printf("Error multiplying terms.  \%s",
1408             mp_error_to_string(result));
1409      return EXIT_FAILURE;
1410   \}
1411
1412   /* display */
1413   printf("number1 * number2 == \%" PRIi32, mp_get_i32(&number1));
1414
1415   /* free terms and return */
1416   mp_clear_multi(&number1, &number2, NULL);
1417
1418   return EXIT_SUCCESS;
1419\}
1420\end{alltt}
1421
1422If this program succeeds it shall output the following.
1423
1424\begin{alltt}
1425number1 * number2 == 262911
1426\end{alltt}
1427
1428\section{Squaring}
1429Since squaring can be performed faster than multiplication it is performed it's own function instead of just using
1430mp\_mul().
1431
1432\index{mp\_sqr}
1433\begin{alltt}
1434int mp_sqr (mp_int * a, mp_int * b);
1435\end{alltt}
1436
1437Will square $a$ and store it in $b$.  Like the case of multiplication there are four different squaring
1438algorithms all which can be called from mp\_sqr().  It is ideal to use mp\_sqr over mp\_mul when squaring terms because
1439of the speed difference.
1440
1441\section{Tuning Polynomial Basis Routines}
1442
1443Both of the Toom-Cook and Karatsuba multiplication algorithms are faster than the traditional $O(n^2)$ approach that
1444the Comba and baseline algorithms use.  At $O(n^{1.464973})$ and $O(n^{1.584962})$ running times respectively they require
1445considerably less work.  For example, a 10000-digit multiplication would take roughly 724,000 single precision
1446multiplications with Toom-Cook or 100,000,000 single precision multiplications with the standard Comba (a factor
1447of 138).
1448
1449So why not always use Karatsuba or Toom-Cook?   The simple answer is that they have so much overhead that they're not
1450actually faster than Comba until you hit distinct  ``cutoff'' points.  For Karatsuba with the default configuration,
1451GCC 3.3.1 and an Athlon XP processor the cutoff point is roughly 110 digits (about 70 for the Intel P4).  That is, at
1452110 digits Karatsuba and Comba multiplications just about break even and for 110+ digits Karatsuba is faster.
1453
1454Toom-Cook has incredible overhead and is probably only useful for very large inputs.  So far no known cutoff points
1455exist and for the most part I just set the cutoff points very high to make sure they're not called.
1456
1457To get reasonable values for the cut-off points for your architecture, type
1458
1459\begin{alltt}
1460make tune
1461\end{alltt}
1462
1463This will run a benchmark, computes the medians, rewrites \texttt{bncore.c}, and recompiles \texttt{bncore.c} and relinks the library.
1464
1465The benchmark itself can be fine-tuned in the file \texttt{etc/tune\_it.sh}.
1466
1467The program \texttt{etc/tune} is also able to print a list of values for printing curves with e.g.: \texttt{gnuplot}. type \texttt{./etc/tune -h} to get a list of all available options.
1468
1469\chapter{Modular Reduction}
1470
1471Modular reduction is process of taking the remainder of one quantity divided by another.  Expressed
1472as (\ref{eqn:mod}) the modular reduction is equivalent to the remainder of $b$ divided by $c$.
1473
1474\begin{equation}
1475a \equiv b \mbox{ (mod }c\mbox{)}
1476\label{eqn:mod}
1477\end{equation}
1478
1479Of particular interest to cryptography are reductions where $b$ is limited to the range $0 \le b < c^2$ since particularly
1480fast reduction algorithms can be written for the limited range.
1481
1482Note that one of the four optimized reduction algorithms are automatically chosen in the modular exponentiation
1483algorithm mp\_exptmod when an appropriate modulus is detected.
1484
1485\section{Straight Division}
1486In order to effect an arbitrary modular reduction the following algorithm is provided.
1487
1488\index{mp\_mod}
1489\begin{alltt}
1490int mp_mod(mp_int *a, mp_int *b, mp_int *c);
1491\end{alltt}
1492
1493This reduces $a$ modulo $b$ and stores the result in $c$.  The sign of $c$ shall agree with the sign
1494of $b$.  This algorithm accepts an input $a$ of any range and is not limited by $0 \le a < b^2$.
1495
1496\section{Barrett Reduction}
1497
1498Barrett reduction is a generic optimized reduction algorithm that requires pre--computation to achieve
1499a decent speedup over straight division.  First a $\mu$ value must be precomputed with the following function.
1500
1501\index{mp\_reduce\_setup}
1502\begin{alltt}
1503int mp_reduce_setup(mp_int *a, mp_int *b);
1504\end{alltt}
1505
1506Given a modulus in $b$ this produces the required $\mu$ value in $a$.  For any given modulus this only has to
1507be computed once.  Modular reduction can now be performed with the following.
1508
1509\index{mp\_reduce}
1510\begin{alltt}
1511int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
1512\end{alltt}
1513
1514This will reduce $a$ in place modulo $b$ with the precomputed $\mu$ value in $c$.  $a$ must be in the range
1515$0 \le a < b^2$.
1516
1517\begin{alltt}
1518int main(void)
1519\{
1520   mp_int   a, b, c, mu;
1521   int      result;
1522
1523   /* initialize a,b to desired values, mp_init mu,
1524    * c and set c to 1...we want to compute a^3 mod b
1525    */
1526
1527   /* get mu value */
1528   if ((result = mp_reduce_setup(&mu, b)) != MP_OKAY) \{
1529      printf("Error getting mu.  \%s",
1530             mp_error_to_string(result));
1531      return EXIT_FAILURE;
1532   \}
1533
1534   /* square a to get c = a^2 */
1535   if ((result = mp_sqr(&a, &c)) != MP_OKAY) \{
1536      printf("Error squaring.  \%s",
1537             mp_error_to_string(result));
1538      return EXIT_FAILURE;
1539   \}
1540
1541   /* now reduce `c' modulo b */
1542   if ((result = mp_reduce(&c, &b, &mu)) != MP_OKAY) \{
1543      printf("Error reducing.  \%s",
1544             mp_error_to_string(result));
1545      return EXIT_FAILURE;
1546   \}
1547
1548   /* multiply a to get c = a^3 */
1549   if ((result = mp_mul(&a, &c, &c)) != MP_OKAY) \{
1550      printf("Error reducing.  \%s",
1551             mp_error_to_string(result));
1552      return EXIT_FAILURE;
1553   \}
1554
1555   /* now reduce `c' modulo b  */
1556   if ((result = mp_reduce(&c, &b, &mu)) != MP_OKAY) \{
1557      printf("Error reducing.  \%s",
1558             mp_error_to_string(result));
1559      return EXIT_FAILURE;
1560   \}
1561
1562   /* c now equals a^3 mod b */
1563
1564   return EXIT_SUCCESS;
1565\}
1566\end{alltt}
1567
1568This program will calculate $a^3 \mbox{ mod }b$ if all the functions succeed.
1569
1570\section{Montgomery Reduction}
1571
1572Montgomery is a specialized reduction algorithm for any odd moduli.  Like Barrett reduction a pre--computation
1573step is required.  This is accomplished with the following.
1574
1575\index{mp\_montgomery\_setup}
1576\begin{alltt}
1577int mp_montgomery_setup(mp_int *a, mp_digit *mp);
1578\end{alltt}
1579
1580For the given odd moduli $a$ the precomputation value is placed in $mp$.  The reduction is computed with the
1581following.
1582
1583\index{mp\_montgomery\_reduce}
1584\begin{alltt}
1585int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
1586\end{alltt}
1587This reduces $a$ in place modulo $m$ with the pre--computed value $mp$.   $a$ must be in the range
1588$0 \le a < b^2$.
1589
1590Montgomery reduction is faster than Barrett reduction for moduli smaller than the ``comba'' limit.  With the default
1591setup for instance, the limit is $127$ digits ($3556$--bits).   Note that this function is not limited to
1592$127$ digits just that it falls back to a baseline algorithm after that point.
1593
1594An important observation is that this reduction does not return $a \mbox{ mod }m$ but $aR^{-1} \mbox{ mod }m$
1595where $R = \beta^n$, $n$ is the n number of digits in $m$ and $\beta$ is radix used (default is $2^{28}$).
1596
1597To quickly calculate $R$ the following function was provided.
1598
1599\index{mp\_montgomery\_calc\_normalization}
1600\begin{alltt}
1601int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
1602\end{alltt}
1603Which calculates $a = R$ for the odd moduli $b$ without using multiplication or division.
1604
1605The normal modus operandi for Montgomery reductions is to normalize the integers before entering the system.  For
1606example, to calculate $a^3 \mbox { mod }b$ using Montgomery reduction the value of $a$ can be normalized by
1607multiplying it by $R$.  Consider the following code snippet.
1608
1609\begin{alltt}
1610int main(void)
1611\{
1612   mp_int   a, b, c, R;
1613   mp_digit mp;
1614   int      result;
1615
1616   /* initialize a,b to desired values,
1617    * mp_init R, c and set c to 1....
1618    */
1619
1620   /* get normalization */
1621   if ((result = mp_montgomery_calc_normalization(&R, b)) != MP_OKAY) \{
1622      printf("Error getting norm.  \%s",
1623             mp_error_to_string(result));
1624      return EXIT_FAILURE;
1625   \}
1626
1627   /* get mp value */
1628   if ((result = mp_montgomery_setup(&c, &mp)) != MP_OKAY) \{
1629      printf("Error setting up montgomery.  \%s",
1630             mp_error_to_string(result));
1631      return EXIT_FAILURE;
1632   \}
1633
1634   /* normalize `a' so now a is equal to aR */
1635   if ((result = mp_mulmod(&a, &R, &b, &a)) != MP_OKAY) \{
1636      printf("Error computing aR.  \%s",
1637             mp_error_to_string(result));
1638      return EXIT_FAILURE;
1639   \}
1640
1641   /* square a to get c = a^2R^2 */
1642   if ((result = mp_sqr(&a, &c)) != MP_OKAY) \{
1643      printf("Error squaring.  \%s",
1644             mp_error_to_string(result));
1645      return EXIT_FAILURE;
1646   \}
1647
1648   /* now reduce `c' back down to c = a^2R^2 * R^-1 == a^2R */
1649   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
1650      printf("Error reducing.  \%s",
1651             mp_error_to_string(result));
1652      return EXIT_FAILURE;
1653   \}
1654
1655   /* multiply a to get c = a^3R^2 */
1656   if ((result = mp_mul(&a, &c, &c)) != MP_OKAY) \{
1657      printf("Error reducing.  \%s",
1658             mp_error_to_string(result));
1659      return EXIT_FAILURE;
1660   \}
1661
1662   /* now reduce `c' back down to c = a^3R^2 * R^-1 == a^3R */
1663   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
1664      printf("Error reducing.  \%s",
1665             mp_error_to_string(result));
1666      return EXIT_FAILURE;
1667   \}
1668
1669   /* now reduce (again) `c' back down to c = a^3R * R^-1 == a^3 */
1670   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) \{
1671      printf("Error reducing.  \%s",
1672             mp_error_to_string(result));
1673      return EXIT_FAILURE;
1674   \}
1675
1676   /* c now equals a^3 mod b */
1677
1678   return EXIT_SUCCESS;
1679\}
1680\end{alltt}
1681
1682This particular example does not look too efficient but it demonstrates the point of the algorithm.  By
1683normalizing the inputs the reduced results are always of the form $aR$ for some variable $a$.  This allows
1684a single final reduction to correct for the normalization and the fast reduction used within the algorithm.
1685
1686For more details consider examining the file \textit{bn\_mp\_exptmod\_fast.c}.
1687
1688\section{Restricted Diminished Radix}
1689
1690``Diminished Radix'' reduction refers to reduction with respect to moduli that are amenable to simple
1691digit shifting and small multiplications.  In this case the ``restricted'' variant refers to moduli of the
1692form $\beta^k - p$ for some $k \ge 0$ and $0 < p < \beta$ where $\beta$ is the radix (default to $2^{28}$).
1693
1694As in the case of Montgomery reduction there is a pre--computation phase required for a given modulus.
1695
1696\index{mp\_dr\_setup}
1697\begin{alltt}
1698void mp_dr_setup(mp_int *a, mp_digit *d);
1699\end{alltt}
1700
1701This computes the value required for the modulus $a$ and stores it in $d$.  This function cannot fail
1702and does not return any error codes.  After the pre--computation a reduction can be performed with the
1703following.
1704
1705\index{mp\_dr\_reduce}
1706\begin{alltt}
1707int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
1708\end{alltt}
1709
1710This reduces $a$ in place modulo $b$ with the pre--computed value $mp$.  $b$ must be of a restricted
1711diminished radix form and $a$ must be in the range $0 \le a < b^2$.  Diminished radix reductions are
1712much faster than both Barrett and Montgomery reductions as they have a much lower asymptotic running time.
1713
1714Since the moduli are restricted this algorithm is not particularly useful for something like Rabin, RSA or
1715BBS cryptographic purposes.  This reduction algorithm is useful for Diffie-Hellman and ECC where fixed
1716primes are acceptable.
1717
1718Note that unlike Montgomery reduction there is no normalization process.  The result of this function is
1719equal to the correct residue.
1720
1721\section{Unrestricted Diminished Radix}
1722
1723Unrestricted reductions work much like the restricted counterparts except in this case the moduli is of the
1724form $2^k - p$ for $0 < p < \beta$.  In this sense the unrestricted reductions are more flexible as they
1725can be applied to a wider range of numbers.
1726
1727\index{mp\_reduce\_2k\_setup}
1728\begin{alltt}
1729int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
1730\end{alltt}
1731
1732This will compute the required $d$ value for the given moduli $a$.
1733
1734\index{mp\_reduce\_2k}
1735\begin{alltt}
1736int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
1737\end{alltt}
1738
1739This will reduce $a$ in place modulo $n$ with the pre--computed value $d$.  From my experience this routine is
1740slower than mp\_dr\_reduce but faster for most moduli sizes than the Montgomery reduction.
1741
1742\section{Combined Modular Reduction}
1743
1744Some of the combinations of an arithmetic operations followed by a modular reduction can be done in a faster way. The ones implemented are:
1745
1746Addition $d = (a + b) \mod c$
1747\index{mp\_addmod}
1748\begin{alltt}
1749int mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1750\end{alltt}
1751
1752Subtraction  $d = (a - b) \mod c$
1753\begin{alltt}
1754int mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1755\end{alltt}
1756
1757Multiplication $d = (ab) \mod c$
1758\begin{alltt}
1759int mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1760\end{alltt}
1761
1762Squaring  $d = (a^2) \mod c$
1763\begin{alltt}
1764int mp_sqrmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1765\end{alltt}
1766
1767
1768
1769\chapter{Exponentiation}
1770\section{Single Digit Exponentiation}
1771\index{mp\_expt\_d}
1772\begin{alltt}
1773int mp_expt_d (mp_int * a, mp_digit b, mp_int * c)
1774\end{alltt}
1775This function computes $c = a^b$.
1776
1777\section{Modular Exponentiation}
1778\index{mp\_exptmod}
1779\begin{alltt}
1780int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
1781\end{alltt}
1782This computes $Y \equiv G^X \mbox{ (mod }P\mbox{)}$ using a variable width sliding window algorithm.  This function
1783will automatically detect the fastest modular reduction technique to use during the operation.  For negative values of
1784$X$ the operation is performed as $Y \equiv (G^{-1} \mbox{ mod }P)^{\vert X \vert} \mbox{ (mod }P\mbox{)}$ provided that
1785$gcd(G, P) = 1$.
1786
1787This function is actually a shell around the two internal exponentiation functions.  This routine will automatically
1788detect when Barrett, Montgomery, Restricted and Unrestricted Diminished Radix based exponentiation can be used.  Generally
1789moduli of the a ``restricted diminished radix'' form lead to the fastest modular exponentiations.  Followed by Montgomery
1790and the other two algorithms.
1791
1792\section{Modulus a Power of Two}
1793\index{mp\_mod\_2d}
1794\begin{alltt}
1795int mp_mod_2d(const mp_int *a, int b, mp_int *c)
1796\end{alltt}
1797It calculates $c = a \mod 2^b$.
1798
1799\section{Root Finding}
1800\index{mp\_n\_root}
1801\begin{alltt}
1802int mp_n_root (mp_int * a, mp_digit b, mp_int * c)
1803\end{alltt}
1804This computes $c = a^{1/b}$ such that $c^b \le a$ and $(c+1)^b > a$. Will return a positive root only for even roots and return
1805a root with the sign of the input for odd roots.  For example, performing $4^{1/2}$ will return $2$ whereas $(-8)^{1/3}$
1806will return $-2$.
1807
1808This algorithm uses the ``Newton Approximation'' method and will converge on the correct root fairly quickly.
1809
1810The square root  $c = a^{1/2}$ (with the same conditions $c^2 \le a$ and $(c+1)^2 > a$) is implemented with a faster algorithm.
1811
1812\index{mp\_sqrt}
1813\begin{alltt}
1814int mp_sqrt (mp_int * a, mp_digit b, mp_int * c)
1815\end{alltt}
1816
1817
1818\chapter{Logarithm}
1819\section{Integer Logarithm}
1820A logarithm function for positive integer input \texttt{a, base} computing  $\floor{\log_bx}$ such that $(\log_b x)^b \le x$.
1821\index{mp\_ilogb}
1822\begin{alltt}
1823int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
1824\end{alltt}
1825\subsection{Example}
1826\begin{alltt}
1827#include <stdlib.h>
1828#include <stdio.h>
1829#include <errno.h>
1830
1831#include <tommath.h>
1832
1833int main(int argc, char **argv)
1834{
1835   mp_int x, output;
1836   mp_digit base;
1837   int e;
1838
1839   if (argc != 3) {
1840      fprintf(stderr,"Usage %s base x\textbackslash{}n", argv[0]);
1841      exit(EXIT_FAILURE);
1842   }
1843   if ((e = mp_init_multi(&x, &output, NULL)) != MP_OKAY) {
1844      fprintf(stderr,"mp_init failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
1845                     mp_error_to_string(e));
1846              exit(EXIT_FAILURE);
1847   }
1848   errno = 0;
1849#ifdef MP_64BIT
1850   base = (mp_digit)strtoull(argv[1], NULL, 10);
1851#else
1852   base = (mp_digit)strtoul(argv[1], NULL, 10);
1853#endif
1854   if ((errno == ERANGE) || (base > (base & MP_MASK))) {
1855      fprintf(stderr,"strtoul(l) failed: input out of range\textbackslash{}n");
1856      exit(EXIT_FAILURE);
1857   }
1858   if ((e = mp_read_radix(&x, argv[2], 10)) != MP_OKAY) {
1859      fprintf(stderr,"mp_read_radix failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
1860                      mp_error_to_string(e));
1861      exit(EXIT_FAILURE);
1862   }
1863   if ((e = mp_ilogb(&x, base, &output)) != MP_OKAY) {
1864      fprintf(stderr,"mp_ilogb failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
1865                      mp_error_to_string(e));
1866      exit(EXIT_FAILURE);
1867   }
1868
1869   if ((e = mp_fwrite(&output, 10, stdout)) != MP_OKAY) {
1870      fprintf(stderr,"mp_fwrite failed: \textbackslash{}"%s\textbackslash{}"\textbackslash{}n",
1871                      mp_error_to_string(e));
1872      exit(EXIT_FAILURE);
1873   }
1874   putchar('\textbackslash{}n');
1875
1876   mp_clear_multi(&x, &output, NULL);
1877   exit(EXIT_SUCCESS);
1878}
1879\end{alltt}
1880
1881
1882
1883\chapter{Prime Numbers}
1884\section{Trial Division}
1885\index{mp\_prime\_is\_divisible}
1886\begin{alltt}
1887int mp_prime_is_divisible (mp_int * a, int *result)
1888\end{alltt}
1889This will attempt to evenly divide $a$ by a list of primes\footnote{Default is the first 256 primes.} and store the
1890outcome in ``result''.  That is if $result = 0$ then $a$ is not divisible by the primes, otherwise it is.  Note that
1891if the function does not return \textbf{MP\_OKAY} the value in ``result'' should be considered undefined\footnote{Currently
1892the default is to set it to zero first.}.
1893
1894\section{Fermat Test}
1895\index{mp\_prime\_fermat}
1896\begin{alltt}
1897int mp_prime_fermat (mp_int * a, mp_int * b, int *result)
1898\end{alltt}
1899Performs a Fermat primality test to the base $b$.  That is it computes $b^a \mbox{ mod }a$ and tests whether the value is
1900equal to $b$ or not.  If the values are equal then $a$ is probably prime and $result$ is set to one.  Otherwise $result$
1901is set to zero.
1902
1903\section{Miller-Rabin Test}
1904\index{mp\_prime\_miller\_rabin}
1905\begin{alltt}
1906int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
1907\end{alltt}
1908Performs a Miller-Rabin test to the base $b$ of $a$.  This test is much stronger than the Fermat test and is very hard to
1909fool (besides with Carmichael numbers).  If $a$ passes the test (therefore is probably prime) $result$ is set to one.
1910Otherwise $result$ is set to zero.
1911
1912Note that is suggested that you use the Miller-Rabin test instead of the Fermat test since all of the failures of
1913Miller-Rabin are a subset of the failures of the Fermat test.
1914
1915\subsection{Required Number of Tests}
1916Generally to ensure a number is very likely to be prime you have to perform the Miller-Rabin with at least a half-dozen
1917or so unique bases.  However, it has been proven that the probability of failure goes down as the size of the input goes up.
1918This is why a simple function has been provided to help out.
1919
1920\index{mp\_prime\_rabin\_miller\_trials}
1921\begin{alltt}
1922int mp_prime_rabin_miller_trials(int size)
1923\end{alltt}
1924This returns the number of trials required for a low probability of failure for a given ``size'' expressed in bits.  This comes in handy specially since larger numbers are slower to test. For example, a 512-bit number would require 18 tests for a probability of $2^{-160}$ whereas a 1024-bit number would only require 12 tests for a probability of $2^{-192}$. The exact values as implemented are listed in table \ref{table:millerrabinrunsimpl}.
1925
1926\begin{table}[h]
1927\begin{center}
1928\begin{tabular}{c c c}
1929\textbf{bits} & \textbf{Rounds} & \textbf{Error}\\
1930 80 & -1  &  Use deterministic algorithm for size <= 80 bits \\
1931 81 & 37  &  $2^{-96}$ \\
1932 96 & 32  & $2^{-96}$ \\
1933 128 & 40  & $2^{-112}$ \\
1934 160 & 35  & $2^{-112}$ \\
1935 256 & 27  & $2^{-128}$ \\
1936 384 & 16  & $2^{-128}$ \\
1937 512 & 18  & $2^{-160}$ \\
1938 768 & 11  & $2^{-160}$ \\
1939 896 & 10  & $2^{-160}$ \\
1940 1024 & 12  & $2^{-192}$ \\
1941 1536 & 8   & $2^{-192}$ \\
1942 2048 & 6   & $2^{-192}$ \\
1943 3072 & 4   & $2^{-192}$ \\
1944 4096 & 5   & $2^{-256}$ \\
1945 5120 & 4   & $2^{-256}$ \\
1946 6144 & 4   & $2^{-256}$ \\
1947 8192 & 3   & $2^{-256}$ \\
1948 9216 & 3   & $2^{-256}$ \\
1949 10240 & 2  & $2^{-256}$
1950\end{tabular}
1951\caption{ Number of Miller-Rabin rounds as implemented } \label{table:millerrabinrunsimpl}
1952\end{center}
1953\end{table}
1954
1955You should always still perform a trial division before a Miller-Rabin test though.
1956
1957A small table, broke in two for typographical reasons, with the number of rounds of Miller-Rabin tests is shown below. The numbers have been compute with a PARI/GP script listed in appendix \ref{app:numberofmrcomp}.
1958The first column is the number of bits $b$ in the prime $p = 2^b$, the numbers in the first row represent the
1959probability that the number that all of the Miller-Rabin tests deemed a pseudoprime is actually a composite. There is a deterministic test for numbers smaller than $2^{80}$.
1960
1961\begin{table}[h]
1962\begin{center}
1963\begin{tabular}{c c c c c c c}
1964\textbf{bits} & $\mathbf{2^{-80}}$ & $\mathbf{2^{-96}}$ & $\mathbf{2^{-112}}$ & $\mathbf{2^{-128}}$ & $\mathbf{2^{-160}}$ & $\mathbf{2^{-192}}$ \\
196580    & 31 & 39 & 47 & 55 & 71 & 87  \\
196696    & 29 & 37 & 45 & 53 & 69 & 85  \\
1967128   & 24 & 32 & 40 & 48 & 64 & 80  \\
1968160   & 19 & 27 & 35 & 43 & 59 & 75  \\
1969192   & 15 & 21 & 29 & 37 & 53 & 69  \\
1970256   & 10 & 15 & 20 & 27 & 43 & 59  \\
1971384   & 7  & 9  & 12 & 16 & 25 & 38  \\
1972512   & 5  & 7  & 9  & 12 & 18 & 26  \\
1973768   & 4  & 5  & 6  & 8  & 11 & 16  \\
19741024  & 3  & 4  & 5  & 6  & 9  & 12  \\
19751536  & 2  & 3  & 3  & 4  & 6  & 8   \\
19762048  & 2  & 2  & 3  & 3  & 4  & 6   \\
19773072  & 1  & 2  & 2  & 2  & 3  & 4   \\
19784096  & 1  & 1  & 2  & 2  & 2  & 3   \\
19796144  & 1  & 1  & 1  & 1  & 2  & 2   \\
19808192  & 1  & 1  & 1  & 1  & 2  & 2   \\
198112288 & 1  & 1  & 1  & 1  & 1  & 1   \\
198216384 & 1  & 1  & 1  & 1  & 1  & 1   \\
198324576 & 1  & 1  & 1  & 1  & 1  & 1   \\
198432768 & 1  & 1  & 1  & 1  & 1  & 1
1985\end{tabular}
1986\caption{ Number of Miller-Rabin rounds. Part I } \label{table:millerrabinrunsp1}
1987\end{center}
1988\end{table}
1989\newpage
1990\begin{table}[h]
1991\begin{center}
1992\begin{tabular}{c c c c c c c c}
1993\textbf{bits} &$\mathbf{2^{-224}}$ & $\mathbf{2^{-256}}$ & $\mathbf{2^{-288}}$ & $\mathbf{2^{-320}}$ & $\mathbf{2^{-352}}$ & $\mathbf{2^{-384}}$ & $\mathbf{2^{-416}}$\\
199480    & 103 & 119 & 135 & 151 & 167 & 183 & 199 \\
199596    & 101 & 117 & 133 & 149 & 165 & 181 & 197 \\
1996128   & 96  & 112 & 128 & 144 & 160 & 176 & 192 \\
1997160   & 91  & 107 & 123 & 139 & 155 & 171 & 187 \\
1998192   & 85  & 101 & 117 & 133 & 149 & 165 & 181 \\
1999256   & 75  & 91  & 107 & 123 & 139 & 155 & 171 \\
2000384   & 54  & 70  & 86  & 102 & 118 & 134 & 150 \\
2001512   & 36  & 49  & 65  & 81  & 97  & 113 & 129 \\
2002768   & 22  & 29  & 37  & 47  & 58  & 70  & 86  \\
20031024  & 16  & 21  & 26  & 33  & 40  & 48  & 58  \\
20041536  & 10  & 13  & 17  & 21  & 25  & 30  & 35  \\
20052048  & 8   & 10  & 13  & 15  & 18  & 22  & 26  \\
20063072  & 5   & 7   & 8	& 10  & 12  & 14  & 17  \\
20074096  & 4   & 5   & 6	& 8   & 9   & 11  & 12  \\
20086144  & 3   & 4   & 4	& 5   & 6   & 7   & 8	\\
20098192  & 2   & 3   & 3	& 4   & 5   & 6   & 6	\\
201012288 & 2   & 2   & 2	& 3   & 3   & 4   & 4	\\
201116384 & 1   & 2   & 2	& 2   & 3   & 3   & 3	\\
201224576 & 1   & 1   & 2	& 2   & 2   & 2   & 2	\\
201332768 & 1   & 1   & 1	& 1   & 2   & 2   & 2
2014\end{tabular}
2015\caption{ Number of Miller-Rabin rounds. Part II } \label{table:millerrabinrunsp2}
2016\end{center}
2017\end{table}
2018
2019Determining the probability needed to pick the right column is a bit harder. Fips 186.4, for example has $2^{-80}$ for $512$ bit large numbers, $2^{-112}$ for $1024$ bits, and $2^{128}$ for $1536$ bits. It can be seen in table \ref{table:millerrabinrunsp1} that those combinations follow the diagonal from $(512,2^{-80})$ downwards and to the right to gain a lower probabilty of getting a composite declared a pseudoprime for the same amount of work or less.
2020
2021If this version of the library has the strong Lucas-Selfridge and/or the Frobenius-Underwood test implemented only one or two rounds of the Miller-Rabin test with a random base is necesssary for numbers larger than or equal to $1024$ bits.
2022
2023This function is meant for RSA. The number of rounds for DSA is $\lceil -log_2(p)/2\rceil$ with $p$ the probability which is just the half of the absolute value of $p$ if given as a power of two. E.g.: with $p = 2^{-128}$, $\lceil -log_2(p)/2\rceil = 64$.
2024
2025This function can be used to test a DSA prime directly if these rounds are followed by a Lucas test.
2026
2027See also table C.1 in FIPS 186-4.
2028
2029\section{Strong Lucas-Selfridge Test}
2030\index{mp\_prime\_strong\_lucas\_selfridge}
2031\begin{alltt}
2032int mp_prime_strong_lucas_selfridge(const mp_int *a, int *result)
2033\end{alltt}
2034Performs a strong Lucas-Selfridge test. The strong Lucas-Selfridge test together with the Rabin-Miler test with bases $2$ and $3$ resemble the BPSW test. The single internal use is a compile-time option in \texttt{mp\_prime\_is\_prime} and can be excluded
2035from the Libtommath build if not needed.
2036
2037\section{Frobenius (Underwood)  Test}
2038\index{mp\_prime\_frobenius\_underwood}
2039\begin{alltt}
2040int mp_prime_frobenius_underwood(const mp_int *N, int *result)
2041\end{alltt}
2042Performs the variant of the Frobenius test as described by Paul Underwood. The single internal use is in
2043\texttt{mp\_prime\_is\_prime} for \texttt{MP\_8BIT} only but can be included at build-time for all other sizes
2044if the preprocessor macro \texttt{LTM\_USE\_FROBENIUS\_TEST} is defined.
2045
2046It returns \texttt{MP\_ITER} if the number of iterations is exhausted, assumes a composite as the input and sets \texttt{result} accordingly. This will reduce the set of available pseudoprimes by a very small amount: test with large datasets (more than $10^{10}$ numbers, both randomly chosen and sequences of odd numbers with a random start point) found only 31 (thirty-one) numbers with $a > 120$ and none at all with just an additional simple check for divisors $d < 2^8$.
2047
2048\section{Primality Testing}
2049Testing if a number is a square can be done a bit faster than just by calculating the square root. It is used by the primality testing function described below.
2050\index{mp\_is\_square}
2051\begin{alltt}
2052int mp_is_square(const mp_int *arg, int *ret);
2053\end{alltt}
2054
2055
2056\index{mp\_prime\_is\_prime}
2057\begin{alltt}
2058int mp_prime_is_prime (mp_int * a, int t, int *result)
2059\end{alltt}
2060This will perform a trial division followed by two rounds of Miller-Rabin with bases 2 and 3 and a Lucas-Selfridge test. The Lucas-Selfridge test is replaced with a Frobenius-Underwood for \texttt{MP\_8BIT}. The Frobenius-Underwood test for all other sizes is available as a compile-time option with the preprocessor macro \texttt{LTM\_USE\_FROBENIUS\_TEST}. See file
2061\texttt{bn\_mp\_prime\_is\_prime.c} for the necessary details. It shall be noted that both functions are much slower than
2062the Miller-Rabin test and if speed is an essential issue, the macro \texttt{LTM\_USE\_ONLY\_MR} switches both functions, the Frobenius-Underwood test and the Lucas-Selfridge test off and their code will not even be compiled into the library.
2063
2064If $t$ is set to a positive value $t$ additional rounds of the Miller-Rabin test with random bases will be performed to allow for Fips 186.4 (vid.~p.~126ff) compliance. The function \texttt{mp\_prime\_rabin\_miller\_trials} can be used to determine the number of rounds. It is vital that the function \texttt{mp\_rand()} has a cryptographically strong random number generator available.
2065
2066One Miller-Rabin tests with a random base will be run automatically, so by setting $t$ to a positive value this function will run $t + 1$ Miller-Rabin tests with random bases.
2067
2068If  $t$ is set to a negative value the test will run the deterministic Miller-Rabin test for the primes up to $3317044064679887385961981$. That limit has to be checked by the caller.
2069
2070If $a$ passes all of the tests $result$ is set to one, otherwise it is set to zero.
2071
2072\section{Next Prime}
2073\index{mp\_prime\_next\_prime}
2074\begin{alltt}
2075int mp_prime_next_prime(mp_int *a, int t, int bbs_style)
2076\end{alltt}
2077This finds the next prime after $a$ that passes mp\_prime\_is\_prime() with $t$ tests but see the documentation for
2078mp\_prime\_is\_prime for details regarding the use of the argument $t$.  Set $bbs\_style$ to one if you
2079want only the next prime congruent to $3 \mbox{ mod } 4$, otherwise set it to zero to find any next prime.
2080
2081\section{Random Primes}
2082\index{mp\_prime\_rand}
2083\begin{alltt}
2084int mp_prime_rand(mp_int *a,    int t,
2085                  int     size, int flags);
2086\end{alltt}
2087This will generate a prime in $a$ using $t$ tests of the primality testing algorithms.
2088See the documentation for mp\_prime\_is\_prime for details regarding the use of the argument $t$.
2089The variable $size$ specifies the bit length of the prime desired.
2090The variable $flags$ specifies one of several options available
2091(see fig. \ref{fig:primeopts}) which can be OR'ed together.
2092
2093The function mp\_prime\_rand() is suitable for generating primes which must be secret (as in the case of RSA) since there
2094is no skew on the least significant bits.
2095
2096\textit{Note:} This function replaces the deprecated mp\_prime\_random and mp\_prime\_random\_ex functions.
2097
2098\begin{figure}[h]
2099\begin{center}
2100\begin{small}
2101\begin{tabular}{|r|l|}
2102\hline \textbf{Flag}         & \textbf{Meaning} \\
2103\hline LTM\_PRIME\_BBS       & Make the prime congruent to $3$ modulo $4$ \\
2104\hline LTM\_PRIME\_SAFE      & Make a prime $p$ such that $(p - 1)/2$ is also prime. \\
2105                             & This option implies LTM\_PRIME\_BBS as well. \\
2106\hline LTM\_PRIME\_2MSB\_OFF & Makes sure that the bit adjacent to the most significant bit \\
2107                             & Is forced to zero.  \\
2108\hline LTM\_PRIME\_2MSB\_ON  & Makes sure that the bit adjacent to the most significant bit \\
2109                             & Is forced to one. \\
2110\hline
2111\end{tabular}
2112\end{small}
2113\end{center}
2114\caption{Primality Generation Options}
2115\label{fig:primeopts}
2116\end{figure}
2117
2118\chapter{Random Number Generation}
2119\section{PRNG}
2120\index{mp\_rand\_digit}
2121\begin{alltt}
2122int mp_rand_digit(mp_digit *r)
2123\end{alltt}
2124This function generates a random number in \texttt{r} of the size given in \texttt{r} (that is, the variable is used for in- and output) but not more than \texttt{MP\_MASK} bits.
2125
2126\index{mp\_rand}
2127\begin{alltt}
2128int mp_rand(mp_int *a, int digits)
2129\end{alltt}
2130This function generates a random number of \texttt{digits} bits.
2131
2132The random number generated with these two functions is cryptographically secure if the source of random numbers the operating systems offers is cryptographically secure. It will use \texttt{arc4random()} if the OS is a BSD flavor, Wincrypt on Windows, or \texttt{/dev/urandom} on all operating systems that have it.
2133
2134
2135\chapter{Input and Output}
2136\section{ASCII Conversions}
2137\subsection{To ASCII}
2138\index{mp\_to\_radix}
2139\begin{alltt}
2140int mp_to_radix (mp_int *a, char *str, size_t maxlen, size_t *written, int radix);
2141\end{alltt}
2142This stores $a$ in \texttt{str} of maximum length \texttt{maxlen} as a base-\texttt{radix} string of ASCII chars and appends a \texttt{NUL} character to terminate the string.
2143
2144Valid values of \texttt{radix} line in the range $[2, 64]$.
2145
2146The exact number of characters in \texttt{str} plus the \texttt{NUL} will be put in \texttt{written} if that variable is not set to \texttt{NULL}.
2147
2148If \texttt{str} is not big enough to hold $a$, \texttt{str} will be filled with the least-significant digits
2149of length \texttt{maxlen-1}, then \texttt{str} will be \texttt{NUL} terminated and the error \texttt{MP\_VAL} is returned.
2150
2151Please be aware that this function cannot evaluate the actual size of the buffer, it relies on the correctness of \texttt{maxlen}!
2152
2153
2154\index{mp\_radix\_size}
2155\begin{alltt}
2156int mp_radix_size (mp_int * a, int radix, int *size)
2157\end{alltt}
2158This stores in ``size'' the number of characters (including space for the NUL terminator) required.  Upon error this
2159function returns an error code and ``size'' will be zero.
2160
2161If \texttt{LTM\_NO\_FILE} is not defined a function to write to a file is also available.
2162\index{mp\_fwrite}
2163\begin{alltt}
2164int mp_fwrite(const mp_int *a, int radix, FILE *stream);
2165\end{alltt}
2166
2167
2168\subsection{From ASCII}
2169\index{mp\_read\_radix}
2170\begin{alltt}
2171int mp_read_radix (mp_int * a, char *str, int radix);
2172\end{alltt}
2173This will read the base-``radix'' NUL terminated string from ``str'' into $a$.  It will stop reading when it reads a
2174character it does not recognize (which happens to include th NUL char... imagine that...).  A single leading $-$ sign
2175can be used to denote a negative number.
2176
2177If \texttt{LTM\_NO\_FILE} is not defined a function to read from a file is also available.
2178\index{mp\_fread}
2179\begin{alltt}
2180int mp_fread(mp_int *a, int radix, FILE *stream);
2181\end{alltt}
2182
2183
2184\section{Binary Conversions}
2185
2186Converting an mp\_int to and from binary is another keen idea.
2187
2188\index{mp\_ubin\_size}
2189\begin{alltt}
2190size_t mp_ubin_size(mp_int *a);
2191\end{alltt}
2192
2193This will return the number of bytes (octets) required to store the unsigned copy of the integer $a$.
2194
2195\index{mp\_to\_ubin}
2196\begin{alltt}
2197int mp_to_unsigned_bin(mp_int *a, unsigned char *b, size_t maxlen, size_t *len);
2198\end{alltt}
2199This will store $a$ into the buffer $b$ of size \texttt{maxlen} in big--endian format storing the number of bytes written in \texttt{len}.  Fortunately this is exactly what DER (or is it ASN?) requires.  It does not store the sign of the integer.
2200
2201\index{mp\_from\_ubin}
2202\begin{alltt}
2203int mp_from_ubin(mp_int *a, unsigned char *b, size_t size);
2204\end{alltt}
2205This will read in an unsigned big--endian array of bytes (octets) from $b$ of length \texttt{size} into $a$.  The resulting big-integer $a$ will always be positive.
2206
2207For those who acknowledge the existence of negative numbers (heretic!) there are ``signed'' versions of the
2208previous functions.
2209\index{mp\_signed\_bin\_size} \index{mp\_to\_signed\_bin} \index{mp\_read\_signed\_bin}
2210\begin{alltt}
2211int mp_sbin_size(mp_int *a);
2212int mp_from_sbin(mp_int *a, unsigned char *b, size_t size);
2213int mp_to_sbin(mp_int *a, unsigned char *b, size_t maxsize, size_t *len);
2214\end{alltt}
2215They operate essentially the same as the unsigned copies except they prefix the data with zero or non--zero
2216byte depending on the sign.  If the sign is zpos (e.g. not negative) the prefix is zero, otherwise the prefix
2217is non--zero.
2218
2219The two functions \texttt{mp\_unpack} (get your gifts out of the box, import binary data) and \texttt{mp\_pack} (put your gifts into the box, export binary data) implement the similarly working GMP functions as described at \url{http://gmplib.org/manual/Integer-Import-and-Export.html} with the exception that \texttt{mp\_pack} will not allocate memory if \texttt{rop} is \texttt{NULL}.
2220\index{mp\_unpack} \index{mp\_pack}
2221\begin{alltt}
2222int mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
2223             mp_endian endian, size_t nails, const void *op, size_t maxsize);
2224int mp_pack(void *rop, size_t *countp, mp_order order, size_t size,
2225             mp_endian endian, size_t nails, const mp_int *op);
2226\end{alltt}
2227The function \texttt{mp\_pack} has the additional variable \texttt{maxsize} which must hold the size of the buffer \texttt{rop} in bytes. Use
2228\begin{alltt}
2229/* Parameters "nails" and "size" are the same as in mp_pack */
2230size_t mp_pack_size(mp_int *a, size_t nails, size_t size);
2231\end{alltt}
2232To get the size in bytes necessary to be put in \texttt{maxsize}).
2233
2234To enhance the readability of your code, the following enums have been wrought for your convenience.
2235\begin{alltt}
2236typedef enum {
2237   MP_LSB_FIRST = -1,
2238   MP_MSB_FIRST =  1
2239} mp_order;
2240typedef enum {
2241   MP_LITTLE_ENDIAN  = -1,
2242   MP_NATIVE_ENDIAN  =  0,
2243   MP_BIG_ENDIAN     =  1
2244} mp_endian;
2245\end{alltt}
2246
2247\chapter{Algebraic Functions}
2248\section{Extended Euclidean Algorithm}
2249\index{mp\_exteuclid}
2250\begin{alltt}
2251int mp_exteuclid(mp_int *a, mp_int *b,
2252                 mp_int *U1, mp_int *U2, mp_int *U3);
2253\end{alltt}
2254
2255This finds the triple U1/U2/U3 using the Extended Euclidean algorithm such that the following equation holds.
2256
2257\begin{equation}
2258a \cdot U1 + b \cdot U2 = U3
2259\end{equation}
2260
2261Any of the U1/U2/U3 parameters can be set to \textbf{NULL} if they are not desired.
2262
2263\section{Greatest Common Divisor}
2264\index{mp\_gcd}
2265\begin{alltt}
2266int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
2267\end{alltt}
2268This will compute the greatest common divisor of $a$ and $b$ and store it in $c$.
2269
2270\section{Least Common Multiple}
2271\index{mp\_lcm}
2272\begin{alltt}
2273int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
2274\end{alltt}
2275This will compute the least common multiple of $a$ and $b$ and store it in $c$.
2276
2277\section{Jacobi Symbol}
2278\index{mp\_jacobi}
2279\begin{alltt}
2280int mp_jacobi (mp_int * a, mp_int * p, int *c)
2281\end{alltt}
2282This will compute the Jacobi symbol for $a$ with respect to $p$.  If $p$ is prime this essentially computes the Legendre
2283symbol.  The result is stored in $c$ and can take on one of three values $\lbrace -1, 0, 1 \rbrace$.  If $p$ is prime
2284then the result will be $-1$ when $a$ is not a quadratic residue modulo $p$.  The result will be $0$ if $a$ divides $p$
2285and the result will be $1$ if $a$ is a quadratic residue modulo $p$.
2286
2287\section{Kronecker Symbol}
2288\index{mp\_kronecker}
2289\begin{alltt}
2290int mp_kronecker (mp_int * a, mp_int * p, int *c)
2291\end{alltt}
2292Extension of the Jacoby symbol to all $\lbrace a, p \rbrace \in \mathbb{Z}$ .
2293
2294
2295\section{Modular square root}
2296\index{mp\_sqrtmod\_prime}
2297\begin{alltt}
2298int mp_sqrtmod_prime(mp_int *n, mp_int *p, mp_int *r)
2299\end{alltt}
2300
2301This will solve the modular equatioon $r^2 = n \mod p$ where $p$ is a prime number greater than 2 (odd prime).
2302The result is returned in the third argument $r$, the function returns \textbf{MP\_OKAY} on success,
2303other return values indicate failure.
2304
2305The implementation is split for two different cases:
2306
23071. if $p \mod 4 == 3$ we apply \href{http://cacr.uwaterloo.ca/hac/}{Handbook of Applied Cryptography algorithm 3.36} and compute $r$ directly as
2308$r = n^{(p+1)/4} \mod p$
2309
23102. otherwise we use \href{https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm}{Tonelli-Shanks algorithm}
2311
2312The function does not check the primality of parameter $p$ thus it is up to the caller to assure that this parameter
2313is a prime number. When $p$ is a composite the function behaviour is undefined, it may even return a false-positive
2314\textbf{MP\_OKAY}.
2315
2316\section{Modular Inverse}
2317\index{mp\_invmod}
2318\begin{alltt}
2319int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
2320\end{alltt}
2321Computes the multiplicative inverse of $a$ modulo $b$ and stores the result in $c$ such that $ac \equiv 1 \mbox{ (mod }b\mbox{)}$.
2322
2323\section{Single Digit Functions}
2324
2325For those using small numbers (\textit{snicker snicker}) there are several ``helper'' functions
2326
2327\index{mp\_add\_d} \index{mp\_sub\_d} \index{mp\_mul\_d} \index{mp\_div\_d} \index{mp\_mod\_d}
2328\begin{alltt}
2329int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
2330int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
2331int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
2332int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
2333int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
2334\end{alltt}
2335
2336These work like the full mp\_int capable variants except the second parameter $b$ is a mp\_digit.  These
2337functions fairly handy if you have to work with relatively small numbers since you will not have to allocate
2338an entire mp\_int to store a number like $1$ or $2$.
2339
2340The functions \texttt{mp\_incr} and \texttt{mp\_decr} mimic the postfix operators \texttt{++} and \texttt{--} respectively, to increment the input by one. They call the full single-digit functions if the addition would carry. Both functions need to be included in a minimized library because they call each other in case of a negative input, These functions change the inputs!
2341\begin{alltt}
2342int mp_incr(mp_int *a);
2343int mp_decr(mp_int *a);
2344\end{alltt}
2345
2346
2347The division by three can be made faster by replacing the division with a multiplication by the multiplicative inverse of three.
2348
2349\index{mp\_div\_3}
2350\begin{alltt}
2351int mp_div_3(const mp_int *a, mp_int *c, mp_digit *d);
2352\end{alltt}
2353
2354\chapter{Little Helpers}
2355It is never wrong to have some useful little shortcuts at hand.
2356\section{Function Macros}
2357To make this overview simpler the macros are given as function prototypes. The return of logic macros is \texttt{MP\_NO} or \texttt{MP\_YES} respectively.
2358
2359\index{mp\_iseven}
2360\begin{alltt}
2361int mp_iseven(mp_int *a)
2362\end{alltt}
2363Checks if $a = 0 mod 2$
2364
2365\index{mp\_isodd}
2366\begin{alltt}
2367int mp_isodd(mp_int *a)
2368\end{alltt}
2369Checks if $a = 1 mod 2$
2370
2371\index{mp\_isneg}
2372\begin{alltt}
2373int mp_isneg(mp_int *a)
2374\end{alltt}
2375Checks if $a < 0$
2376
2377
2378\index{mp\_iszero}
2379\begin{alltt}
2380int mp_iszero(mp_int *a)
2381\end{alltt}
2382Checks if $a = 0$. It does not check if the amount of memory allocated for $a$ is also minimal.
2383
2384
2385Other macros which are either shortcuts to normal functions or just other names for them do have their place in a programmer's life, too!
2386
2387\subsection{Renamings}
2388\index{mp\_mag\_size}
2389\begin{alltt}
2390#define mp_mag_size(mp) mp_unsigned_bin_size(mp)
2391\end{alltt}
2392
2393
2394\index{mp\_raw\_size}
2395\begin{alltt}
2396#define mp_raw_size(mp) mp_signed_bin_size(mp)
2397\end{alltt}
2398
2399
2400\index{mp\_read\_mag}
2401\begin{alltt}
2402#define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
2403\end{alltt}
2404
2405
2406\index{mp\_read\_raw}
2407\begin{alltt}
2408 #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
2409\end{alltt}
2410
2411
2412\index{mp\_tomag}
2413\begin{alltt}
2414#define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
2415\end{alltt}
2416
2417
2418\index{mp\_toraw}
2419\begin{alltt}
2420#define mp_toraw(mp, str)         mp_to_signed_bin((mp), (str))
2421\end{alltt}
2422
2423
2424
2425\subsection{Shortcuts}
2426
2427\index{mp\_to\_binary}
2428\begin{alltt}
2429#define mp_to_binary(M, S, N)  mp_to_radix((M), (S), (N), 2)
2430\end{alltt}
2431
2432
2433\index{mp\_to\_octal}
2434\begin{alltt}
2435#define mp_to_octal(M, S, N)   mp_to_radix((M), (S), (N), 8)
2436\end{alltt}
2437
2438
2439\index{mp\_to\_decimal}
2440\begin{alltt}
2441#define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), 10)
2442\end{alltt}
2443
2444
2445\index{mp\_to\_hex}
2446\begin{alltt}
2447#define mp_to_hex(M, S, N)     mp_to_radix((M), (S), (N), 16)
2448\end{alltt}
2449
2450\begin{appendices}
2451\appendixpage
2452%\noappendicestocpagenum
2453\addappheadtotoc
2454\chapter{Computing Number of Miller-Rabin Trials}\label{app:numberofmrcomp}
2455The number of Miller-Rabin rounds in the tables \ref{millerrabinrunsimpl}, \ref{millerrabinrunsp1}, and \ref{millerrabinrunsp2} have been calculated with the formula in FIPS 186-4 appendix F.1 (page 117) implemented as a PARI/GP script.
2456\begin{alltt}
2457log2(x) = log(x)/log(2)
2458
2459fips_f1_sums(k, M, t) = {
2460   local(s = 0);
2461   s = sum(m=3,M,
2462          2^(m-t*(m-1)) *
2463          sum(j=2,m,
2464             1/ ( 2^( j + (k-1)/j ) )
2465          )
2466        );
2467   return(s);
2468}
2469
2470fips_f1_2(k, t, M) = {
2471   local(common_factor, t1, t2, f1, f2, ds, res);
2472
2473   common_factor = 2.00743 * log(2) * k * 2^(-k);
2474   t1 = 2^(k - 2 - M*t);
2475   f1 = (8 * ((Pi^2) - 6))/3;
2476   f2 = 2^(k - 2);
2477   ds = t1 + f1 * f2 * fips_f1_sums(k, M, t);
2478   res = common_factor * ds;
2479   return(res);
2480}
2481
2482fips_f1_1(prime_length, ptarget)={
2483   local(t, t_end, M, M_end, pkt);
2484
2485   t_end = ceil(-log2(ptarget)/2);
2486   M_end = floor(2 * sqrt(prime_length-1) - 1);
2487
2488   for(t = 1, t_end,
2489      for(M = 3, M_end,
2490         pkt = fips_f1_2(prime_length, t, M);
2491         if(pkt <= ptarget,
2492            return(t);
2493         );
2494      );
2495   );
2496}
2497\end{alltt}
2498
2499To get the number of rounds for a $1024$ bit large prime with a probability of $2^{-160}$:
2500\begin{alltt}
2501? fips_f1_1(1024,2^(-160))
2502%1 = 9
2503\end{alltt}
2504\end{appendices}
2505\input{bn.ind}
2506
2507\end{document}
2508