1 \documentclass[synpaper]{book}
12 \def\getsrandom{\stackrel{\rm R}{\gets}}
14 \def\cat{\hspace{0.5em} \| \hspace{0.5em}}
16 \def\divides{\hspace{0.3em} | \hspace{0.3em}}
17 \def\nequiv{\not\equiv}
18 \def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
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}
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}}
38 \newcommand{\str}[1]{{\mathbf{#1}}}
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}}
53 \title{LibTomMath User Manual \\ v1.2.0}
54 \author{LibTom Projects \\ www.libtom.net}
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.
61 \begin{flushright}Open Source. Open Academia. Open Minds.
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
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.
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.
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.
97 \section{Building LibTomMath}
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.
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.
106 CC=/home/czurnieden/intel/bin/icc make
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:
111 icc: command line warning #10148: option '-Wbad-function-cast' not supported
112 icc: command line warning #10148: option '-Wcast-align' not supported
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.}.
116 \subsection{Static Libraries}
117 To build as a static library for GCC issue the following
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
125 nmake -f makefile.msvc
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.
131 To run a program to adapt the Toom-Cook cut-off values to your architecture type
135 This will take some time.
137 \subsection{Shared Libraries}
138 \subsubsection{GNU based Operating Systems}
139 To build as a shared library for GCC issue the following
141 make -f makefile.shared
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.
148 To run a program to adapt the Toom-Cook cut-off values to your architecture type
150 make -f makefile.shared tune
152 This will take some time.
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}.
161 The wrong \texttt{make} will result in errors like:
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)
171 The wrong \texttt{libtool} will build it all fine but when it comes to the final linking fails with
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
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.
187 $ sudo pkg_add gmake libtool
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}
191 $ /usr/local/bin/libtool --version
192 libtool (GNU libtool) 2.4.2
193 Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
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.
199 libtool (not (GNU libtool)) 1.5.26
202 The shared library should build now with
204 LIBTOOL="/usr/local/bin/libtool" gmake -f makefile.shared
206 You might need to run a \texttt{gmake -f makefile.shared clean} first.
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.
211 pkg_add gmake libtool
213 Please check with \texttt{libtool --version} that installed libtool is indeed a GNU libtool.
214 Build the shared library by typing:
216 gmake -f makefile.shared
220 To build the library and the test harness type
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
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
238 myprng | mtest/mtest | test
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.
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.
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.
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.
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.
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''.
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.
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 \\
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.
291 \subsubsection{Moduli Related}
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 \\
315 \subsubsection{Operand Size Related}
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 \\
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.
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
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!).
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}.
352 \newpage\begin{figure}[h]
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. \\
368 \caption{LibTomMath Valuation}
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.
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.
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).
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.
390 \section{Return Codes}
391 There are three possible return codes a function may return.
393 \index{MP\_OKAY}\index{MP\_YES}\index{MP\_NO}\index{MP\_VAL}\index{MP\_MEM}
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. \\
403 \hline MP\_YES & Response is yes. \\
404 \hline MP\_NO & Response is no. \\
409 \caption{Return Codes}
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.
416 \index{mp\_error\_to\_string}
418 char *mp_error_to_string(int code);
421 This will return a pointer to a string which describes the given error code. It will not work for the return codes
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
432 int used, alloc, sign;
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.
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.
445 \section{Function Organization}
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,
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 */
456 Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
460 mp_add(&a, &b, &b); /* b = a + b */
461 mp_div(&a, &b, &a, &c); /* a = [a/b], c = a mod b */
464 This allows operands to be re-used which can make programming simpler.
466 \section{Initialization}
467 \subsection{Single Initialization}
468 A single mp\_int can be initialized with the ``mp\_init'' function.
472 int mp_init (mp_int * a);
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.
479 \begin{small} \begin{alltt}
485 if ((result = mp_init(&number)) != MP_OKAY) \{
486 printf("Error initializing the number. \%s",
487 mp_error_to_string(result));
495 \end{alltt} \end{small}
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.
503 void mp_clear (mp_int * a);
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.
510 \begin{small} \begin{alltt}
516 if ((result = mp_init(&number)) != MP_OKAY) \{
517 printf("Error initializing the number. \%s",
518 mp_error_to_string(result));
524 /* We're done with it. */
529 \end{alltt} \end{small}
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
536 The mp\_init\_multi() function provides this functionality.
538 \index{mp\_init\_multi} \index{mp\_clear\_multi}
540 int mp_init_multi(mp_int *mp, ...);
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.
548 \begin{small} \begin{alltt}
551 mp_int num1, num2, num3;
554 if ((result = mp_init_multi(&num1,
556 &num3, NULL)) != MP\_OKAY) \{
557 printf("Error initializing the numbers. \%s",
558 mp_error_to_string(result));
562 /* use the numbers */
564 /* We're done with them. */
565 mp_clear_multi(&num1, &num2, &num3, NULL);
569 \end{alltt} \end{small}
571 \subsection{Other Initializers}
572 To initialized and make a copy of an mp\_int the mp\_init\_copy() function has been provided.
574 \index{mp\_init\_copy}
576 int mp_init_copy (mp_int * a, mp_int * b);
579 This function will initialize $a$ and make it a copy of $b$ if all goes well.
581 \begin{small} \begin{alltt}
587 /* initialize and do work on num1 ... */
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));
596 /* now num2 is ready and contains a copy of num1 */
598 /* We're done with them. */
599 mp_clear_multi(&num1, &num2, NULL);
603 \end{alltt} \end{small}
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.
609 \index{mp\_init\_size}
611 int mp_init_size (mp_int * a, int size);
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).
617 \begin{small} \begin{alltt}
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));
634 \end{alltt} \end{small}
636 \section{Maintenance Functions}
637 \subsection{Clear Leading Zeros}
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.
644 void mp_clamp(mp_int *a);
647 \subsection{Zero Out}
649 This function will set the ``bigint'' to zeros without changing the amount of allocated memory.
653 void mp_zero(mp_int *a);
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.
663 int mp_shrink (mp_int * a);
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).
671 \begin{small} \begin{alltt}
677 if ((result = mp_init(&number)) != MP_OKAY) \{
678 printf("Error initializing the number. \%s",
679 mp_error_to_string(result));
683 /* use the number [e.g. pre-computation] */
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));
695 /* we're done with it. */
700 \end{alltt} \end{small}
702 \subsection{Adding additional digits}
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
712 int mp_grow (mp_int * a, int size);
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.
718 \begin{small} \begin{alltt}
724 if ((result = mp_init(&number)) != MP_OKAY) \{
725 printf("Error initializing the number. \%s",
726 mp_error_to_string(result));
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));
742 /* we're done with it. */
747 \end{alltt} \end{small}
749 \chapter{Basic Operations}
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.
756 int mp_copy (mp_int * a, mp_int *b);
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.
763 void mp_exch (mp_int * a, mp_int *b);
766 \section{Bit Counting}
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 )
772 int mp_cnt_lsb(const mp_int *a);
775 To get the position of the highest bit set (MSB, the Most Significant Bit; the number of bits in teh ``bignum'')
777 \index{mp\_count\_bits}
779 int mp_count_bits(const mp_int *a);
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$).
789 \subsection{Single Digit}
791 Setting a single digit can be accomplished with the following function.
795 void mp_set (mp_int * a, mp_digit b);
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
802 \begin{small} \begin{alltt}
808 if ((result = mp_init(&number)) != MP_OKAY) \{
809 printf("Error initializing the number. \%s",
810 mp_error_to_string(result));
814 /* set the number to 5 */
817 /* we're done with it. */
822 \end{alltt} \end{small}
824 \subsection{Int32 and Int64 Constants}
826 These functions can be used to set a constant with 32 or 64 bits.
828 \index{mp\_set\_i32} \index{mp\_set\_u32}
829 \index{mp\_set\_i64} \index{mp\_set\_u64}
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);
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.
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}
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);
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.
854 \begin{small} \begin{alltt}
860 if ((result = mp_init(&number)) != MP_OKAY) \{
861 printf("Error initializing the number. \%s",
862 mp_error_to_string(result));
866 /* set the number to 654321 (note this is bigger than 127) */
867 mp_set_u32(&number, 654321);
869 printf("number == \%" PRIi32, mp_get_i32(&number));
871 /* we're done with it. */
876 \end{alltt} \end{small}
878 This should output the following if the program succeeds.
884 \subsection{Long Constants - platform dependant}
886 \index{mp\_set\_l} \index{mp\_set\_ul}
888 void mp_set_l (mp_int * a, long b);
889 void mp_set_ul (mp_int * a, unsigned long b);
892 This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
894 To retrieve the value, the following functions can be used.
896 \index{mp\_get\_l} \index{mp\_get\_ul} \index{mp\_get\_mag\_ul}
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);
903 This will return the least significant bits of the mp\_int $a$ that fit into a ``long''.
905 \subsection{Long Long Constants - platform dependant}
907 \index{mp\_set\_ll} \index{mp\_set\_ull}
909 void mp_set_ll (mp_int * a, long long b);
910 void mp_set_ull (mp_int * a, unsigned long long b);
913 This will assign the value of the platform-dependent sized variable $b$ to the mp\_int $a$.
915 To retrieve the value, the following functions can be used.
919 \index{mp\_get\_mag\_ull}
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);
926 This will return the least significant bits of the mp\_int $a$ that fit into a ``long long''.
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}
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);
943 Both functions work like the previous counterparts except they first mp\_init $a$ before setting the values.
948 mp_int number1, number2;
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));
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));
966 printf("Number1, Number2 == \%" PRIi32 ", \%" PRIi32,
967 mp_get_i32(&number1), mp_get_i32(&number2));
970 mp_clear_multi(&number1, &number2, NULL);
976 If this program succeeds it shall output.
978 Number1, Number2 == 100, 1023
981 \section{Comparisons}
983 Comparisons in LibTomMath are always performed in a ``left to right'' fashion. There are three possible return codes
986 \index{MP\_GT} \index{MP\_EQ} \index{MP\_LT}
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$ \\
997 \caption{Comparison Codes for $a, b$}
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
1004 \subsection{Unsigned comparison}
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.
1010 \index{mp\_cmp\_mag}
1012 int mp_cmp_mag(mp_int * a, mp_int * b);
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}.
1017 \begin{small} \begin{alltt}
1020 mp_int number1, number2;
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;
1029 /* set the number1 to 5 */
1030 mp_set(&number1, 5);
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;
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;
1046 /* we're done with it. */
1047 mp_clear_multi(&number1, &number2, NULL);
1049 return EXIT_SUCCESS;
1051 \end{alltt} \end{small}
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.
1057 |number1| < |number2|
1060 This is because $\vert -6 \vert = 6$ and obviously $5 < 6$.
1062 \subsection{Signed comparison}
1064 To compare two mp\_int variables based on their signed value the mp\_cmp() function is provided.
1068 int mp_cmp(mp_int * a, mp_int * b);
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}.
1075 \begin{small} \begin{alltt}
1078 mp_int number1, number2;
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;
1087 /* set the number1 to 5 */
1088 mp_set(&number1, 5);
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;
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;
1104 /* we're done with it. */
1105 mp_clear_multi(&number1, &number2, NULL);
1107 return EXIT_SUCCESS;
1109 \end{alltt} \end{small}
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.
1118 \subsection{Single Digit}
1120 To compare a single digit against an mp\_int the following function has been provided.
1124 int mp_cmp_d(mp_int * a, mp_digit b);
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}.
1133 \begin{small} \begin{alltt}
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;
1145 /* set the number to 5 */
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;
1154 /* we're done with it. */
1157 return EXIT_SUCCESS;
1159 \end{alltt} \end{small}
1161 If this program functions properly it will print out the following.
1167 \section{Logical Operations}
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.
1172 \subsection{Multiplication by two}
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.
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}
1180 int mp_mul_2(mp_int * a, mp_int * b);
1181 int mp_div_2(mp_int * a, mp_int * b);
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.
1187 \begin{small} \begin{alltt}
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;
1199 /* set the number to 5 */
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;
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;
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;
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;
1226 /* we're done with it. */
1229 return EXIT_SUCCESS;
1231 \end{alltt} \end{small}
1233 If this program is successful it will print out the following text.
1240 Since $10 > 7$ and $5 < 7$.
1242 To multiply by a power of two the following function can be used.
1246 int mp_mul_2d(mp_int * a, int b, mp_int * c);
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.
1253 To divide by a power of two use the following.
1257 int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d);
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.
1264 It is also not very uncommon to need just the power of two $2^b$; for example the startvalue for the Newton method.
1268 int mp_2expt(mp_int *a, int b);
1270 It is faster than doing it by shifting $1$ with \texttt{mp\_mul\_2d}.
1272 \subsection{Polynomial Basis Operations}
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$.
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.
1284 int mp_lshd (mp_int * a, int b);
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.
1292 void mp_rshd (mp_int * a, int b)
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.
1297 \subsection{AND, OR, XOR and COMPLEMENT Operations}
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.
1302 \index{mp\_or} \index{mp\_and} \index{mp\_xor} \index{mp\_complement}
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);
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}.
1314 \subsection{Bit Picking}
1315 \index{mp\_get\_bit}
1317 int mp_get_bit(mp_int *a, int b)
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$.
1323 \section{Addition and Subtraction}
1325 To compute an addition or subtraction the following two functions can be used.
1327 \index{mp\_add} \index{mp\_sub}
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)
1333 Which perform $c = a \odot b$ where $\odot$ is one of signed addition or subtraction. The operations are fully sign
1336 \section{Sign Manipulation}
1337 \subsection{Negation}
1339 Simple integer negation can be performed with the following.
1343 int mp_neg (mp_int * a, mp_int * b);
1346 Which assigns $-a$ to $b$.
1348 \subsection{Absolute}
1349 Simple integer absolutes can be performed with the following.
1353 int mp_abs (mp_int * a, mp_int * b);
1356 Which assigns $\vert a \vert$ to $b$.
1358 \section{Integer Division and Remainder}
1359 To perform a complete and general integer division with remainder use the following function.
1363 int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d);
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}.
1371 \chapter{Multiplication and Squaring}
1372 \section{Multiplication}
1373 A full signed integer multiplication can be performed with the following.
1376 int mp_mul (mp_int * a, mp_int * b, mp_int * c);
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.
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.
1389 mp_int number1, number2;
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;
1401 mp_set_i32(&number, 257);
1402 mp_set_i32(&number2, 1023);
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;
1413 printf("number1 * number2 == \%" PRIi32, mp_get_i32(&number1));
1415 /* free terms and return */
1416 mp_clear_multi(&number1, &number2, NULL);
1418 return EXIT_SUCCESS;
1422 If this program succeeds it shall output the following.
1425 number1 * number2 == 262911
1429 Since squaring can be performed faster than multiplication it is performed it's own function instead of just using
1434 int mp_sqr (mp_int * a, mp_int * b);
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.
1441 \section{Tuning Polynomial Basis Routines}
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
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.
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.
1457 To get reasonable values for the cut-off points for your architecture, type
1463 This will run a benchmark, computes the medians, rewrites \texttt{bncore.c}, and recompiles \texttt{bncore.c} and relinks the library.
1465 The benchmark itself can be fine-tuned in the file \texttt{etc/tune\_it.sh}.
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.
1469 \chapter{Modular Reduction}
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$.
1475 a \equiv b \mbox{ (mod }c\mbox{)}
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.
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.
1485 \section{Straight Division}
1486 In order to effect an arbitrary modular reduction the following algorithm is provided.
1490 int mp_mod(mp_int *a, mp_int *b, mp_int *c);
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$.
1496 \section{Barrett Reduction}
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.
1501 \index{mp\_reduce\_setup}
1503 int mp_reduce_setup(mp_int *a, mp_int *b);
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.
1511 int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
1514 This will reduce $a$ in place modulo $b$ with the precomputed $\mu$ value in $c$. $a$ must be in the range
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
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;
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;
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;
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;
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;
1562 /* c now equals a^3 mod b */
1564 return EXIT_SUCCESS;
1568 This program will calculate $a^3 \mbox{ mod }b$ if all the functions succeed.
1570 \section{Montgomery Reduction}
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.
1575 \index{mp\_montgomery\_setup}
1577 int mp_montgomery_setup(mp_int *a, mp_digit *mp);
1580 For the given odd moduli $a$ the precomputation value is placed in $mp$. The reduction is computed with the
1583 \index{mp\_montgomery\_reduce}
1585 int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
1587 This reduces $a$ in place modulo $m$ with the pre--computed value $mp$. $a$ must be in the range
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.
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}$).
1597 To quickly calculate $R$ the following function was provided.
1599 \index{mp\_montgomery\_calc\_normalization}
1601 int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
1603 Which calculates $a = R$ for the odd moduli $b$ without using multiplication or division.
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.
1616 /* initialize a,b to desired values,
1617 * mp_init R, c and set c to 1....
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;
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;
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;
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;
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;
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;
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;
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;
1676 /* c now equals a^3 mod b */
1678 return EXIT_SUCCESS;
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.
1686 For more details consider examining the file \textit{bn\_mp\_exptmod\_fast.c}.
1688 \section{Restricted Diminished Radix}
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}$).
1694 As in the case of Montgomery reduction there is a pre--computation phase required for a given modulus.
1696 \index{mp\_dr\_setup}
1698 void mp_dr_setup(mp_int *a, mp_digit *d);
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
1705 \index{mp\_dr\_reduce}
1707 int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
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.
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.
1718 Note that unlike Montgomery reduction there is no normalization process. The result of this function is
1719 equal to the correct residue.
1721 \section{Unrestricted Diminished Radix}
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.
1727 \index{mp\_reduce\_2k\_setup}
1729 int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
1732 This will compute the required $d$ value for the given moduli $a$.
1734 \index{mp\_reduce\_2k}
1736 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
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.
1742 \section{Combined Modular Reduction}
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:
1746 Addition $d = (a + b) \mod c$
1749 int mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1752 Subtraction $d = (a - b) \mod c$
1754 int mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1757 Multiplication $d = (ab) \mod c$
1759 int mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1762 Squaring $d = (a^2) \mod c$
1764 int mp_sqrmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);
1769 \chapter{Exponentiation}
1770 \section{Single Digit Exponentiation}
1773 int mp_expt_d (mp_int * a, mp_digit b, mp_int * c)
1775 This function computes $c = a^b$.
1777 \section{Modular Exponentiation}
1780 int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
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
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.
1792 \section{Modulus a Power of Two}
1795 int mp_mod_2d(const mp_int *a, int b, mp_int *c)
1797 It calculates $c = a \mod 2^b$.
1799 \section{Root Finding}
1802 int mp_n_root (mp_int * a, mp_digit b, mp_int * c)
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}$
1808 This algorithm uses the ``Newton Approximation'' method and will converge on the correct root fairly quickly.
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.
1814 int mp_sqrt (mp_int * a, mp_digit b, mp_int * c)
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$.
1823 int mp_ilogb(mp_int *a, mp_digit base, mp_int *c)
1825 \subsection{Example}
1831 #include <tommath.h>
1833 int main(int argc, char **argv)
1840 fprintf(stderr,"Usage %s base x\textbackslash{}n", argv[0]);
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));
1850 base = (mp_digit)strtoull(argv[1], NULL, 10);
1852 base = (mp_digit)strtoul(argv[1], NULL, 10);
1854 if ((errno == ERANGE) || (base > (base & MP_MASK))) {
1855 fprintf(stderr,"strtoul(l) failed: input out of range\textbackslash{}n");
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));
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));
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));
1874 putchar('\textbackslash{}n');
1876 mp_clear_multi(&x, &output, NULL);
1883 \chapter{Prime Numbers}
1884 \section{Trial Division}
1885 \index{mp\_prime\_is\_divisible}
1887 int mp_prime_is_divisible (mp_int * a, int *result)
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.}.
1894 \section{Fermat Test}
1895 \index{mp\_prime\_fermat}
1897 int mp_prime_fermat (mp_int * a, mp_int * b, int *result)
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$
1903 \section{Miller-Rabin Test}
1904 \index{mp\_prime\_miller\_rabin}
1906 int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
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.
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.
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.
1920 \index{mp\_prime\_rabin\_miller\_trials}
1922 int mp_prime_rabin_miller_trials(int size)
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}.
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}$
1951 \caption{ Number of Miller-Rabin rounds as implemented } \label{table:millerrabinrunsimpl}
1955 You should always still perform a trial division before a Miller-Rabin test though.
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}$.
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
1986 \caption{ Number of Miller-Rabin rounds. Part I } \label{table:millerrabinrunsp1}
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
2015 \caption{ Number of Miller-Rabin rounds. Part II } \label{table:millerrabinrunsp2}
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.
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.
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$.
2025 This function can be used to test a DSA prime directly if these rounds are followed by a Lucas test.
2027 See also table C.1 in FIPS 186-4.
2029 \section{Strong Lucas-Selfridge Test}
2030 \index{mp\_prime\_strong\_lucas\_selfridge}
2032 int mp_prime_strong_lucas_selfridge(const mp_int *a, int *result)
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.
2037 \section{Frobenius (Underwood) Test}
2038 \index{mp\_prime\_frobenius\_underwood}
2040 int mp_prime_frobenius_underwood(const mp_int *N, int *result)
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.
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$.
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}
2052 int mp_is_square(const mp_int *arg, int *ret);
2056 \index{mp\_prime\_is\_prime}
2058 int mp_prime_is_prime (mp_int * a, int t, int *result)
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.
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.
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.
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.
2070 If $a$ passes all of the tests $result$ is set to one, otherwise it is set to zero.
2072 \section{Next Prime}
2073 \index{mp\_prime\_next\_prime}
2075 int mp_prime_next_prime(mp_int *a, int t, int bbs_style)
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.
2081 \section{Random Primes}
2082 \index{mp\_prime\_rand}
2084 int mp_prime_rand(mp_int *a, int t,
2085 int size, int flags);
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.
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.
2096 \textit{Note:} This function replaces the deprecated mp\_prime\_random and mp\_prime\_random\_ex functions.
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. \\
2114 \caption{Primality Generation Options}
2115 \label{fig:primeopts}
2118 \chapter{Random Number Generation}
2120 \index{mp\_rand\_digit}
2122 int mp_rand_digit(mp_digit *r)
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.
2128 int mp_rand(mp_int *a, int digits)
2130 This function generates a random number of \texttt{digits} bits.
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.
2135 \chapter{Input and Output}
2136 \section{ASCII Conversions}
2137 \subsection{To ASCII}
2138 \index{mp\_to\_radix}
2140 int mp_to_radix (mp_int *a, char *str, size_t maxlen, size_t *written, int radix);
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.
2144 Valid values of \texttt{radix} line in the range $[2, 64]$.
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}.
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.
2151 Please be aware that this function cannot evaluate the actual size of the buffer, it relies on the correctness of \texttt{maxlen}!
2154 \index{mp\_radix\_size}
2156 int mp_radix_size (mp_int * a, int radix, int *size)
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.
2161 If \texttt{LTM\_NO\_FILE} is not defined a function to write to a file is also available.
2164 int mp_fwrite(const mp_int *a, int radix, FILE *stream);
2168 \subsection{From ASCII}
2169 \index{mp\_read\_radix}
2171 int mp_read_radix (mp_int * a, char *str, int radix);
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.
2177 If \texttt{LTM\_NO\_FILE} is not defined a function to read from a file is also available.
2180 int mp_fread(mp_int *a, int radix, FILE *stream);
2184 \section{Binary Conversions}
2186 Converting an mp\_int to and from binary is another keen idea.
2188 \index{mp\_ubin\_size}
2190 size_t mp_ubin_size(mp_int *a);
2193 This will return the number of bytes (octets) required to store the unsigned copy of the integer $a$.
2195 \index{mp\_to\_ubin}
2197 int mp_to_unsigned_bin(mp_int *a, unsigned char *b, size_t maxlen, size_t *len);
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.
2201 \index{mp\_from\_ubin}
2203 int mp_from_ubin(mp_int *a, unsigned char *b, size_t size);
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.
2207 For those who acknowledge the existence of negative numbers (heretic!) there are ``signed'' versions of the
2209 \index{mp\_signed\_bin\_size} \index{mp\_to\_signed\_bin} \index{mp\_read\_signed\_bin}
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);
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
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}
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);
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
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);
2232 To get the size in bytes necessary to be put in \texttt{maxsize}).
2234 To enhance the readability of your code, the following enums have been wrought for your convenience.
2241 MP_LITTLE_ENDIAN = -1,
2242 MP_NATIVE_ENDIAN = 0,
2247 \chapter{Algebraic Functions}
2248 \section{Extended Euclidean Algorithm}
2249 \index{mp\_exteuclid}
2251 int mp_exteuclid(mp_int *a, mp_int *b,
2252 mp_int *U1, mp_int *U2, mp_int *U3);
2255 This finds the triple U1/U2/U3 using the Extended Euclidean algorithm such that the following equation holds.
2258 a \cdot U1 + b \cdot U2 = U3
2261 Any of the U1/U2/U3 parameters can be set to \textbf{NULL} if they are not desired.
2263 \section{Greatest Common Divisor}
2266 int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
2268 This will compute the greatest common divisor of $a$ and $b$ and store it in $c$.
2270 \section{Least Common Multiple}
2273 int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
2275 This will compute the least common multiple of $a$ and $b$ and store it in $c$.
2277 \section{Jacobi Symbol}
2280 int mp_jacobi (mp_int * a, mp_int * p, int *c)
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$.
2287 \section{Kronecker Symbol}
2288 \index{mp\_kronecker}
2290 int mp_kronecker (mp_int * a, mp_int * p, int *c)
2292 Extension of the Jacoby symbol to all $\lbrace a, p \rbrace \in \mathbb{Z}$ .
2295 \section{Modular square root}
2296 \index{mp\_sqrtmod\_prime}
2298 int mp_sqrtmod_prime(mp_int *n, mp_int *p, mp_int *r)
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.
2305 The implementation is split for two different cases:
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$
2310 2. otherwise we use \href{https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm}{Tonelli-Shanks algorithm}
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
2316 \section{Modular Inverse}
2319 int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
2321 Computes the multiplicative inverse of $a$ modulo $b$ and stores the result in $c$ such that $ac \equiv 1 \mbox{ (mod }b\mbox{)}$.
2323 \section{Single Digit Functions}
2325 For those using small numbers (\textit{snicker snicker}) there are several ``helper'' functions
2327 \index{mp\_add\_d} \index{mp\_sub\_d} \index{mp\_mul\_d} \index{mp\_div\_d} \index{mp\_mod\_d}
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);
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$.
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!
2342 int mp_incr(mp_int *a);
2343 int mp_decr(mp_int *a);
2347 The division by three can be made faster by replacing the division with a multiplication by the multiplicative inverse of three.
2351 int mp_div_3(const mp_int *a, mp_int *c, mp_digit *d);
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.
2361 int mp_iseven(mp_int *a)
2363 Checks if $a = 0 mod 2$
2367 int mp_isodd(mp_int *a)
2369 Checks if $a = 1 mod 2$
2373 int mp_isneg(mp_int *a)
2380 int mp_iszero(mp_int *a)
2382 Checks if $a = 0$. It does not check if the amount of memory allocated for $a$ is also minimal.
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!
2387 \subsection{Renamings}
2388 \index{mp\_mag\_size}
2390 #define mp_mag_size(mp) mp_unsigned_bin_size(mp)
2394 \index{mp\_raw\_size}
2396 #define mp_raw_size(mp) mp_signed_bin_size(mp)
2400 \index{mp\_read\_mag}
2402 #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
2406 \index{mp\_read\_raw}
2408 #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
2414 #define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
2420 #define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))
2425 \subsection{Shortcuts}
2427 \index{mp\_to\_binary}
2429 #define mp_to_binary(M, S, N) mp_to_radix((M), (S), (N), 2)
2433 \index{mp\_to\_octal}
2435 #define mp_to_octal(M, S, N) mp_to_radix((M), (S), (N), 8)
2439 \index{mp\_to\_decimal}
2441 #define mp_to_decimal(M, S, N) mp_to_radix((M), (S), (N), 10)
2447 #define mp_to_hex(M, S, N) mp_to_radix((M), (S), (N), 16)
2452 %\noappendicestocpagenum
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.
2457 log2(x) = log(x)/log(2)
2459 fips_f1_sums(k, M, t) = {
2464 1/ ( 2^( j + (k-1)/j ) )
2470 fips_f1_2(k, t, M) = {
2471 local(common_factor, t1, t2, f1, f2, ds, res);
2473 common_factor = 2.00743 * log(2) * k * 2^(-k);
2474 t1 = 2^(k - 2 - M*t);
2475 f1 = (8 * ((Pi^2) - 6))/3;
2477 ds = t1 + f1 * f2 * fips_f1_sums(k, M, t);
2478 res = common_factor * ds;
2482 fips_f1_1(prime_length, ptarget)={
2483 local(t, t_end, M, M_end, pkt);
2485 t_end = ceil(-log2(ptarget)/2);
2486 M_end = floor(2 * sqrt(prime_length-1) - 1);
2490 pkt = fips_f1_2(prime_length, t, M);
2499 To get the number of rounds for a $1024$ bit large prime with a probability of $2^{-160}$:
2501 ? fips_f1_1(1024,2^(-160))