Properly implement neg_mechs & GM_USE_MG_CRED (fix)
[metze/heimdal/wip.git] / lib / hcrypto / libtommath / doc / bn.tex
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
56 This text, the library and the accompanying textbook are all hereby placed in the public domain.  This book has been
57 formatted 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{ }
64 LibTom Projects
65
66 \& originally
67
68 Tom St Denis,
69
70 Ontario, Canada
71 \end{flushright}
72
73 \tableofcontents
74 \listoffigures
75 \mainmatter
76 \pagestyle{headings}
77 \chapter{Introduction}
78 \section{What is LibTomMath?}
79 LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
80 large integer numbers.  It was written in portable ISO C source code so that it will build on any platform with a conforming
81 C compiler.
82
83 In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
84 to implement ``bignum'' math.  However, the resulting code has proven to be very useful.  It has been used by numerous
85 universities, commercial and open source software developers.  It has been used on a variety of platforms ranging from
86 Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.
87
88 \section{License}
89 As of the v0.25 the library source code has been placed in the public domain with every new release.  As of the v0.28
90 release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
91 release as well.  This textbook is meant to compliment the project by providing a more solid walkthrough of the development
92 algorithms used in the library.
93
94 Since both\footnote{Note that the MPI files under mtest/ are copyrighted by Michael Fromberger.  They are not required to use LibTomMath.} are in the
95 public domain everyone is entitled to do with them as they see fit.
96
97 \section{Building LibTomMath}
98
99 LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC.  However, the library will
100 also build in MSVC, Borland C out of the box.  For any other ISO C compiler a makefile will have to be made by the end
101 developer. 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
104 Intel'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}
106 CC=/home/czurnieden/intel/bin/icc make
107 \end{alltt}
108
109 ICC 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}
111 icc: command line warning #10148: option '-Wbad-function-cast' not supported
112 icc: command line warning #10148: option '-Wcast-align' not supported
113 \end{alltt}
114 It 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}
117 To build as a static library for GCC issue the following
118 \begin{alltt}
119 make
120 \end{alltt}
121
122 command.  This will build the library and archive the object files in ``libtommath.a''.  Now you link against
123 that and include ``tommath.h'' within your programs.  Alternatively to build with MSVC issue the following
124 \begin{alltt}
125 nmake -f makefile.msvc
126 \end{alltt}
127
128 This will build the library and archive the object files in ``tommath.lib''.  This has been tested with MSVC
129 version 6.00 with service pack 5.
130
131 To run a program to adapt the Toom-Cook cut-off values to your architecture type
132 \begin{alltt}
133 make tune
134 \end{alltt}
135 This will take some time.
136
137 \subsection{Shared Libraries}
138 \subsubsection{GNU based Operating Systems}
139 To build as a shared library for GCC issue the following
140 \begin{alltt}
141 make -f makefile.shared
142 \end{alltt}
143 This requires the ``libtool'' package (common on most Linux/BSD systems).  It will build LibTomMath as both shared
144 and static then install (by default) into /usr/lib as well as install the header files in /usr/include.  The shared
145 library (resource) will be called ``libtommath.la'' while the static library called ``libtommath.a''.  Generally
146 you use libtool to link your application against the shared object.
147
148 To run a program to adapt the Toom-Cook cut-off values to your architecture type
149 \begin{alltt}
150 make -f makefile.shared tune
151 \end{alltt}
152 This will take some time.
153
154 \subsubsection{Microsoft Windows based Operating Systems}
155 There is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_dll'' makefile.  It requires
156 Cygwin 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}
159 OpenBSD 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
161 The 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}
171 The wrong \texttt{libtool} will build it all fine but when it comes to the final linking fails with
172 \begin{alltt}
173 ...
174 cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
175 cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
176 cc -I./ -Wall -Wsign-compare -Wextra -Wshadow -Wsystem-headers -Wdeclaration-afo...
177 libtool --mode=link --tag=CC cc  bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_mo
178 libtool: link: cc bn_error.lo bn_s_mp_invmod_fast.lo bn_s_mp_montgomery_reduce_fast0
179 bn_error.lo: file not recognized: File format not recognized
180 cc: error: linker command failed with exit code 1 (use -v to see invocation)
181 Error while executing cc bn_error.lo bn_s_mp_invmod_fast.lo bn_fast_mp_montgomery0
182 gmake: *** [makefile.shared:64: libtommath.la] Error 1
183 \end{alltt}
184
185 To 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}
189 At 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
192 libtool (GNU libtool) 2.4.2
193 Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
194
195 Copyright (C) 2011 Free Software Foundation, Inc.
196 This is free software; see the source for copying conditions.  There is NO
197 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
198 $ libtool --version
199 libtool (not (GNU libtool)) 1.5.26
200 \end{alltt}
201
202 The shared library should build now with
203 \begin{alltt}
204 LIBTOOL="/usr/local/bin/libtool" gmake -f makefile.shared
205 \end{alltt}
206 You might need to run a \texttt{gmake -f makefile.shared clean} first.
207
208 \subsubsection{NetBSD}
209 NetBSD 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}
211 pkg_add gmake libtool
212 \end{alltt}
213 Please check with \texttt{libtool --version} that installed libtool is indeed a GNU libtool.
214 Build the shared library by typing:
215 \begin{alltt}
216 gmake -f makefile.shared
217 \end{alltt}
218
219 \subsection{Testing}
220 To build the library and the test harness type
221
222 \begin{alltt}
223 make test
224 \end{alltt}
225
226 This will build the library, ``test'' and ``mtest/mtest''.  The ``test'' program will accept test vectors and verify the
227 results.  ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote{A copy of MPI
228 is included in the package}.  Simply pipe mtest into test using
229
230 \begin{alltt}
231 mtest/mtest | test
232 \end{alltt}
233
234 If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into
235 mtest.  For example, if your PRNG program is called ``myprng'' simply invoke
236
237 \begin{alltt}
238 myprng | mtest/mtest | test
239 \end{alltt}
240
241 This will output a row of numbers that are increasing.  Each column is a different test (such as addition, multiplication, etc)
242 that is being performed.  The numbers represent how many times the test was invoked.  If an error is detected the program
243 will exit with a dump of the relevant numbers it was working with.
244
245 \section{Build Configuration}
246 LibTomMath can configured at build time in three phases we shall call ``depends'', ``tweaks'' and ``trims''.
247 Each phase changes how the library is built and they are applied one after another respectively.
248
249 To 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
251 instructs the system to build all of the functions.  This is how LibTomMath used to be packaged.  This will give you
252 access to every function LibTomMath offers.
253
254 However, there are cases where such a build is not optional.  For instance, you want to perform RSA operations.  You
255 don't need the vast majority of the library to perform these operations.  Aside from LTM\_ALL there is
256 another pre--defined class ``SC\_RSA\_1'' which works in conjunction with the RSA from LibTomCrypt.  Additional
257 classes can be defined base on the need of the user.
258
259 \subsection{Build Depends}
260 In the file tommath\_class.h you will see a large list of C ``defines'' followed by a series of ``ifdefs''
261 which further define symbols.  All of the symbols (technically they're macros $\ldots$) represent a given C source
262 file.  For instance, BN\_MP\_ADD\_C represents the file ``bn\_mp\_add.c''.  When a define has been enabled the
263 function in the respective file will be compiled and linked into the library.  Accordingly when the define
264 is absent the file will not be compiled and not contribute any size to the library.
265
266 You will also note that the header tommath\_class.h is actually recursively included (it includes itself twice).
267 This is to help resolve as many dependencies as possible.  In the last pass the symbol LTM\_LAST will be defined.
268 This is useful for ``trims''.
269
270 \subsection{Build Tweaks}
271 A tweak is an algorithm ``alternative''.  For example, to provide tradeoffs (usually between size and space).
272 They 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}
286 A trim is a manner of removing functionality from a function that is not required.  For instance, to perform
287 RSA cryptography you only require exponentiation with odd moduli so even moduli support can be safely removed.
288 Build trims are meant to be defined on the last pass of the configuration which means they are to be defined
289 only 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}
336 Unlike  GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with
337 bleeding edge performance in mind.  First and foremost LibTomMath was written to be entirely open.  Not only is the
338 source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
339 source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
340 arithmetic techniques.
341
342 LibTomMath was written to be an instructive collection of source code.  This is why there are many comments, only one
343 function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
344 increase.
345
346 Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
347 the library (beat that!).
348
349 So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe.  Let me tabulate what I think
350 are the pros and cons of LibTomMath by comparing it to the math routines from GnuPG\footnote{GnuPG v1.2.3 versus LibTomMath v0.28}.
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
371 It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application.
372 However, LibTomMath was written with cryptography in mind.  It provides essentially all of the functions a cryptosystem
373 would require when working with large integers.
374
375 So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
376 own application but I think there are reasons not to.  While LibTomMath is slower than libraries such as GnuMP it is
377 not normally significantly slower.  On x86 machines the difference is normally a factor of two when performing modular
378 exponentiations.  It depends largely on the processor, compiler and the moduli being used.
379
380 Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern.  However,
381 on the other side of the coin LibTomMath offers you a totally free (public domain) well structured math library
382 that is very flexible, complete and performs well in resource constrained environments.  Fast RSA for example can
383 be 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}
387 In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically
388 libtommath.a).  There is no library initialization required and the entire library is thread safe.
389
390 \section{Return Codes}
391 There 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
412 The last two codes listed are not actually ``return'ed'' by a function.  They are placed in an integer (the caller must
413 provide the address of an integer it can store to) which the caller can access.  To convert one of the three return codes
414 to a string use the following function.
415
416 \index{mp\_error\_to\_string}
417 \begin{alltt}
418 char *mp_error_to_string(int code);
419 \end{alltt}
420
421 This will return a pointer to a string which describes the given error code.  It will not work for the return codes
422 MP\_YES and MP\_NO.
423
424 \section{Data Types}
425 The basic ``multiple precision integer'' type is known as the ``mp\_int'' within LibTomMath.  This data type is used to
426 organize all of the data required to manipulate the integer it represents.  Within LibTomMath it has been prototyped
427 as the following.
428
429 \index{mp\_int}
430 \begin{alltt}
431 typedef struct  \{
432     int used, alloc, sign;
433     mp_digit *dp;
434 \} mp_int;
435 \end{alltt}
436
437 Where ``mp\_digit'' is a data type that represents individual digits of the integer.  By default, an mp\_digit is the
438 ISO C ``unsigned long'' data type and each digit is $28-$bits long.  The mp\_digit type can be configured to suit other
439 platforms by defining the appropriate macros.
440
441 All LTM functions that use the mp\_int type will expect a pointer to mp\_int structure.  You must allocate memory to
442 hold the structure itself by yourself (whether off stack or heap it doesn't matter).  The very first thing that must be
443 done to use an mp\_int is that it must be initialized.
444
445 \section{Function Organization}
446
447 The arithmetic functions of the library are all organized to have the same style prototype.  That is source operands
448 are passed on the left and the destination is on the right.  For instance,
449
450 \begin{alltt}
451 mp_add(&a, &b, &c);       /* c = a + b */
452 mp_mul(&a, &a, &c);       /* c = a * a */
453 mp_div(&a, &b, &c, &d);   /* c = [a/b], d = a mod b */
454 \end{alltt}
455
456 Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
457 For instance,
458
459 \begin{alltt}
460 mp_add(&a, &b, &b);       /* b = a + b */
461 mp_div(&a, &b, &a, &c);   /* a = [a/b], c = a mod b */
462 \end{alltt}
463
464 This allows operands to be re-used which can make programming simpler.
465
466 \section{Initialization}
467 \subsection{Single Initialization}
468 A single mp\_int can be initialized with the ``mp\_init'' function.
469
470 \index{mp\_init}
471 \begin{alltt}
472 int mp_init (mp_int * a);
473 \end{alltt}
474
475 This function expects a pointer to an mp\_int structure and will initialize the members of the structure so the mp\_int
476 represents the default integer which is zero.  If the functions returns MP\_OKAY then the mp\_int is ready to be used
477 by the other LibTomMath functions.
478
479 \begin{small} \begin{alltt}
480 int 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}
498 When you are finished with an mp\_int it is ideal to return the heap it used back to the system.  The following function
499 provides this functionality.
500
501 \index{mp\_clear}
502 \begin{alltt}
503 void mp_clear (mp_int * a);
504 \end{alltt}
505
506 The function expects a pointer to a previously initialized mp\_int structure and frees the heap it uses.  It sets the
507 pointer\footnote{The ``dp'' member.} within the mp\_int to \textbf{NULL} which is used to prevent double free situations.
508 Is is legal to call mp\_clear() twice on the same mp\_int in a row.
509
510 \begin{small} \begin{alltt}
511 int 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}
532 Certain algorithms require more than one large integer.  In these instances it is ideal to initialize all of the mp\_int
533 variables in an ``all or nothing'' fashion.  That is, they are either all initialized successfully or they are all
534 not initialized.
535
536 The  mp\_init\_multi() function provides this functionality.
537
538 \index{mp\_init\_multi} \index{mp\_clear\_multi}
539 \begin{alltt}
540 int mp_init_multi(mp_int *mp, ...);
541 \end{alltt}
542
543 It accepts a \textbf{NULL} terminated list of pointers to mp\_int structures.  It will attempt to initialize them all
544 at once.  If the function returns MP\_OKAY then all of the mp\_int variables are ready to use, otherwise none of them
545 are available for use.  A complementary mp\_clear\_multi() function allows multiple mp\_int variables to be free'd
546 from the heap at the same time.
547
548 \begin{small} \begin{alltt}
549 int 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}
572 To 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}
576 int mp_init_copy (mp_int * a, mp_int * b);
577 \end{alltt}
578
579 This function will initialize $a$ and make it a copy of $b$ if all goes well.
580
581 \begin{small} \begin{alltt}
582 int 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
605 Another less common initializer is mp\_init\_size() which allows the user to initialize an mp\_int with a given
606 default number of digits.  By default, all initializers allocate \textbf{MP\_PREC} digits.  This function lets
607 you override this behaviour.
608
609 \index{mp\_init\_size}
610 \begin{alltt}
611 int mp_init_size (mp_int * a, int size);
612 \end{alltt}
613
614 The $size$ parameter must be greater than zero.  If the function succeeds the mp\_int $a$ will be initialized
615 to have $size$ digits (which are all initially zero).
616
617 \begin{small} \begin{alltt}
618 int 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
639 This is used to ensure that leading zero digits are trimed and the leading "used" digit will be non-zero.
640 It also fixes the sign if there are no more leading digits.
641
642 \index{mp\_clamp}
643 \begin{alltt}
644 void mp_clamp(mp_int *a);
645 \end{alltt}
646
647 \subsection{Zero Out}
648
649 This function will set the ``bigint'' to zeros without changing the amount of allocated memory.
650
651 \index{mp\_zero}
652 \begin{alltt}
653 void mp_zero(mp_int *a);
654 \end{alltt}
655
656
657 \subsection{Reducing Memory Usage}
658 When an mp\_int is in a state where it won't be changed again\footnote{A Diffie-Hellman modulus for instance.} excess
659 digits can be removed to return memory to the heap with the mp\_shrink() function.
660
661 \index{mp\_shrink}
662 \begin{alltt}
663 int mp_shrink (mp_int * a);
664 \end{alltt}
665
666 This will remove excess digits of the mp\_int $a$.  If the operation fails the mp\_int should be intact without the
667 excess digits being removed.  Note that you can use a shrunk mp\_int in further computations, however, such operations
668 will require heap operations which can be slow.  It is not ideal to shrink mp\_int variables that you will further
669 modify in the system (unless you are seriously low on memory).
670
671 \begin{small} \begin{alltt}
672 int 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
704 Within the mp\_int structure are two parameters which control the limitations of the array of digits that represent
705 the integer the mp\_int is meant to equal.   The \textit{used} parameter dictates how many digits are significant, that is,
706 contribute to the value of the mp\_int.  The \textit{alloc} parameter dictates how many digits are currently available in
707 the array.  If you need to perform an operation that requires more digits you will have to mp\_grow() the mp\_int to
708 your desired size.
709
710 \index{mp\_grow}
711 \begin{alltt}
712 int mp_grow (mp_int * a, int size);
713 \end{alltt}
714
715 This 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}
719 int 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
752 A 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}
756 int mp_copy (mp_int * a, mp_int *b);
757 \end{alltt}
758
759 You 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}
763 void mp_exch (mp_int * a, mp_int *b);
764 \end{alltt}
765
766 \section{Bit Counting}
767
768 To 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}
772 int mp_cnt_lsb(const mp_int *a);
773 \end{alltt}
774
775 To 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}
779 int mp_count_bits(const mp_int *a);
780 \end{alltt}
781
782
783 \section{Small Constants}
784 Setting mp\_ints to small constants is a relatively common operation.  To accommodate these instances there is a
785 small constant assignment function.  This function is used to set a single digit constant.
786 The reason for this function is efficiency.  Setting a single digit is quick but the
787 domain of a digit can change (it's always at least $0 \ldots 127$).
788
789 \subsection{Single Digit}
790
791 Setting a single digit can be accomplished with the following function.
792
793 \index{mp\_set}
794 \begin{alltt}
795 void mp_set (mp_int * a, mp_digit b);
796 \end{alltt}
797
798 This will zero the contents of $a$ and make it represent an integer equal to the value of $b$.  Note that this
799 function has a return type of \textbf{void}.  It cannot cause an error so it is safe to assume the function
800 succeeded.
801
802 \begin{small} \begin{alltt}
803 int 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
826 These 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}
831 void mp_set_i32 (mp_int * a, int32_t b);
832 void mp_set_u32 (mp_int * a, uint32_t b);
833 void mp_set_i64 (mp_int * a, int64_t b);
834 void mp_set_u64 (mp_int * a, uint64_t b);
835 \end{alltt}
836
837 These functions assign the sign and value of the input \texttt{b} to \texttt{mp\_int a}.
838 The 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}
843 int32_t mp_get_i32 (mp_int * a);
844 uint32_t mp_get_u32 (mp_int * a);
845 uint32_t mp_get_mag_u32 (mp_int * a);
846 int64_t mp_get_i64 (mp_int * a);
847 uint64_t mp_get_u64 (mp_int * a);
848 uint64_t mp_get_mag_u64 (mp_int * a);
849 \end{alltt}
850
851 These functions return the 32 or 64 least significant bits of $a$ respectively. The unsigned functions
852 return 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}
855 int 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
878 This should output the following if the program succeeds.
879
880 \begin{alltt}
881 number == 654321
882 \end{alltt}
883
884 \subsection{Long Constants - platform dependant}
885
886 \index{mp\_set\_l} \index{mp\_set\_ul}
887 \begin{alltt}
888 void mp_set_l (mp_int * a, long b);
889 void mp_set_ul (mp_int * a, unsigned long b);
890 \end{alltt}
891
892 This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
893
894 To 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}
898 long mp_get_l (mp_int * a);
899 unsigned long mp_get_ul (mp_int * a);
900 unsigned long mp_get_mag_ul (mp_int * a);
901 \end{alltt}
902
903 This 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}
909 void mp_set_ll (mp_int * a, long long b);
910 void mp_set_ull (mp_int * a, unsigned long long b);
911 \end{alltt}
912
913 This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
914
915 To 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}
921 long long mp_get_ll (mp_int * a);
922 unsigned long long mp_get_ull (mp_int * a);
923 unsigned long long mp_get_mag_ull (mp_int * a);
924 \end{alltt}
925
926 This will return the least significant bits of the mp\_int $a$ that fit into a ``long long''.
927
928 \subsection{Initialize and Setting Constants}
929 To 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}
932 int mp_init_set (mp_int * a, mp_digit b);
933 int mp_init_i32 (mp_int * a, int32_t b);
934 int mp_init_u32 (mp_int * a, uint32_t b);
935 int mp_init_i64 (mp_int * a, int64_t b);
936 int mp_init_u64 (mp_int * a, uint64_t b);
937 int mp_init_l   (mp_int * a, long b);
938 int mp_init_ul  (mp_int * a, unsigned long b);
939 int mp_init_ll  (mp_int * a, long long b);
940 int mp_init_ull (mp_int * a, unsigned long long b);
941 \end{alltt}
942
943 Both functions work like the previous counterparts except they first mp\_init $a$ before setting the values.
944
945 \begin{alltt}
946 int 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
976 If this program succeeds it shall output.
977 \begin{alltt}
978 Number1, Number2 == 100, 1023
979 \end{alltt}
980
981 \section{Comparisons}
982
983 Comparisons in LibTomMath are always performed in a ``left to right'' fashion.  There are three possible return codes
984 for 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
1001 In figure \ref{fig:CMP} two integers $a$ and $b$ are being compared.  In this case $a$ is said to be ``to the left'' of
1002 $b$.
1003
1004 \subsection{Unsigned comparison}
1005
1006 An unsigned comparison considers only the digits themselves and not the associated \textit{sign} flag of the
1007 mp\_int structures.  This is analogous to an absolute comparison.  The function mp\_cmp\_mag() will compare two
1008 mp\_int variables based on their digits only.
1009
1010 \index{mp\_cmp\_mag}
1011 \begin{alltt}
1012 int mp_cmp_mag(mp_int * a, mp_int * b);
1013 \end{alltt}
1014 This will compare $a$ to $b$ placing $a$ to the left of $b$.  This function cannot fail and will return one of the
1015 three compare codes listed in figure \ref{fig:CMP}.
1016
1017 \begin{small} \begin{alltt}
1018 int 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
1053 If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
1054 successfully it should print the following.
1055
1056 \begin{alltt}
1057 |number1| < |number2|
1058 \end{alltt}
1059
1060 This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
1061
1062 \subsection{Signed comparison}
1063
1064 To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
1065
1066 \index{mp\_cmp}
1067 \begin{alltt}
1068 int mp_cmp(mp_int * a, mp_int * b);
1069 \end{alltt}
1070
1071 This will compare $a$ to the left of $b$.  It will first compare the signs of the two mp\_int variables.  If they
1072 differ it will return immediately based on their signs.  If the signs are equal then it will compare the digits
1073 individually.  This function will return one of the compare conditions codes listed in figure \ref{fig:CMP}.
1074
1075 \begin{small} \begin{alltt}
1076 int 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
1111 If this program\footnote{This function uses the mp\_neg() function which is discussed in section \ref{sec:NEG}.} completes
1112 successfully it should print the following.
1113
1114 \begin{alltt}
1115 number1 > number2
1116 \end{alltt}
1117
1118 \subsection{Single Digit}
1119
1120 To compare a single digit against an mp\_int the following function has been provided.
1121
1122 \index{mp\_cmp\_d}
1123 \begin{alltt}
1124 int mp_cmp_d(mp_int * a, mp_digit b);
1125 \end{alltt}
1126
1127 This will compare $a$ to the left of $b$ using a signed comparison.  Note that it will always treat $b$ as
1128 positive.  This function is rather handy when you have to compare against small values such as $1$ (which often
1129 comes up in cryptography).  The function cannot fail and will return one of the tree compare condition codes
1130 listed in figure \ref{fig:CMP}.
1131
1132
1133 \begin{small} \begin{alltt}
1134 int 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
1161 If this program functions properly it will print out the following.
1162
1163 \begin{alltt}
1164 number < 7
1165 \end{alltt}
1166
1167 \section{Logical Operations}
1168
1169 Logical operations are operations that can be performed either with simple shifts or boolean operators such as
1170 AND, XOR and OR directly.  These operations are very quick.
1171
1172 \subsection{Multiplication by two}
1173
1174 Multiplications and divisions by any power of two can be performed with quick logical shifts either left or
1175 right depending on the operation.
1176
1177 When 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}
1180 int mp_mul_2(mp_int * a, mp_int * b);
1181 int mp_div_2(mp_int * a, mp_int * b);
1182 \end{alltt}
1183
1184 The former will assign twice $a$ to $b$ while the latter will assign half $a$ to $b$.  These functions are fast
1185 since the shift counts and maskes are hardcoded into the routines.
1186
1187 \begin{small} \begin{alltt}
1188 int 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
1233 If this program is successful it will print out the following text.
1234
1235 \begin{alltt}
1236 2*number > 7
1237 2*number/2 < 7
1238 \end{alltt}
1239
1240 Since $10 > 7$ and $5 < 7$.
1241
1242 To multiply by a power of two the following function can be used.
1243
1244 \index{mp\_mul\_2d}
1245 \begin{alltt}
1246 int mp_mul_2d(mp_int * a, int b, mp_int * c);
1247 \end{alltt}
1248
1249 This will multiply $a$ by $2^b$ and store the result in ``c''.  If the value of $b$ is less than or equal to
1250 zero the function will copy $a$ to ``c'' without performing any further actions.  The multiplication itself
1251 is implemented as a right-shift operation of $a$ by $b$ bits.
1252
1253 To divide by a power of two use the following.
1254
1255 \index{mp\_div\_2d}
1256 \begin{alltt}
1257 int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d);
1258 \end{alltt}
1259 Which will divide $a$ by $2^b$, store the quotient in ``c'' and the remainder in ``d'.  If $b \le 0$ then the
1260 function simply copies $a$ over to ``c'' and zeroes $d$.  The variable $d$ may be passed as a \textbf{NULL}
1261 value to signal that the remainder is not desired.  The division itself is implemented as a left-shift
1262 operation of $a$ by $b$ bits.
1263
1264 It 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}
1268 int mp_2expt(mp_int *a, int b);
1269 \end{alltt}
1270 It is faster than doing it by shifting $1$ with \texttt{mp\_mul\_2d}.
1271
1272 \subsection{Polynomial Basis Operations}
1273
1274 Strictly 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
1277 the polynomial basis representation of $z$ if $f(\beta) = z$ for a given radix $\beta$.
1278
1279 To multiply by the polynomial $g(x) = x$ all you have todo is shift the digits of the basis left one place.  The
1280 following function provides this operation.
1281
1282 \index{mp\_lshd}
1283 \begin{alltt}
1284 int mp_lshd (mp_int * a, int b);
1285 \end{alltt}
1286
1287 This will multiply $a$ in place by $x^b$ which is equivalent to shifting the digits left $b$ places and inserting zeroes
1288 in 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}
1292 void mp_rshd (mp_int * a, int b)
1293 \end{alltt}
1294 This will divide $a$ in place by $x^b$ and discard the remainder.  This function cannot fail as it performs the operations
1295 in place and no new digits are required to complete it.
1296
1297 \subsection{AND, OR, XOR and COMPLEMENT Operations}
1298
1299 While AND, OR and XOR operations compute arbitrary-precision bitwise operations. Negative numbers
1300 are 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}
1304 int mp_or  (mp_int * a, mp_int * b, mp_int * c);
1305 int mp_and (mp_int * a, mp_int * b, mp_int * c);
1306 int mp_xor (mp_int * a, mp_int * b, mp_int * c);
1307 int mp_complement(const mp_int *a, mp_int *b);
1308 int mp_signed_rsh(mp_int * a, int b, mp_int * c, mp_int * d);
1309 \end{alltt}
1310
1311 The function \texttt{mp\_complement} computes a two-complement $b = \sim a$. The function \texttt{mp\_signed\_rsh} performs
1312 sign 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}
1317 int mp_get_bit(mp_int *a, int b)
1318 \end{alltt}
1319
1320 Pick 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}
1321 if the bit is 0 (zero) and \texttt{MP\_VAL} if $b < 0$.
1322
1323 \section{Addition and Subtraction}
1324
1325 To compute an addition or subtraction the following two functions can be used.
1326
1327 \index{mp\_add} \index{mp\_sub}
1328 \begin{alltt}
1329 int mp_add (mp_int * a, mp_int * b, mp_int * c);
1330 int mp_sub (mp_int * a, mp_int * b, mp_int * c)
1331 \end{alltt}
1332
1333 Which perform $c = a \odot b$ where $\odot$ is one of signed addition or subtraction.  The operations are fully sign
1334 aware.
1335
1336 \section{Sign Manipulation}
1337 \subsection{Negation}
1338 \label{sec:NEG}
1339 Simple integer negation can be performed with the following.
1340
1341 \index{mp\_neg}
1342 \begin{alltt}
1343 int mp_neg (mp_int * a, mp_int * b);
1344 \end{alltt}
1345
1346 Which assigns $-a$ to $b$.
1347
1348 \subsection{Absolute}
1349 Simple integer absolutes can be performed with the following.
1350
1351 \index{mp\_abs}
1352 \begin{alltt}
1353 int mp_abs (mp_int * a, mp_int * b);
1354 \end{alltt}
1355
1356 Which assigns $\vert a \vert$ to $b$.
1357
1358 \section{Integer Division and Remainder}
1359 To perform a complete and general integer division with remainder use the following function.
1360
1361 \index{mp\_div}
1362 \begin{alltt}
1363 int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d);
1364 \end{alltt}
1365
1366 This 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}
1373 A full signed integer multiplication can be performed with the following.
1374 \index{mp\_mul}
1375 \begin{alltt}
1376 int mp_mul (mp_int * a, mp_int * b, mp_int * c);
1377 \end{alltt}
1378 Which assigns the full signed product $ab$ to $c$.  This function actually breaks into one of four cases which are
1379 specific multiplication routines optimized for given parameters.  First there are the Toom-Cook multiplications which
1380 should only be used with very large inputs.  This is followed by the Karatsuba multiplications which are for moderate
1381 sized inputs.  Then followed by the Comba and baseline multipliers.
1382
1383 Fortunately for the developer you don't really need to know this unless you really want to fine tune the system.  mp\_mul()
1384 will 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}
1387 int 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
1422 If this program succeeds it shall output the following.
1423
1424 \begin{alltt}
1425 number1 * number2 == 262911
1426 \end{alltt}
1427
1428 \section{Squaring}
1429 Since squaring can be performed faster than multiplication it is performed it's own function instead of just using
1430 mp\_mul().
1431
1432 \index{mp\_sqr}
1433 \begin{alltt}
1434 int mp_sqr (mp_int * a, mp_int * b);
1435 \end{alltt}
1436
1437 Will square $a$ and store it in $b$.  Like the case of multiplication there are four different squaring
1438 algorithms all which can be called from mp\_sqr().  It is ideal to use mp\_sqr over mp\_mul when squaring terms because
1439 of the speed difference.
1440
1441 \section{Tuning Polynomial Basis Routines}
1442
1443 Both of the Toom-Cook and Karatsuba multiplication algorithms are faster than the traditional $O(n^2)$ approach that
1444 the Comba and baseline algorithms use.  At $O(n^{1.464973})$ and $O(n^{1.584962})$ running times respectively they require
1445 considerably less work.  For example, a 10000-digit multiplication would take roughly 724,000 single precision
1446 multiplications with Toom-Cook or 100,000,000 single precision multiplications with the standard Comba (a factor
1447 of 138).
1448
1449 So why not always use Karatsuba or Toom-Cook?   The simple answer is that they have so much overhead that they're not
1450 actually faster than Comba until you hit distinct  ``cutoff'' points.  For Karatsuba with the default configuration,
1451 GCC 3.3.1 and an Athlon XP processor the cutoff point is roughly 110 digits (about 70 for the Intel P4).  That is, at
1452 110 digits Karatsuba and Comba multiplications just about break even and for 110+ digits Karatsuba is faster.
1453
1454 Toom-Cook has incredible overhead and is probably only useful for very large inputs.  So far no known cutoff points
1455 exist and for the most part I just set the cutoff points very high to make sure they're not called.
1456
1457 To get reasonable values for the cut-off points for your architecture, type
1458
1459 \begin{alltt}
1460 make tune
1461 \end{alltt}
1462
1463 This will run a benchmark, computes the medians, rewrites \texttt{bncore.c}, and recompiles \texttt{bncore.c} and relinks the library.
1464
1465 The benchmark itself can be fine-tuned in the file \texttt{etc/tune\_it.sh}.
1466
1467 The 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
1471 Modular reduction is process of taking the remainder of one quantity divided by another.  Expressed
1472 as (\ref{eqn:mod}) the modular reduction is equivalent to the remainder of $b$ divided by $c$.
1473
1474 \begin{equation}
1475 a \equiv b \mbox{ (mod }c\mbox{)}
1476 \label{eqn:mod}
1477 \end{equation}
1478
1479 Of particular interest to cryptography are reductions where $b$ is limited to the range $0 \le b < c^2$ since particularly
1480 fast reduction algorithms can be written for the limited range.
1481
1482 Note that one of the four optimized reduction algorithms are automatically chosen in the modular exponentiation
1483 algorithm mp\_exptmod when an appropriate modulus is detected.
1484
1485 \section{Straight Division}
1486 In order to effect an arbitrary modular reduction the following algorithm is provided.
1487
1488 \index{mp\_mod}
1489 \begin{alltt}
1490 int mp_mod(mp_int *a, mp_int *b, mp_int *c);
1491 \end{alltt}
1492
1493 This reduces $a$ modulo $b$ and stores the result in $c$.  The sign of $c$ shall agree with the sign
1494 of $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
1498 Barrett reduction is a generic optimized reduction algorithm that requires pre--computation to achieve
1499 a 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}
1503 int mp_reduce_setup(mp_int *a, mp_int *b);
1504 \end{alltt}
1505
1506 Given a modulus in $b$ this produces the required $\mu$ value in $a$.  For any given modulus this only has to
1507 be computed once.  Modular reduction can now be performed with the following.
1508
1509 \index{mp\_reduce}
1510 \begin{alltt}
1511 int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
1512 \end{alltt}
1513
1514 This 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}
1518 int 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
1568 This program will calculate $a^3 \mbox{ mod }b$ if all the functions succeed.
1569
1570 \section{Montgomery Reduction}
1571
1572 Montgomery is a specialized reduction algorithm for any odd moduli.  Like Barrett reduction a pre--computation
1573 step is required.  This is accomplished with the following.
1574
1575 \index{mp\_montgomery\_setup}
1576 \begin{alltt}
1577 int mp_montgomery_setup(mp_int *a, mp_digit *mp);
1578 \end{alltt}
1579
1580 For the given odd moduli $a$ the precomputation value is placed in $mp$.  The reduction is computed with the
1581 following.
1582
1583 \index{mp\_montgomery\_reduce}
1584 \begin{alltt}
1585 int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
1586 \end{alltt}
1587 This 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
1590 Montgomery reduction is faster than Barrett reduction for moduli smaller than the ``comba'' limit.  With the default
1591 setup 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
1594 An important observation is that this reduction does not return $a \mbox{ mod }m$ but $aR^{-1} \mbox{ mod }m$
1595 where $R = \beta^n$, $n$ is the n number of digits in $m$ and $\beta$ is radix used (default is $2^{28}$).
1596
1597 To quickly calculate $R$ the following function was provided.
1598
1599 \index{mp\_montgomery\_calc\_normalization}
1600 \begin{alltt}
1601 int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
1602 \end{alltt}
1603 Which calculates $a = R$ for the odd moduli $b$ without using multiplication or division.
1604
1605 The normal modus operandi for Montgomery reductions is to normalize the integers before entering the system.  For
1606 example, to calculate $a^3 \mbox { mod }b$ using Montgomery reduction the value of $a$ can be normalized by
1607 multiplying it by $R$.  Consider the following code snippet.
1608
1609 \begin{alltt}
1610 int 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
1682 This particular example does not look too efficient but it demonstrates the point of the algorithm.  By
1683 normalizing the inputs the reduced results are always of the form $aR$ for some variable $a$.  This allows
1684 a single final reduction to correct for the normalization and the fast reduction used within the algorithm.
1685
1686 For 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
1691 digit shifting and small multiplications.  In this case the ``restricted'' variant refers to moduli of the
1692 form $\beta^k - p$ for some $k \ge 0$ and $0 < p < \beta$ where $\beta$ is the radix (default to $2^{28}$).
1693
1694 As 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}
1698 void mp_dr_setup(mp_int *a, mp_digit *d);
1699 \end{alltt}
1700
1701 This computes the value required for the modulus $a$ and stores it in $d$.  This function cannot fail
1702 and does not return any error codes.  After the pre--computation a reduction can be performed with the
1703 following.
1704
1705 \index{mp\_dr\_reduce}
1706 \begin{alltt}
1707 int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
1708 \end{alltt}
1709
1710 This reduces $a$ in place modulo $b$ with the pre--computed value $mp$.  $b$ must be of a restricted
1711 diminished radix form and $a$ must be in the range $0 \le a < b^2$.  Diminished radix reductions are
1712 much faster than both Barrett and Montgomery reductions as they have a much lower asymptotic running time.
1713
1714 Since the moduli are restricted this algorithm is not particularly useful for something like Rabin, RSA or
1715 BBS cryptographic purposes.  This reduction algorithm is useful for Diffie-Hellman and ECC where fixed
1716 primes are acceptable.
1717
1718 Note that unlike Montgomery reduction there is no normalization process.  The result of this function is
1719 equal to the correct residue.
1720
1721 \section{Unrestricted Diminished Radix}
1722
1723 Unrestricted reductions work much like the restricted counterparts except in this case the moduli is of the
1724 form $2^k - p$ for $0 < p < \beta$.  In this sense the unrestricted reductions are more flexible as they
1725 can be applied to a wider range of numbers.
1726
1727 \index{mp\_reduce\_2k\_setup}
1728 \begin{alltt}
1729 int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
1730 \end{alltt}
1731
1732 This will compute the required $d$ value for the given moduli $a$.
1733
1734 \index{mp\_reduce\_2k}
1735 \begin{alltt}
1736 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
1737 \end{alltt}
1738
1739 This will reduce $a$ in place modulo $n$ with the pre--computed value $d$.  From my experience this routine is
1740 slower than mp\_dr\_reduce but faster for most moduli sizes than the Montgomery reduction.
1741
1742 \section{Combined Modular Reduction}
1743
1744 Some of the combinations of an arithmetic operations followed by a modular reduction can be done in a faster way. The ones implemented are:
1745
1746 Addition $d = (a + b) \mod c$
1747 \index{mp\_addmod}
1748 \begin{alltt}
1749 int mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1750 \end{alltt}
1751
1752 Subtraction  $d = (a - b) \mod c$
1753 \begin{alltt}
1754 int mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1755 \end{alltt}
1756
1757 Multiplication $d = (ab) \mod c$
1758 \begin{alltt}
1759 int mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1760 \end{alltt}
1761
1762 Squaring  $d = (a^2) \mod c$
1763 \begin{alltt}
1764 int 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}
1773 int mp_expt_d (mp_int * a, mp_digit b, mp_int * c)
1774 \end{alltt}
1775 This function computes $c = a^b$.
1776
1777 \section{Modular Exponentiation}
1778 \index{mp\_exptmod}
1779 \begin{alltt}
1780 int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
1781 \end{alltt}
1782 This computes $Y \equiv G^X \mbox{ (mod }P\mbox{)}$ using a variable width sliding window algorithm.  This function
1783 will 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
1787 This function is actually a shell around the two internal exponentiation functions.  This routine will automatically
1788 detect when Barrett, Montgomery, Restricted and Unrestricted Diminished Radix based exponentiation can be used.  Generally
1789 moduli of the a ``restricted diminished radix'' form lead to the fastest modular exponentiations.  Followed by Montgomery
1790 and the other two algorithms.
1791
1792 \section{Modulus a Power of Two}
1793 \index{mp\_mod\_2d}
1794 \begin{alltt}
1795 int mp_mod_2d(const mp_int *a, int b, mp_int *c)
1796 \end{alltt}
1797 It calculates $c = a \mod 2^b$.
1798
1799 \section{Root Finding}
1800 \index{mp\_n\_root}
1801 \begin{alltt}
1802 int mp_n_root (mp_int * a, mp_digit b, mp_int * c)
1803 \end{alltt}
1804 This 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
1805 a root with the sign of the input for odd roots.  For example, performing $4^{1/2}$ will return $2$ whereas $(-8)^{1/3}$
1806 will return $-2$.
1807
1808 This algorithm uses the ``Newton Approximation'' method and will converge on the correct root fairly quickly.
1809
1810 The 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}
1814 int mp_sqrt (mp_int * a, mp_digit b, mp_int * c)
1815 \end{alltt}
1816
1817
1818 \chapter{Logarithm}
1819 \section{Integer Logarithm}
1820 A 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}
1823 int 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
1833 int 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}
1887 int mp_prime_is_divisible (mp_int * a, int *result)
1888 \end{alltt}
1889 This will attempt to evenly divide $a$ by a list of primes\footnote{Default is the first 256 primes.} and store the
1890 outcome in ``result''.  That is if $result = 0$ then $a$ is not divisible by the primes, otherwise it is.  Note that
1891 if the function does not return \textbf{MP\_OKAY} the value in ``result'' should be considered undefined\footnote{Currently
1892 the default is to set it to zero first.}.
1893
1894 \section{Fermat Test}
1895 \index{mp\_prime\_fermat}
1896 \begin{alltt}
1897 int mp_prime_fermat (mp_int * a, mp_int * b, int *result)
1898 \end{alltt}
1899 Performs a Fermat primality test to the base $b$.  That is it computes $b^a \mbox{ mod }a$ and tests whether the value is
1900 equal to $b$ or not.  If the values are equal then $a$ is probably prime and $result$ is set to one.  Otherwise $result$
1901 is set to zero.
1902
1903 \section{Miller-Rabin Test}
1904 \index{mp\_prime\_miller\_rabin}
1905 \begin{alltt}
1906 int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
1907 \end{alltt}
1908 Performs a Miller-Rabin test to the base $b$ of $a$.  This test is much stronger than the Fermat test and is very hard to
1909 fool (besides with Carmichael numbers).  If $a$ passes the test (therefore is probably prime) $result$ is set to one.
1910 Otherwise $result$ is set to zero.
1911
1912 Note that is suggested that you use the Miller-Rabin test instead of the Fermat test since all of the failures of
1913 Miller-Rabin are a subset of the failures of the Fermat test.
1914
1915 \subsection{Required Number of Tests}
1916 Generally to ensure a number is very likely to be prime you have to perform the Miller-Rabin with at least a half-dozen
1917 or so unique bases.  However, it has been proven that the probability of failure goes down as the size of the input goes up.
1918 This is why a simple function has been provided to help out.
1919
1920 \index{mp\_prime\_rabin\_miller\_trials}
1921 \begin{alltt}
1922 int mp_prime_rabin_miller_trials(int size)
1923 \end{alltt}
1924 This 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
1955 You should always still perform a trial division before a Miller-Rabin test though.
1956
1957 A 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}.
1958 The first column is the number of bits $b$ in the prime $p = 2^b$, the numbers in the first row represent the
1959 probability 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}}$ \\
1965 80    & 31 & 39 & 47 & 55 & 71 & 87  \\
1966 96    & 29 & 37 & 45 & 53 & 69 & 85  \\
1967 128   & 24 & 32 & 40 & 48 & 64 & 80  \\
1968 160   & 19 & 27 & 35 & 43 & 59 & 75  \\
1969 192   & 15 & 21 & 29 & 37 & 53 & 69  \\
1970 256   & 10 & 15 & 20 & 27 & 43 & 59  \\
1971 384   & 7  & 9  & 12 & 16 & 25 & 38  \\
1972 512   & 5  & 7  & 9  & 12 & 18 & 26  \\
1973 768   & 4  & 5  & 6  & 8  & 11 & 16  \\
1974 1024  & 3  & 4  & 5  & 6  & 9  & 12  \\
1975 1536  & 2  & 3  & 3  & 4  & 6  & 8   \\
1976 2048  & 2  & 2  & 3  & 3  & 4  & 6   \\
1977 3072  & 1  & 2  & 2  & 2  & 3  & 4   \\
1978 4096  & 1  & 1  & 2  & 2  & 2  & 3   \\
1979 6144  & 1  & 1  & 1  & 1  & 2  & 2   \\
1980 8192  & 1  & 1  & 1  & 1  & 2  & 2   \\
1981 12288 & 1  & 1  & 1  & 1  & 1  & 1   \\
1982 16384 & 1  & 1  & 1  & 1  & 1  & 1   \\
1983 24576 & 1  & 1  & 1  & 1  & 1  & 1   \\
1984 32768 & 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}}$\\
1994 80    & 103 & 119 & 135 & 151 & 167 & 183 & 199 \\
1995 96    & 101 & 117 & 133 & 149 & 165 & 181 & 197 \\
1996 128   & 96  & 112 & 128 & 144 & 160 & 176 & 192 \\
1997 160   & 91  & 107 & 123 & 139 & 155 & 171 & 187 \\
1998 192   & 85  & 101 & 117 & 133 & 149 & 165 & 181 \\
1999 256   & 75  & 91  & 107 & 123 & 139 & 155 & 171 \\
2000 384   & 54  & 70  & 86  & 102 & 118 & 134 & 150 \\
2001 512   & 36  & 49  & 65  & 81  & 97  & 113 & 129 \\
2002 768   & 22  & 29  & 37  & 47  & 58  & 70  & 86  \\
2003 1024  & 16  & 21  & 26  & 33  & 40  & 48  & 58  \\
2004 1536  & 10  & 13  & 17  & 21  & 25  & 30  & 35  \\
2005 2048  & 8   & 10  & 13  & 15  & 18  & 22  & 26  \\
2006 3072  & 5   & 7   & 8   & 10  & 12  & 14  & 17  \\
2007 4096  & 4   & 5   & 6   & 8   & 9   & 11  & 12  \\
2008 6144  & 3   & 4   & 4   & 5   & 6   & 7   & 8   \\
2009 8192  & 2   & 3   & 3   & 4   & 5   & 6   & 6   \\
2010 12288 & 2   & 2   & 2   & 3   & 3   & 4   & 4   \\
2011 16384 & 1   & 2   & 2   & 2   & 3   & 3   & 3   \\
2012 24576 & 1   & 1   & 2   & 2   & 2   & 2   & 2   \\
2013 32768 & 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
2019 Determining 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
2021 If 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
2023 This 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
2025 This function can be used to test a DSA prime directly if these rounds are followed by a Lucas test.
2026
2027 See 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}
2032 int mp_prime_strong_lucas_selfridge(const mp_int *a, int *result)
2033 \end{alltt}
2034 Performs 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
2035 from the Libtommath build if not needed.
2036
2037 \section{Frobenius (Underwood)  Test}
2038 \index{mp\_prime\_frobenius\_underwood}
2039 \begin{alltt}
2040 int mp_prime_frobenius_underwood(const mp_int *N, int *result)
2041 \end{alltt}
2042 Performs 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
2044 if the preprocessor macro \texttt{LTM\_USE\_FROBENIUS\_TEST} is defined.
2045
2046 It 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}
2049 Testing 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}
2052 int mp_is_square(const mp_int *arg, int *ret);
2053 \end{alltt}
2054
2055
2056 \index{mp\_prime\_is\_prime}
2057 \begin{alltt}
2058 int mp_prime_is_prime (mp_int * a, int t, int *result)
2059 \end{alltt}
2060 This 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
2062 the 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
2064 If $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
2066 One 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
2068 If  $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
2070 If $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}
2075 int mp_prime_next_prime(mp_int *a, int t, int bbs_style)
2076 \end{alltt}
2077 This finds the next prime after $a$ that passes mp\_prime\_is\_prime() with $t$ tests but see the documentation for
2078 mp\_prime\_is\_prime for details regarding the use of the argument $t$.  Set $bbs\_style$ to one if you
2079 want 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}
2084 int mp_prime_rand(mp_int *a,    int t,
2085                   int     size, int flags);
2086 \end{alltt}
2087 This will generate a prime in $a$ using $t$ tests of the primality testing algorithms.
2088 See the documentation for mp\_prime\_is\_prime for details regarding the use of the argument $t$.
2089 The variable $size$ specifies the bit length of the prime desired.
2090 The variable $flags$ specifies one of several options available
2091 (see fig. \ref{fig:primeopts}) which can be OR'ed together.
2092
2093 The function mp\_prime\_rand() is suitable for generating primes which must be secret (as in the case of RSA) since there
2094 is 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}
2122 int mp_rand_digit(mp_digit *r)
2123 \end{alltt}
2124 This 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}
2128 int mp_rand(mp_int *a, int digits)
2129 \end{alltt}
2130 This function generates a random number of \texttt{digits} bits.
2131
2132 The 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}
2140 int mp_to_radix (mp_int *a, char *str, size_t maxlen, size_t *written, int radix);
2141 \end{alltt}
2142 This 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
2144 Valid values of \texttt{radix} line in the range $[2, 64]$.
2145
2146 The 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
2148 If \texttt{str} is not big enough to hold $a$, \texttt{str} will be filled with the least-significant digits
2149 of length \texttt{maxlen-1}, then \texttt{str} will be \texttt{NUL} terminated and the error \texttt{MP\_VAL} is returned.
2150
2151 Please 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}
2156 int mp_radix_size (mp_int * a, int radix, int *size)
2157 \end{alltt}
2158 This stores in ``size'' the number of characters (including space for the NUL terminator) required.  Upon error this
2159 function returns an error code and ``size'' will be zero.
2160
2161 If \texttt{LTM\_NO\_FILE} is not defined a function to write to a file is also available.
2162 \index{mp\_fwrite}
2163 \begin{alltt}
2164 int 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}
2171 int mp_read_radix (mp_int * a, char *str, int radix);
2172 \end{alltt}
2173 This will read the base-``radix'' NUL terminated string from ``str'' into $a$.  It will stop reading when it reads a
2174 character it does not recognize (which happens to include th NUL char... imagine that...).  A single leading $-$ sign
2175 can be used to denote a negative number.
2176
2177 If \texttt{LTM\_NO\_FILE} is not defined a function to read from a file is also available.
2178 \index{mp\_fread}
2179 \begin{alltt}
2180 int mp_fread(mp_int *a, int radix, FILE *stream);
2181 \end{alltt}
2182
2183
2184 \section{Binary Conversions}
2185
2186 Converting an mp\_int to and from binary is another keen idea.
2187
2188 \index{mp\_ubin\_size}
2189 \begin{alltt}
2190 size_t mp_ubin_size(mp_int *a);
2191 \end{alltt}
2192
2193 This 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}
2197 int mp_to_unsigned_bin(mp_int *a, unsigned char *b, size_t maxlen, size_t *len);
2198 \end{alltt}
2199 This 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}
2203 int mp_from_ubin(mp_int *a, unsigned char *b, size_t size);
2204 \end{alltt}
2205 This 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
2207 For those who acknowledge the existence of negative numbers (heretic!) there are ``signed'' versions of the
2208 previous functions.
2209 \index{mp\_signed\_bin\_size} \index{mp\_to\_signed\_bin} \index{mp\_read\_signed\_bin}
2210 \begin{alltt}
2211 int mp_sbin_size(mp_int *a);
2212 int mp_from_sbin(mp_int *a, unsigned char *b, size_t size);
2213 int mp_to_sbin(mp_int *a, unsigned char *b, size_t maxsize, size_t *len);
2214 \end{alltt}
2215 They operate essentially the same as the unsigned copies except they prefix the data with zero or non--zero
2216 byte depending on the sign.  If the sign is zpos (e.g. not negative) the prefix is zero, otherwise the prefix
2217 is non--zero.
2218
2219 The 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}
2222 int 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);
2224 int 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}
2227 The 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 */
2230 size_t mp_pack_size(mp_int *a, size_t nails, size_t size);
2231 \end{alltt}
2232 To get the size in bytes necessary to be put in \texttt{maxsize}).
2233
2234 To enhance the readability of your code, the following enums have been wrought for your convenience.
2235 \begin{alltt}
2236 typedef enum {
2237    MP_LSB_FIRST = -1,
2238    MP_MSB_FIRST =  1
2239 } mp_order;
2240 typedef 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}
2251 int mp_exteuclid(mp_int *a, mp_int *b,
2252                  mp_int *U1, mp_int *U2, mp_int *U3);
2253 \end{alltt}
2254
2255 This finds the triple U1/U2/U3 using the Extended Euclidean algorithm such that the following equation holds.
2256
2257 \begin{equation}
2258 a \cdot U1 + b \cdot U2 = U3
2259 \end{equation}
2260
2261 Any 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}
2266 int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
2267 \end{alltt}
2268 This 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}
2273 int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
2274 \end{alltt}
2275 This 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}
2280 int mp_jacobi (mp_int * a, mp_int * p, int *c)
2281 \end{alltt}
2282 This will compute the Jacobi symbol for $a$ with respect to $p$.  If $p$ is prime this essentially computes the Legendre
2283 symbol.  The result is stored in $c$ and can take on one of three values $\lbrace -1, 0, 1 \rbrace$.  If $p$ is prime
2284 then the result will be $-1$ when $a$ is not a quadratic residue modulo $p$.  The result will be $0$ if $a$ divides $p$
2285 and 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}
2290 int mp_kronecker (mp_int * a, mp_int * p, int *c)
2291 \end{alltt}
2292 Extension 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}
2298 int mp_sqrtmod_prime(mp_int *n, mp_int *p, mp_int *r)
2299 \end{alltt}
2300
2301 This will solve the modular equatioon $r^2 = n \mod p$ where $p$ is a prime number greater than 2 (odd prime).
2302 The result is returned in the third argument $r$, the function returns \textbf{MP\_OKAY} on success,
2303 other return values indicate failure.
2304
2305 The implementation is split for two different cases:
2306
2307 1. 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
2310 2. otherwise we use \href{https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm}{Tonelli-Shanks algorithm}
2311
2312 The function does not check the primality of parameter $p$ thus it is up to the caller to assure that this parameter
2313 is 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}
2319 int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
2320 \end{alltt}
2321 Computes 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
2325 For 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}
2329 int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
2330 int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
2331 int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
2332 int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
2333 int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
2334 \end{alltt}
2335
2336 These work like the full mp\_int capable variants except the second parameter $b$ is a mp\_digit.  These
2337 functions fairly handy if you have to work with relatively small numbers since you will not have to allocate
2338 an entire mp\_int to store a number like $1$ or $2$.
2339
2340 The 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}
2342 int mp_incr(mp_int *a);
2343 int mp_decr(mp_int *a);
2344 \end{alltt}
2345
2346
2347 The 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}
2351 int mp_div_3(const mp_int *a, mp_int *c, mp_digit *d);
2352 \end{alltt}
2353
2354 \chapter{Little Helpers}
2355 It is never wrong to have some useful little shortcuts at hand.
2356 \section{Function Macros}
2357 To 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}
2361 int mp_iseven(mp_int *a)
2362 \end{alltt}
2363 Checks if $a = 0 mod 2$
2364
2365 \index{mp\_isodd}
2366 \begin{alltt}
2367 int mp_isodd(mp_int *a)
2368 \end{alltt}
2369 Checks if $a = 1 mod 2$
2370
2371 \index{mp\_isneg}
2372 \begin{alltt}
2373 int mp_isneg(mp_int *a)
2374 \end{alltt}
2375 Checks if $a < 0$
2376
2377
2378 \index{mp\_iszero}
2379 \begin{alltt}
2380 int mp_iszero(mp_int *a)
2381 \end{alltt}
2382 Checks if $a = 0$. It does not check if the amount of memory allocated for $a$ is also minimal.
2383
2384
2385 Other 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}
2455 The 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}
2457 log2(x) = log(x)/log(2)
2458
2459 fips_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
2470 fips_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
2482 fips_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
2499 To 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}