2006-12-24 11:12:36 -05:00
\documentclass [synpaper] { book}
2003-12-24 13:59:22 -05:00
\usepackage { hyperref}
\usepackage { makeidx}
\usepackage { amssymb}
\usepackage { color}
\usepackage { alltt}
\usepackage { graphicx}
\usepackage { layout}
\def \union { \cup }
\def \intersect { \cap }
\def \getsrandom { \stackrel { \rm R} { \gets } }
\def \cross { \times }
\def \cat { \hspace { 0.5em} \| \hspace { 0.5em} }
\def \catn { $ \| $ }
\def \divides { \hspace { 0.3em} | \hspace { 0.3em} }
\def \nequiv { \not \equiv }
\def \approx { \raisebox { 0.2ex} { \mbox { \small $ \sim $ } } }
\def \lcm { { \rm lcm} }
\def \gcd { { \rm gcd} }
\def \log { { \rm log} }
\def \ord { { \rm ord} }
\def \abs { { \mathit abs} }
\def \rep { { \mathit rep} }
\def \mod { { \mathit \ mod\ } }
\renewcommand { \pmod } [1]{ \ ({ \rm mod\ } { #1} )}
\newcommand { \floor } [1]{ \left \lfloor { #1} \right \rfloor }
\newcommand { \ceil } [1]{ \left \lceil { #1} \right \rceil }
\def \Or { { \rm \ or\ } }
\def \And { { \rm \ and\ } }
\def \iff { \hspace { 1em} \Longleftrightarrow \hspace { 1em} }
\def \implies { \Rightarrow }
\def \undefined { { \rm ``undefined"} }
\def \Proof { \vspace { 1ex} \noindent { \bf Proof:} \hspace { 1em} }
\let \oldphi \phi
\def \phi { \varphi }
\def \Pr { { \rm Pr} }
\newcommand { \str } [1]{ { \mathbf { #1} } }
\def \F { { \mathbb F} }
\def \N { { \mathbb N} }
\def \Z { { \mathbb Z} }
\def \R { { \mathbb R} }
\def \C { { \mathbb C} }
\def \Q { { \mathbb Q} }
\definecolor { DGray} { gray} { 0.5}
\newcommand { \emailaddr } [1]{ \mbox { $ < $ { #1} $ > $ } }
\def \twiddle { \raisebox { 0.3ex} { \mbox { \tiny $ \sim $ } } }
\def \gap { \vspace { 0.5ex} }
\makeindex
2003-02-28 11:07:58 -05:00
\begin { document}
2003-12-24 13:59:22 -05:00
\frontmatter
\pagestyle { empty}
2017-08-28 11:02:30 -04:00
\title { LibTomMath User Manual \\ v1.0.1}
2018-02-02 06:07:21 -05:00
\author { LibTom Projects \\ www.libtom.net}
2003-02-28 11:07:58 -05:00
\maketitle
2014-10-12 12:48:26 -04:00
This text, the library and the accompanying textbook are all hereby placed in the public domain. This book has been
2003-12-24 13:59:22 -05:00
formatted for B5 [176x250] paper using the \LaTeX { } { \em book} macro package.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\vspace { 10cm}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { flushright} Open Source. Open Academia. Open Minds.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\mbox { }
2018-02-02 06:07:21 -05:00
LibTom Projects
\& originally
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Tom St Denis,
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Ontario, Canada
\end { flushright}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\tableofcontents
\listoffigures
\mainmatter
\pagestyle { headings}
\chapter { Introduction}
\section { What is LibTomMath?}
LibTomMath is a library of source code which provides a series of efficient and carefully written functions for manipulating
large integer numbers. It was written in portable ISO C source code so that it will build on any platform with a conforming
2014-10-12 12:48:26 -04:00
C compiler.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
In a nutshell the library was written from scratch with verbose comments to help instruct computer science students how
2014-10-12 12:48:26 -04:00
to implement ``bignum'' math. However, the resulting code has proven to be very useful. It has been used by numerous
2003-12-24 13:59:22 -05:00
universities, commercial and open source software developers. It has been used on a variety of platforms ranging from
2014-10-12 12:48:26 -04:00
Linux and Windows based x86 to ARM based Gameboys and PPC based MacOS machines.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { License}
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
release the textbook ``Implementing Multiple Precision Arithmetic'' has been placed in the public domain with every new
release as well. This textbook is meant to compliment the project by providing a more solid walkthrough of the development
algorithms used in the library.
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
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
2003-12-24 13:59:22 -05:00
public domain everyone is entitled to do with them as they see fit.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Building LibTomMath}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
LibTomMath is meant to be very ``GCC friendly'' as it comes with a makefile well suited for GCC. However, the library will
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
2014-10-12 12:48:26 -04:00
developer.
2003-02-28 11:07:58 -05:00
2004-10-29 18:07:18 -04:00
\subsection { Static Libraries}
To build as a static library for GCC issue the following
2003-12-24 13:59:22 -05:00
\begin { alltt}
make
\end { alltt}
2003-02-28 11:08:34 -05:00
2014-10-12 12:48:26 -04:00
command. This will build the library and archive the object files in ``libtommath.a''. Now you link against
2004-10-29 18:07:18 -04:00
that and include ``tommath.h'' within your programs. Alternatively to build with MSVC issue the following
2003-12-24 13:59:22 -05:00
\begin { alltt}
nmake -f makefile.msvc
\end { alltt}
2003-02-28 11:08:34 -05:00
2014-10-12 12:48:26 -04:00
This will build the library and archive the object files in ``tommath.lib''. This has been tested with MSVC
version 6.00 with service pack 5.
2004-10-29 18:07:18 -04:00
\subsection { Shared Libraries}
To build as a shared library for GCC issue the following
\begin { alltt}
make -f makefile.shared
\end { alltt}
This requires the ``libtool'' package (common on most Linux/BSD systems). It will build LibTomMath as both shared
2014-10-12 12:48:26 -04:00
and static then install (by default) into /usr/lib as well as install the header files in /usr/include. The shared
library (resource) will be called ``libtommath.la'' while the static library called ``libtommath.a''. Generally
you use libtool to link your application against the shared object.
2003-02-28 11:08:34 -05:00
2014-10-12 12:48:26 -04:00
There is limited support for making a ``DLL'' in windows via the ``makefile.cygwin\_ dll'' makefile. It requires
Cygwin to work with since it requires the auto-export/import functionality. The resulting DLL and import library
2004-10-29 18:07:18 -04:00
``libtommath.dll.a'' can be used to link LibTomMath dynamically to any Windows program using Cygwin.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Testing}
To build the library and the test harness type
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
make test
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
This will build the library, ``test'' and ``mtest/mtest''. The ``test'' program will accept test vectors and verify the
results. ``mtest/mtest'' will generate test vectors using the MPI library by Michael Fromberger\footnote { A copy of MPI
is included in the package} . Simply pipe mtest into test using
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
mtest/mtest | test
\end { alltt}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
If you do not have a ``/dev/urandom'' style RNG source you will have to write your own PRNG and simply pipe that into
2003-12-24 13:59:22 -05:00
mtest. For example, if your PRNG program is called ``myprng'' simply invoke
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
myprng | mtest/mtest | test
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
This will output a row of numbers that are increasing. Each column is a different test (such as addition, multiplication, etc)
that is being performed. The numbers represent how many times the test was invoked. If an error is detected the program
2018-05-03 17:45:02 -04:00
will exit with a dump of the relevant numbers it was working with.
2003-02-28 11:07:58 -05:00
2004-10-29 18:07:18 -04:00
\section { Build Configuration}
2014-10-12 12:48:26 -04:00
LibTomMath can configured at build time in three phases we shall call ``depends'', ``tweaks'' and ``trims''.
Each phase changes how the library is built and they are applied one after another respectively.
2004-10-29 18:07:18 -04:00
To make the system more powerful you can tweak the build process. Classes are defined in the file
2014-10-12 12:48:26 -04:00
``tommath\_ superclass.h''. By default, the symbol ``LTM\_ ALL'' shall be defined which simply
instructs the system to build all of the functions. This is how LibTomMath used to be packaged. This will give you
2004-10-29 18:07:18 -04:00
access to every function LibTomMath offers.
2014-10-12 12:48:26 -04:00
However, there are cases where such a build is not optional. For instance, you want to perform RSA operations. You
don't need the vast majority of the library to perform these operations. Aside from LTM\_ ALL there is
another pre--defined class ``SC\_ RSA\_ 1'' which works in conjunction with the RSA from LibTomCrypt. Additional
2004-10-29 18:07:18 -04:00
classes can be defined base on the need of the user.
\subsection { Build Depends}
In the file tommath\_ class.h you will see a large list of C ``defines'' followed by a series of ``ifdefs''
which further define symbols. All of the symbols (technically they're macros $ \ldots $ ) represent a given C source
file. For instance, BN\_ MP\_ ADD\_ C represents the file ``bn\_ mp\_ add.c''. When a define has been enabled the
function in the respective file will be compiled and linked into the library. Accordingly when the define
is absent the file will not be compiled and not contribute any size to the library.
2014-10-12 12:48:26 -04:00
You will also note that the header tommath\_ class.h is actually recursively included (it includes itself twice).
This is to help resolve as many dependencies as possible. In the last pass the symbol LTM\_ LAST will be defined.
2004-10-29 18:07:18 -04:00
This is useful for ``trims''.
\subsection { Build Tweaks}
A tweak is an algorithm ``alternative''. For example, to provide tradeoffs (usually between size and space).
They can be enabled at any pass of the configuration phase.
\begin { small}
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { Define} & \textbf { Purpose} \\
\hline BN\_ MP\_ DIV\_ SMALL & Enables a slower, smaller and equally \\
& functional mp\_ div() function \\
\hline
\end { tabular}
\end { center}
\end { small}
\subsection { Build Trims}
A trim is a manner of removing functionality from a function that is not required. For instance, to perform
2014-10-12 12:48:26 -04:00
RSA cryptography you only require exponentiation with odd moduli so even moduli support can be safely removed.
2004-10-29 18:07:18 -04:00
Build trims are meant to be defined on the last pass of the configuration which means they are to be defined
only if LTM\_ LAST has been defined.
\subsubsection { Moduli Related}
\begin { small}
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { Restriction} & \textbf { Undefine} \\
\hline Exponentiation with odd moduli only & BN\_ S\_ MP\_ EXPTMOD\_ C \\
& BN\_ MP\_ REDUCE\_ C \\
& BN\_ MP\_ REDUCE\_ SETUP\_ C \\
& BN\_ S\_ MP\_ MUL\_ HIGH\_ DIGS\_ C \\
& BN\_ FAST\_ S\_ MP\_ MUL\_ HIGH\_ DIGS\_ C \\
\hline Exponentiation with random odd moduli & (The above plus the following) \\
& BN\_ MP\_ REDUCE\_ 2K\_ C \\
& BN\_ MP\_ REDUCE\_ 2K\_ SETUP\_ C \\
& BN\_ MP\_ REDUCE\_ IS\_ 2K\_ C \\
& BN\_ MP\_ DR\_ IS\_ MODULUS\_ C \\
& BN\_ MP\_ DR\_ REDUCE\_ C \\
& BN\_ MP\_ DR\_ SETUP\_ C \\
\hline Modular inverse odd moduli only & BN\_ MP\_ INVMOD\_ SLOW\_ C \\
\hline Modular inverse (both, smaller/slower) & BN\_ FAST\_ MP\_ INVMOD\_ C \\
\hline
\end { tabular}
\end { center}
\end { small}
\subsubsection { Operand Size Related}
\begin { small}
\begin { center}
\begin { tabular} { |l|l|}
\hline \textbf { Restriction} & \textbf { Undefine} \\
\hline Moduli $ \le 2560 $ bits & BN\_ MP\_ MONTGOMERY\_ REDUCE\_ C \\
& BN\_ S\_ MP\_ MUL\_ DIGS\_ C \\
& BN\_ S\_ MP\_ MUL\_ HIGH\_ DIGS\_ C \\
& BN\_ S\_ MP\_ SQR\_ C \\
\hline Polynomial Schmolynomial & BN\_ MP\_ KARATSUBA\_ MUL\_ C \\
& BN\_ MP\_ KARATSUBA\_ SQR\_ C \\
2014-10-12 12:48:26 -04:00
& BN\_ MP\_ TOOM\_ MUL\_ C \\
2004-10-29 18:07:18 -04:00
& BN\_ MP\_ TOOM\_ SQR\_ C \\
\hline
\end { tabular}
\end { center}
\end { small}
2003-12-24 13:59:22 -05:00
\section { Purpose of LibTomMath}
2014-10-12 12:48:26 -04:00
Unlike GNU MP (GMP) Library, LIP, OpenSSL or various other commercial kits (Miracl), LibTomMath was not written with
bleeding edge performance in mind. First and foremost LibTomMath was written to be entirely open. Not only is the
2003-12-24 13:59:22 -05:00
source code public domain (unlike various other GPL/etc licensed code), not only is the code freely downloadable but the
source code is also accessible for computer science students attempting to learn ``BigNum'' or multiple precision
2014-10-12 12:48:26 -04:00
arithmetic techniques.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
LibTomMath was written to be an instructive collection of source code. This is why there are many comments, only one
function per source file and often I use a ``middle-road'' approach where I don't cut corners for an extra 2\% speed
increase.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Source code alone cannot really teach how the algorithms work which is why I also wrote a textbook that accompanies
the library (beat that!).
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
So you may be thinking ``should I use LibTomMath?'' and the answer is a definite maybe. Let me tabulate what I think
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} .
2003-02-28 11:07:58 -05:00
2017-08-25 07:00:05 -04:00
\newpage \begin { figure} [h]
2003-12-24 13:59:22 -05:00
\begin { small}
\begin { center}
\begin { tabular} { |l|c|c|l|}
\hline \textbf { Criteria} & \textbf { Pro} & \textbf { Con} & \textbf { Notes} \\
2005-02-12 03:40:15 -05:00
\hline Few lines of code per file & X & & GnuPG $ = 300 . 9 $ , LibTomMath $ = 71 . 97 $ \\
2003-12-24 13:59:22 -05:00
\hline Commented function prototypes & X & & GnuPG function names are cryptic. \\
\hline Speed & & X & LibTomMath is slower. \\
\hline Totally free & X & & GPL has unfavourable restrictions.\\
\hline Large function base & X & & GnuPG is barebones. \\
2005-02-12 03:40:15 -05:00
\hline Five modular reduction algorithms & X & & Faster modular exponentiation for a variety of moduli. \\
2003-12-24 13:59:22 -05:00
\hline Portable & X & & GnuPG requires configuration to build. \\
\hline
\end { tabular}
\end { center}
\end { small}
\caption { LibTomMath Valuation}
\end { figure}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
It may seem odd to compare LibTomMath to GnuPG since the math in GnuPG is only a small portion of the entire application.
2003-12-24 13:59:22 -05:00
However, LibTomMath was written with cryptography in mind. It provides essentially all of the functions a cryptosystem
2014-10-12 12:48:26 -04:00
would require when working with large integers.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
So it may feel tempting to just rip the math code out of GnuPG (or GnuMP where it was taken from originally) in your
own application but I think there are reasons not to. While LibTomMath is slower than libraries such as GnuMP it is
not normally significantly slower. On x86 machines the difference is normally a factor of two when performing modular
2005-02-12 03:40:15 -05:00
exponentiations. It depends largely on the processor, compiler and the moduli being used.
2003-02-28 11:07:58 -05:00
2005-02-12 03:40:15 -05:00
Essentially the only time you wouldn't use LibTomMath is when blazing speed is the primary concern. However,
on the other side of the coin LibTomMath offers you a totally free (public domain) well structured math library
2018-05-03 17:45:02 -04:00
that is very flexible, complete and performs well in resource constrained environments. Fast RSA for example can
2014-10-12 12:48:26 -04:00
be performed with as little as 8KB of ram for data (again depending on build options).
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\chapter { Getting Started with LibTomMath}
\section { Building Programs}
2014-10-12 12:48:26 -04:00
In order to use LibTomMath you must include ``tommath.h'' and link against the appropriate library file (typically
2003-12-24 13:59:22 -05:00
libtommath.a). There is no library initialization required and the entire library is thread safe.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Return Codes}
There are three possible return codes a function may return.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { MP\_ OKAY} \index { MP\_ YES} \index { MP\_ NO} \index { MP\_ VAL} \index { MP\_ MEM}
2017-08-25 07:00:05 -04:00
\begin { figure} [h!]
2003-12-24 13:59:22 -05:00
\begin { center}
\begin { small}
\begin { tabular} { |l|l|}
\hline \textbf { Code} & \textbf { Meaning} \\
\hline MP\_ OKAY & The function succeeded. \\
\hline MP\_ VAL & The function input was invalid. \\
\hline MP\_ MEM & Heap memory exhausted. \\
\hline & \\
\hline MP\_ YES & Response is yes. \\
\hline MP\_ NO & Response is no. \\
\hline
\end { tabular}
\end { small}
\end { center}
\caption { Return Codes}
\end { figure}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
The last two codes listed are not actually ``return'ed'' by a function. They are placed in an integer (the caller must
provide the address of an integer it can store to) which the caller can access. To convert one of the three return codes
to a string use the following function.
2003-03-29 13:16:01 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ error\_ to\_ string}
\begin { alltt}
char *mp_ error_ to_ string(int code);
\end { alltt}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
This will return a pointer to a string which describes the given error code. It will not work for the return codes
MP\_ YES and MP\_ NO.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Data Types}
The basic ``multiple precision integer'' type is known as the ``mp\_ int'' within LibTomMath. This data type is used to
organize all of the data required to manipulate the integer it represents. Within LibTomMath it has been prototyped
as the following.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ int}
\begin { alltt}
typedef struct \{
int used, alloc, sign;
mp_ digit *dp;
\} mp_ int;
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Where ``mp\_ digit'' is a data type that represents individual digits of the integer. By default, an mp\_ digit is the
ISO C ``unsigned long'' data type and each digit is $ 28 - $ bits long. The mp\_ digit type can be configured to suit other
2014-10-12 12:48:26 -04:00
platforms by defining the appropriate macros.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
All LTM functions that use the mp\_ int type will expect a pointer to mp\_ int structure. You must allocate memory to
hold the structure itself by yourself (whether off stack or heap it doesn't matter). The very first thing that must be
done to use an mp\_ int is that it must be initialized.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Function Organization}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
The arithmetic functions of the library are all organized to have the same style prototype. That is source operands
are passed on the left and the destination is on the right. For instance,
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
mp_ add(& a, & b, & c); /* c = a + b */
mp_ mul(& a, & a, & c); /* c = a * a */
mp_ div(& a, & b, & c, & d); /* c = [a/b], d = a mod b */
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Another feature of the way the functions have been implemented is that source operands can be destination operands as well.
For instance,
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
mp_ add(& a, & b, & b); /* b = a + b */
mp_ div(& a, & b, & a, & c); /* a = [a/b], c = a mod b */
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
This allows operands to be re-used which can make programming simpler.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Initialization}
\subsection { Single Initialization}
2014-10-12 12:48:26 -04:00
A single mp\_ int can be initialized with the ``mp\_ init'' function.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ init}
\begin { alltt}
int mp_ init (mp_ int * a);
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
This function expects a pointer to an mp\_ int structure and will initialize the members of the structure so the mp\_ int
represents the default integer which is zero. If the functions returns MP\_ OKAY then the mp\_ int is ready to be used
by the other LibTomMath functions.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the number */
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
\subsection { Single Free}
2014-10-12 12:48:26 -04:00
When you are finished with an mp\_ int it is ideal to return the heap it used back to the system. The following function
2003-12-24 13:59:22 -05:00
provides this functionality.
\index { mp\_ clear}
\begin { alltt}
void mp_ clear (mp_ int * a);
\end { alltt}
2014-10-12 12:48:26 -04:00
The function expects a pointer to a previously initialized mp\_ int structure and frees the heap it uses. It sets the
pointer\footnote { The ``dp'' member.} within the mp\_ int to \textbf { NULL} which is used to prevent double free situations.
Is is legal to call mp\_ clear() twice on the same mp\_ int in a row.
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the number */
/* We're done with it. */
mp_ clear(& number);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
\subsection { Multiple Initializations}
Certain algorithms require more than one large integer. In these instances it is ideal to initialize all of the mp\_ int
variables in an ``all or nothing'' fashion. That is, they are either all initialized successfully or they are all
not initialized.
The mp\_ init\_ multi() function provides this functionality.
\index { mp\_ init\_ multi} \index { mp\_ clear\_ multi}
\begin { alltt}
int mp_ init_ multi(mp_ int *mp, ...);
\end { alltt}
It accepts a \textbf { NULL} terminated list of pointers to mp\_ int structures. It will attempt to initialize them all
at once. If the function returns MP\_ OKAY then all of the mp\_ int variables are ready to use, otherwise none of them
2014-10-12 12:48:26 -04:00
are available for use. A complementary mp\_ clear\_ multi() function allows multiple mp\_ int variables to be free'd
from the heap at the same time.
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int num1, num2, num3;
int result;
2014-10-12 12:48:26 -04:00
if ((result = mp_ init_ multi(& num1,
2003-12-24 13:59:22 -05:00
& num2,
2014-10-12 12:48:26 -04:00
& num3, NULL)) != MP\_ OKAY) \{
printf("Error initializing the numbers. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the numbers */
/* We're done with them. */
mp_ clear_ multi(& num1, & num2, & num3, NULL);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
\subsection { Other Initializers}
2014-10-12 12:48:26 -04:00
To initialized and make a copy of an mp\_ int the mp\_ init\_ copy() function has been provided.
2003-12-24 13:59:22 -05:00
\index { mp\_ init\_ copy}
\begin { alltt}
int mp_ init_ copy (mp_ int * a, mp_ int * b);
\end { alltt}
2004-04-11 16:46:22 -04:00
This function will initialize $ a $ and make it a copy of $ b $ if all goes well.
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int num1, num2;
int result;
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
/* initialize and do work on num1 ... */
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
/* We want a copy of num1 in num2 now */
if ((result = mp_ init_ copy(& num2, & num1)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the copy. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* now num2 is ready and contains a copy of num1 */
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
/* We're done with them. */
mp_ clear_ multi(& num1, & num2, NULL);
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
Another less common initializer is mp\_ init\_ size() which allows the user to initialize an mp\_ int with a given
default number of digits. By default, all initializers allocate \textbf { MP\_ PREC} digits. This function lets
you override this behaviour.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ init\_ size}
\begin { alltt}
int mp_ init_ size (mp_ int * a, int size);
\end { alltt}
2003-03-22 10:10:20 -05:00
2004-04-11 16:46:22 -04:00
The $ size $ parameter must be greater than zero. If the function succeeds the mp\_ int $ a $ will be initialized
2014-10-12 12:48:26 -04:00
to have $ size $ digits (which are all initially zero).
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
/* we need a 60-digit number */
if ((result = mp_ init_ size(& number, 60)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the number */
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
\section { Maintenance Functions}
2018-12-09 17:11:38 -05:00
\subsection { Clear Leading Zeros}
This is used to ensure that leading zero digits are trimed and the leading "used" digit will be non-zero.
It also fixes the sign if there are no more leading digits.
\index { mp\_ clamp}
\begin { alltt}
void mp_ clamp(mp_ int *a);
\end { alltt}
\subsection { Zero Out}
This function will set the ``bigint'' to zeros without changing the amount of allocated memory.
\index { mp\_ zero}
\begin { alltt}
void mp_ zero(mp_ int *a);
\end { alltt}
2003-12-24 13:59:22 -05:00
\subsection { Reducing Memory Usage}
When an mp\_ int is in a state where it won't be changed again\footnote { A Diffie-Hellman modulus for instance.} excess
digits can be removed to return memory to the heap with the mp\_ shrink() function.
\index { mp\_ shrink}
\begin { alltt}
int mp_ shrink (mp_ int * a);
\end { alltt}
2004-04-11 16:46:22 -04:00
This will remove excess digits of the mp\_ int $ a $ . If the operation fails the mp\_ int should be intact without the
2003-12-24 13:59:22 -05:00
excess digits being removed. Note that you can use a shrunk mp\_ int in further computations, however, such operations
will require heap operations which can be slow. It is not ideal to shrink mp\_ int variables that you will further
2014-10-12 12:48:26 -04:00
modify in the system (unless you are seriously low on memory).
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the number [e.g. pre-computation] */
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
/* We're done with it for now. */
if ((result = mp_ shrink(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error shrinking the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
/* use it .... */
2003-03-22 10:10:20 -05:00
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Adding additional digits}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Within the mp\_ int structure are two parameters which control the limitations of the array of digits that represent
the integer the mp\_ int is meant to equal. The \textit { used} parameter dictates how many digits are significant, that is,
contribute to the value of the mp\_ int. The \textit { alloc} parameter dictates how many digits are currently available in
the array. If you need to perform an operation that requires more digits you will have to mp\_ grow() the mp\_ int to
2014-10-12 12:48:26 -04:00
your desired size.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ grow}
\begin { alltt}
int mp_ grow (mp_ int * a, int size);
\end { alltt}
2003-02-28 11:07:58 -05:00
2004-04-11 16:46:22 -04:00
This will grow the array of digits of $ a $ to $ size $ . If the \textit { alloc} parameter is already bigger than
$ size $ the function will not do anything.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* use the number */
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
/* We need to add 20 digits to the number */
if ((result = mp_ grow(& number, number.alloc + 20)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error growing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
/* use the number */
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\chapter { Basic Operations}
2018-12-09 17:11:38 -05:00
\section { Copying}
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.
\index { mp\_ copy}
\begin { alltt}
int mp_ copy (mp_ int * a, mp_ int *b);
\end { alltt}
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.
\index { mp\_ exch}
\begin { alltt}
void mp_ exch (mp_ int * a, mp_ int *b);
\end { alltt}
\section { Bit Counting}
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 )
\index { mp\_ cnt\_ lsb}
\begin { alltt}
int mp_ cnt_ lsb(const mp_ int *a);
\end { alltt}
To get the position of the highest bit set (MSB, the Most Significant Bit; the number of bits in teh ``bignum'')
\index { mp\_ count\_ bits}
\begin { alltt}
int mp_ count_ bits(const mp_ int *a);
\end { alltt}
2003-12-24 13:59:22 -05:00
\section { Small Constants}
2018-05-03 17:45:02 -04:00
Setting mp\_ ints to small constants is a relatively common operation. To accommodate these instances there are two
2003-12-24 13:59:22 -05:00
small constant assignment functions. The first function is used to set a single digit constant while the second sets
an ISO C style ``unsigned long'' constant. The reason for both functions is efficiency. Setting a single digit is quick but the
2014-10-12 12:48:26 -04:00
domain of a digit can change (it's always at least $ 0 \ldots 127 $ ).
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Single Digit}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Setting a single digit can be accomplished with the following function.
2003-03-12 21:11:11 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ set}
\begin { alltt}
void mp_ set (mp_ int * a, mp_ digit b);
\end { alltt}
2003-03-12 21:11:11 -05:00
2004-04-11 16:46:22 -04:00
This will zero the contents of $ a $ and make it represent an integer equal to the value of $ b $ . Note that this
2003-12-24 13:59:22 -05:00
function has a return type of \textbf { void} . It cannot cause an error so it is safe to assume the function
succeeded.
2003-03-12 21:11:11 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
2003-03-12 21:11:11 -05:00
2003-12-24 13:59:22 -05:00
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number to 5 */
mp_ set(& number, 5);
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2003-02-28 11:08:34 -05:00
2004-04-11 16:46:22 -04:00
\subsection { Long Constants}
2003-02-28 11:08:34 -05:00
2014-10-12 12:48:26 -04:00
To set a constant that is the size of an ISO C ``unsigned long'' and larger than a single digit the following function
2004-04-11 16:46:22 -04:00
can be used.
2003-02-28 11:08:34 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ set\_ int}
\begin { alltt}
int mp_ set_ int (mp_ int * a, unsigned long b);
\end { alltt}
2003-02-28 11:08:34 -05:00
2004-04-11 16:46:22 -04:00
This will assign the value of the 32-bit variable $ b $ to the mp\_ int $ a $ . Unlike mp\_ set() this function will always
2014-10-12 12:48:26 -04:00
accept a 32-bit input regardless of the size of a single digit. However, since the value may span several digits
2003-12-24 13:59:22 -05:00
this function can fail if it runs out of heap memory.
2003-02-28 11:08:34 -05:00
2004-04-11 16:46:22 -04:00
To get the ``unsigned long'' copy of an mp\_ int the following function can be used.
\index { mp\_ get\_ int}
\begin { alltt}
unsigned long mp_ get_ int (mp_ int * a);
\end { alltt}
2014-10-12 12:48:26 -04:00
This will return the 32 least significant bits of the mp\_ int $ a $ .
2004-04-11 16:46:22 -04:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number to 654321 (note this is bigger than 127) */
if ((result = mp_ set_ int(& number, 654321)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting the value of the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2004-04-11 16:46:22 -04:00
printf("number == \% lu", mp_ get_ int(& number));
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2004-04-11 16:46:22 -04:00
This should output the following if the program succeeds.
\begin { alltt}
number == 654321
\end { alltt}
2014-12-10 13:08:42 -05:00
\subsection { Long Constants - platform dependant}
\index { mp\_ set\_ long}
\begin { alltt}
int mp_ set_ long (mp_ int * a, unsigned long b);
\end { alltt}
2018-05-03 17:45:02 -04:00
This will assign the value of the platform-dependent sized variable $ b $ to the mp\_ int $ a $ .
2014-12-10 13:08:42 -05:00
To get the ``unsigned long'' copy of an mp\_ int the following function can be used.
\index { mp\_ get\_ long}
\begin { alltt}
unsigned long mp_ get_ long (mp_ int * a);
\end { alltt}
This will return the least significant bits of the mp\_ int $ a $ that fit into an ``unsigned long''.
\subsection { Long Long Constants}
\index { mp\_ set\_ long\_ long}
\begin { alltt}
int mp_ set_ long_ long (mp_ int * a, unsigned long long b);
\end { alltt}
This will assign the value of the 64-bit variable $ b $ to the mp\_ int $ a $ .
To get the ``unsigned long long'' copy of an mp\_ int the following function can be used.
\index { mp\_ get\_ long\_ long}
\begin { alltt}
unsigned long long mp_ get_ long_ long (mp_ int * a);
\end { alltt}
This will return the 64 least significant bits of the mp\_ int $ a $ .
2004-04-11 16:46:22 -04:00
\subsection { Initialize and Setting Constants}
To both initialize and set small constants the following two functions are available.
\index { mp\_ init\_ set} \index { mp\_ init\_ set\_ int}
\begin { alltt}
int mp_ init_ set (mp_ int * a, mp_ digit b);
int mp_ init_ set_ int (mp_ int * a, unsigned long b);
\end { alltt}
2014-10-12 12:48:26 -04:00
Both functions work like the previous counterparts except they first mp\_ init $ a $ before setting the values.
2004-04-11 16:46:22 -04:00
\begin { alltt}
int main(void)
\{
mp_ int number1, number2;
int result;
/* initialize and set a single digit */
if ((result = mp_ init_ set(& number1, 100)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting number1: \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
2014-10-12 12:48:26 -04:00
\}
2004-04-11 16:46:22 -04:00
/* initialize and set a long */
if ((result = mp_ init_ set_ int(& number2, 1023)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting number2: \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* display */
printf("Number1, Number2 == \% lu, \% lu",
mp_ get_ int(& number1), mp_ get_ int(& number2));
/* clear */
mp_ clear_ multi(& number1, & number2, NULL);
return EXIT_ SUCCESS;
\}
\end { alltt}
If this program succeeds it shall output.
\begin { alltt}
Number1, Number2 == 100, 1023
\end { alltt}
2003-12-24 13:59:22 -05:00
\section { Comparisons}
Comparisons in LibTomMath are always performed in a ``left to right'' fashion. There are three possible return codes
for any comparison.
\index { MP\_ GT} \index { MP\_ EQ} \index { MP\_ LT}
2017-08-25 07:00:05 -04:00
\begin { figure} [h]
2003-12-24 13:59:22 -05:00
\begin { center}
\begin { tabular} { |c|c|}
\hline \textbf { Result Code} & \textbf { Meaning} \\
\hline MP\_ GT & $ a > b $ \\
\hline MP\_ EQ & $ a = b $ \\
\hline MP\_ LT & $ a < b $ \\
\hline
\end { tabular}
\end { center}
\caption { Comparison Codes for $ a, b $ }
\label { fig:CMP}
\end { figure}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
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
$ b $ .
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Unsigned comparison}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
An unsigned comparison considers only the digits themselves and not the associated \textit { sign} flag of the
2003-12-24 13:59:22 -05:00
mp\_ int structures. This is analogous to an absolute comparison. The function mp\_ cmp\_ mag() will compare two
2014-10-12 12:48:26 -04:00
mp\_ int variables based on their digits only.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ cmp\_ mag}
\begin { alltt}
2005-02-12 03:40:15 -05:00
int mp_ cmp_ mag(mp_ int * a, mp_ int * b);
2003-12-24 13:59:22 -05:00
\end { alltt}
2004-04-11 16:46:22 -04:00
This will compare $ a $ to $ b $ placing $ a $ to the left of $ b $ . This function cannot fail and will return one of the
2003-12-24 13:59:22 -05:00
three compare codes listed in figure \ref { fig:CMP} .
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number1, number2;
int result;
if ((result = mp_ init_ multi(& number1, & number2, NULL)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the numbers. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number1 to 5 */
mp_ set(& number1, 5);
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number2 to -6 */
mp_ set(& number2, 6);
if ((result = mp_ neg(& number2, & number2)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error negating number2. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
switch(mp_ cmp_ mag(& number1, & number2)) \{
case MP_ GT: printf("|number1| > |number2|"); break;
case MP_ EQ: printf("|number1| = |number2|"); break;
case MP_ LT: printf("|number1| < |number2|"); break;
\}
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear_ multi(& number1, & number2, NULL);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2014-10-12 12:48:26 -04:00
If this program\footnote { This function uses the mp\_ neg() function which is discussed in section \ref { sec:NEG} .} completes
2003-12-24 13:59:22 -05:00
successfully it should print the following.
\begin { alltt}
|number1| < |number2|
\end { alltt}
This is because $ \vert - 6 \vert = 6 $ and obviously $ 5 < 6 $ .
\subsection { Signed comparison}
To compare two mp\_ int variables based on their signed value the mp\_ cmp() function is provided.
\index { mp\_ cmp}
\begin { alltt}
int mp_ cmp(mp_ int * a, mp_ int * b);
\end { alltt}
2004-04-11 16:46:22 -04:00
This will compare $ a $ to the left of $ b $ . It will first compare the signs of the two mp\_ int variables. If they
2003-12-24 13:59:22 -05:00
differ it will return immediately based on their signs. If the signs are equal then it will compare the digits
individually. This function will return one of the compare conditions codes listed in figure \ref { fig:CMP} .
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number1, number2;
int result;
if ((result = mp_ init_ multi(& number1, & number2, NULL)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the numbers. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number1 to 5 */
mp_ set(& number1, 5);
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number2 to -6 */
mp_ set(& number2, 6);
if ((result = mp_ neg(& number2, & number2)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error negating number2. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
switch(mp_ cmp(& number1, & number2)) \{
case MP_ GT: printf("number1 > number2"); break;
case MP_ EQ: printf("number1 = number2"); break;
case MP_ LT: printf("number1 < number2"); break;
\}
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear_ multi(& number1, & number2, NULL);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2014-10-12 12:48:26 -04:00
If this program\footnote { This function uses the mp\_ neg() function which is discussed in section \ref { sec:NEG} .} completes
2003-12-24 13:59:22 -05:00
successfully it should print the following.
\begin { alltt}
number1 > number2
\end { alltt}
\subsection { Single Digit}
To compare a single digit against an mp\_ int the following function has been provided.
\index { mp\_ cmp\_ d}
\begin { alltt}
int mp_ cmp_ d(mp_ int * a, mp_ digit b);
\end { alltt}
2014-10-12 12:48:26 -04:00
This will compare $ a $ to the left of $ b $ using a signed comparison. Note that it will always treat $ b $ as
2003-12-24 13:59:22 -05:00
positive. This function is rather handy when you have to compare against small values such as $ 1 $ (which often
comes up in cryptography). The function cannot fail and will return one of the tree compare condition codes
listed in figure \ref { fig:CMP} .
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number to 5 */
mp_ set(& number, 5);
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
switch(mp_ cmp_ d(& number, 7)) \{
case MP_ GT: printf("number > 7"); break;
case MP_ EQ: printf("number = 7"); break;
case MP_ LT: printf("number < 7"); break;
\}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
If this program functions properly it will print out the following.
2003-02-28 11:09:08 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
number < 7
\end { alltt}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Logical Operations}
2003-02-28 11:09:08 -05:00
2003-12-24 13:59:22 -05:00
Logical operations are operations that can be performed either with simple shifts or boolean operators such as
AND, XOR and OR directly. These operations are very quick.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Multiplication by two}
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Multiplications and divisions by any power of two can be performed with quick logical shifts either left or
2014-10-12 12:48:26 -04:00
right depending on the operation.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
When multiplying or dividing by two a special case routine can be used which are as follows.
\index { mp\_ mul\_ 2} \index { mp\_ div\_ 2}
\begin { alltt}
int mp_ mul_ 2(mp_ int * a, mp_ int * b);
int mp_ div_ 2(mp_ int * a, mp_ int * b);
\end { alltt}
2003-02-28 11:07:58 -05:00
2004-04-11 16:46:22 -04:00
The former will assign twice $ a $ to $ b $ while the latter will assign half $ a $ to $ b $ . These functions are fast
2003-12-24 13:59:22 -05:00
since the shift counts and maskes are hardcoded into the routines.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\begin { small} \begin { alltt}
int main(void)
\{
mp_ int number;
int result;
if ((result = mp_ init(& number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2003-12-24 13:59:22 -05:00
/* set the number to 5 */
mp_ set(& number, 5);
/* multiply by two */
if ((result = mp\_ mul\_ 2(& number, & number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error multiplying the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
switch(mp_ cmp_ d(& number, 7)) \{
case MP_ GT: printf("2*number > 7"); break;
case MP_ EQ: printf("2*number = 7"); break;
case MP_ LT: printf("2*number < 7"); break;
\}
/* now divide by two */
if ((result = mp\_ div\_ 2(& number, & number)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error dividing the number. \% s",
2003-12-24 13:59:22 -05:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
switch(mp_ cmp_ d(& number, 7)) \{
case MP_ GT: printf("2*number/2 > 7"); break;
case MP_ EQ: printf("2*number/2 = 7"); break;
case MP_ LT: printf("2*number/2 < 7"); break;
\}
2014-10-12 12:48:26 -04:00
/* we're done with it. */
2003-12-24 13:59:22 -05:00
mp_ clear(& number);
return EXIT_ SUCCESS;
\}
\end { alltt} \end { small}
If this program is successful it will print out the following text.
\begin { alltt}
2*number > 7
2*number/2 < 7
\end { alltt}
2014-12-11 16:44:50 -05:00
Since $ 10 > 7 $ and $ 5 < 7 $ .
To multiply by a power of two the following function can be used.
2003-12-24 13:59:22 -05:00
\index { mp\_ mul\_ 2d}
\begin { alltt}
int mp_ mul_ 2d(mp_ int * a, int b, mp_ int * c);
\end { alltt}
2014-10-12 12:48:26 -04:00
This will multiply $ a $ by $ 2 ^ b $ and store the result in ``c''. If the value of $ b $ is less than or equal to
2014-12-11 16:44:50 -05:00
zero the function will copy $ a $ to ``c'' without performing any further actions. The multiplication itself
is implemented as a right-shift operation of $ a $ by $ b $ bits.
2003-12-24 13:59:22 -05:00
To divide by a power of two use the following.
\index { mp\_ div\_ 2d}
\begin { alltt}
int mp_ div_ 2d (mp_ int * a, int b, mp_ int * c, mp_ int * d);
\end { alltt}
2004-04-11 16:46:22 -04:00
Which will divide $ a $ by $ 2 ^ b $ , store the quotient in ``c'' and the remainder in ``d'. If $ b \le 0 $ then the
function simply copies $ a $ over to ``c'' and zeroes $ d $ . The variable $ d $ may be passed as a \textbf { NULL}
2014-12-11 16:44:50 -05:00
value to signal that the remainder is not desired. The division itself is implemented as a left-shift
operation of $ a $ by $ b $ bits.
2003-12-24 13:59:22 -05:00
2018-12-09 17:11:38 -05:00
\index { mp\_ tc\_ div\_ 2d} \label { arithrightshift}
\begin { alltt}
int mp_ tc_ div_ 2d (mp_ int * a, int b, mp_ int * c, mp_ int * d);
\end { alltt}
The two-co,mplement version of the function above. This can be used to implement arbitrary-precision two-complement integers together with the two-complement bit-wise operations at page \ref { tcbitwiseops} .
It is also not very uncommon to need just the power of two $ 2 ^ b $ ; for example the startvalue for the Newton method.
\index { mp\_ 2expt}
\begin { alltt}
int mp_ 2expt(mp_ int *a, int b);
\end { alltt}
It is faster than doing it by shifting $ 1 $ with \texttt { mp_ mul_ 2d} .
2003-12-24 13:59:22 -05:00
\subsection { Polynomial Basis Operations}
2014-10-12 12:48:26 -04:00
Strictly speaking the organization of the integers within the mp\_ int structures is what is known as a
2003-12-24 13:59:22 -05:00
``polynomial basis''. This simply means a field element is stored by divisions of a radix. For example, if
2014-10-12 12:48:26 -04:00
$ 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
the polynomial basis representation of $ z $ if $ f ( \beta ) = z $ for a given radix $ \beta $ .
2003-12-24 13:59:22 -05:00
To multiply by the polynomial $ g ( x ) = x $ all you have todo is shift the digits of the basis left one place. The
following function provides this operation.
\index { mp\_ lshd}
\begin { alltt}
int mp_ lshd (mp_ int * a, int b);
\end { alltt}
2004-04-11 16:46:22 -04:00
This will multiply $ a $ in place by $ x ^ b $ which is equivalent to shifting the digits left $ b $ places and inserting zeroes
2003-12-24 13:59:22 -05:00
in the least significant digits. Similarly to divide by a power of $ x $ the following function is provided.
\index { mp\_ rshd}
\begin { alltt}
void mp_ rshd (mp_ int * a, int b)
\end { alltt}
2004-04-11 16:46:22 -04:00
This will divide $ a $ in place by $ x ^ b $ and discard the remainder. This function cannot fail as it performs the operations
2003-12-24 13:59:22 -05:00
in place and no new digits are required to complete it.
2018-12-09 17:11:38 -05:00
\subsection { AND, OR, XOR and COMPLEMENT Operations}
2003-12-24 13:59:22 -05:00
While AND, OR and XOR operations are not typical ``bignum functions'' they can be useful in several instances. The
2018-12-09 17:11:38 -05:00
four functions are prototyped as follows.
2003-12-24 13:59:22 -05:00
2018-12-09 17:11:38 -05:00
\index { mp\_ or} \index { mp\_ and} \index { mp\_ xor} \index { mp\_ complement}
2003-12-24 13:59:22 -05:00
\begin { alltt}
int mp_ or (mp_ int * a, mp_ int * b, mp_ int * c);
int mp_ and (mp_ int * a, mp_ int * b, mp_ int * c);
int mp_ xor (mp_ int * a, mp_ int * b, mp_ int * c);
2018-12-09 17:11:38 -05:00
int mp_ complement(const mp_ int *a, mp_ int *b);
2003-12-24 13:59:22 -05:00
\end { alltt}
2018-12-09 17:11:38 -05:00
Which compute $ c = a \odot b $ where $ \odot $ is one of OR, AND or XOR and $ b = \sim a $ .
There are also three functions that act as if the ``bignum'' would be a two-complement number.
\index { mp\_ tc\_ or} \index { mp\_ tc\_ and} \index { mp\_ tc\_ xor} \label { tcbitwiseops}
\begin { alltt}
int mp_ tc_ or (mp_ int * a, mp_ int * b, mp_ int * c);
int mp_ tc_ and (mp_ int * a, mp_ int * b, mp_ int * c);
int mp_ tc_ xor (mp_ int * a, mp_ int * b, mp_ int * c);
\end { alltt}
The compute $ c = a \odot b $ as above if both $ a $ and $ b $ are positive, negative values are converted into their two-complement representation first. This can be used to implement arbitrary-precision two-complement integers together with the arithmetic right-shift at page \ref { arithrightshift} .
2003-12-24 13:59:22 -05:00
2018-05-03 17:45:02 -04:00
\subsection { Bit Picking}
\index { mp\_ get\_ bit}
\begin { alltt}
int mp_ get_ bit(mp_ int *a, int b)
\end { alltt}
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}
if the bit is 0 (zero) and \texttt { MP\_ VAL} if $ b < 0 $ .
2003-12-24 13:59:22 -05:00
\section { Addition and Subtraction}
To compute an addition or subtraction the following two functions can be used.
\index { mp\_ add} \index { mp\_ sub}
\begin { alltt}
int mp_ add (mp_ int * a, mp_ int * b, mp_ int * c);
int mp_ sub (mp_ int * a, mp_ int * b, mp_ int * c)
\end { alltt}
Which perform $ c = a \odot b $ where $ \odot $ is one of signed addition or subtraction. The operations are fully sign
aware.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Sign Manipulation}
\subsection { Negation}
\label { sec:NEG}
Simple integer negation can be performed with the following.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ neg}
\begin { alltt}
int mp_ neg (mp_ int * a, mp_ int * b);
\end { alltt}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
Which assigns $ - a $ to $ b $ .
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\subsection { Absolute}
Simple integer absolutes can be performed with the following.
2003-02-28 11:07:58 -05:00
2018-12-09 17:11:38 -05:00
\index { mp\_ abs}
2003-12-24 13:59:22 -05:00
\begin { alltt}
int mp_ abs (mp_ int * a, mp_ int * b);
\end { alltt}
2003-02-28 11:07:58 -05:00
2014-10-12 12:48:26 -04:00
Which assigns $ \vert a \vert $ to $ b $ .
2004-04-11 16:46:22 -04:00
\section { Integer Division and Remainder}
To perform a complete and general integer division with remainder use the following function.
\index { mp\_ div}
\begin { alltt}
int mp_ div (mp_ int * a, mp_ int * b, mp_ int * c, mp_ int * d);
\end { alltt}
2014-10-12 12:48:26 -04:00
This divides $ a $ by $ b $ and stores the quotient in $ c $ and $ d $ . The signed quotient is computed such that
$ bc + d = a $ . Note that either of $ c $ or $ d $ can be set to \textbf { NULL} if their value is not required. If
$ b $ is zero the function returns \textbf { MP\_ VAL} .
2004-04-11 16:46:22 -04:00
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\chapter { Multiplication and Squaring}
\section { Multiplication}
A full signed integer multiplication can be performed with the following.
\index { mp\_ mul}
\begin { alltt}
int mp_ mul (mp_ int * a, mp_ int * b, mp_ int * c);
\end { alltt}
2014-10-12 12:48:26 -04:00
Which assigns the full signed product $ ab $ to $ c $ . This function actually breaks into one of four cases which are
2003-12-24 13:59:22 -05:00
specific multiplication routines optimized for given parameters. First there are the Toom-Cook multiplications which
should only be used with very large inputs. This is followed by the Karatsuba multiplications which are for moderate
sized inputs. Then followed by the Comba and baseline multipliers.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
Fortunately for the developer you don't really need to know this unless you really want to fine tune the system. mp\_ mul()
will determine on its own\footnote { Some tweaking may be required.} what routine to use automatically when it is called.
2003-02-28 11:07:58 -05:00
2004-04-11 16:46:22 -04:00
\begin { alltt}
int main(void)
\{
mp_ int number1, number2;
int result;
/* Initialize the numbers */
2014-10-12 12:48:26 -04:00
if ((result = mp_ init_ multi(& number1,
2004-04-11 16:46:22 -04:00
& number2, NULL)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error initializing the numbers. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* set the terms */
if ((result = mp_ set_ int(& number, 257)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting number1. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2004-04-11 16:46:22 -04:00
if ((result = mp_ set_ int(& number2, 1023)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting number2. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* multiply them */
if ((result = mp_ mul(& number1, & number2,
& number1)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error multiplying terms. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* display */
printf("number1 * number2 == \% lu", mp_ get_ int(& number1));
/* free terms and return */
mp_ clear_ multi(& number1, & number2, NULL);
return EXIT_ SUCCESS;
\}
2014-10-12 12:48:26 -04:00
\end { alltt}
2004-04-11 16:46:22 -04:00
If this program succeeds it shall output the following.
\begin { alltt}
number1 * number2 == 262911
\end { alltt}
2003-12-24 13:59:22 -05:00
\section { Squaring}
Since squaring can be performed faster than multiplication it is performed it's own function instead of just using
mp\_ mul().
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\index { mp\_ sqr}
\begin { alltt}
int mp_ sqr (mp_ int * a, mp_ int * b);
\end { alltt}
2003-02-28 11:07:58 -05:00
2004-04-11 16:46:22 -04:00
Will square $ a $ and store it in $ b $ . Like the case of multiplication there are four different squaring
2005-02-12 03:40:15 -05:00
algorithms all which can be called from mp\_ sqr(). It is ideal to use mp\_ sqr over mp\_ mul when squaring terms because
2014-10-12 12:48:26 -04:00
of the speed difference.
2003-02-28 11:07:58 -05:00
2003-12-24 13:59:22 -05:00
\section { Tuning Polynomial Basis Routines}
2003-03-22 10:10:20 -05:00
2004-04-11 16:46:22 -04:00
Both of the Toom-Cook and Karatsuba multiplication algorithms are faster than the traditional $ O ( n ^ 2 ) $ approach that
2014-10-12 12:48:26 -04:00
the Comba and baseline algorithms use. At $ O ( n ^ { 1 . 464973 } ) $ and $ O ( n ^ { 1 . 584962 } ) $ running times respectively they require
2004-01-25 12:40:21 -05:00
considerably less work. For example, a 10000-digit multiplication would take roughly 724,000 single precision
2003-12-24 13:59:22 -05:00
multiplications with Toom-Cook or 100,000,000 single precision multiplications with the standard Comba (a factor
2004-01-25 12:40:21 -05:00
of 138).
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
So why not always use Karatsuba or Toom-Cook? The simple answer is that they have so much overhead that they're not
2014-10-12 12:48:26 -04:00
actually faster than Comba until you hit distinct ``cutoff'' points. For Karatsuba with the default configuration,
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
2003-12-24 13:59:22 -05:00
110 digits Karatsuba and Comba multiplications just about break even and for 110+ digits Karatsuba is faster.
2003-03-22 10:10:20 -05:00
2014-10-12 12:48:26 -04:00
Toom-Cook has incredible overhead and is probably only useful for very large inputs. So far no known cutoff points
2003-12-24 13:59:22 -05:00
exist and for the most part I just set the cutoff points very high to make sure they're not called.
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
A demo program in the ``etc/'' directory of the project called ``tune.c'' can be used to find the cutoff points. This
can be built with GCC as follows
2003-03-22 10:10:20 -05:00
2003-12-24 13:59:22 -05:00
\begin { alltt}
make XXX
\end { alltt}
Where ``XXX'' is one of the following entries from the table \ref { fig:tuning} .
2003-03-22 10:10:20 -05:00
2017-08-25 07:00:05 -04:00
\begin { figure} [h]
2003-03-22 10:10:20 -05:00
\begin { center}
\begin { small}
2003-12-24 13:59:22 -05:00
\begin { tabular} { |l|l|}
\hline \textbf { Value of XXX} & \textbf { Meaning} \\
\hline tune & Builds portable tuning application \\
\hline tune86 & Builds x86 (pentium and up) program for COFF \\
\hline tune86c & Builds x86 program for Cygwin \\
\hline tune86l & Builds x86 program for Linux (ELF format) \\
2003-03-22 10:10:20 -05:00
\hline
\end { tabular}
\end { small}
2003-12-24 13:59:22 -05:00
\end { center}
\caption { Build Names for Tuning Programs}
\label { fig:tuning}
2003-03-22 10:10:20 -05:00
\end { figure}
2003-12-24 13:59:22 -05:00
When the program is running it will output a series of measurements for different cutoff points. It will first find
good Karatsuba squaring and multiplication points. Then it proceeds to find Toom-Cook points. Note that the Toom-Cook
tuning takes a very long time as the cutoff points are likely to be very high.
\chapter { Modular Reduction}
2014-10-12 12:48:26 -04:00
Modular reduction is process of taking the remainder of one quantity divided by another. Expressed
as (\ref { eqn:mod} ) the modular reduction is equivalent to the remainder of $ b $ divided by $ c $ .
2004-04-11 16:46:22 -04:00
\begin { equation}
a \equiv b \mbox { (mod } c\mbox { )}
\label { eqn:mod}
\end { equation}
2014-10-12 12:48:26 -04:00
Of particular interest to cryptography are reductions where $ b $ is limited to the range $ 0 \le b < c ^ 2 $ since particularly
fast reduction algorithms can be written for the limited range.
2004-04-11 16:46:22 -04:00
Note that one of the four optimized reduction algorithms are automatically chosen in the modular exponentiation
2014-10-12 12:48:26 -04:00
algorithm mp\_ exptmod when an appropriate modulus is detected.
2004-04-11 16:46:22 -04:00
\section { Straight Division}
In order to effect an arbitrary modular reduction the following algorithm is provided.
\index { mp\_ mod}
2003-12-24 13:59:22 -05:00
\begin { alltt}
2004-04-11 16:46:22 -04:00
int mp_ mod(mp_ int *a, mp_ int *b, mp_ int *c);
2003-12-24 13:59:22 -05:00
\end { alltt}
2014-10-12 12:48:26 -04:00
This reduces $ a $ modulo $ b $ and stores the result in $ c $ . The sign of $ c $ shall agree with the sign
2004-04-11 16:46:22 -04:00
of $ b $ . This algorithm accepts an input $ a $ of any range and is not limited by $ 0 \le a < b ^ 2 $ .
2003-12-24 13:59:22 -05:00
\section { Barrett Reduction}
2004-04-11 16:46:22 -04:00
Barrett reduction is a generic optimized reduction algorithm that requires pre--computation to achieve
2005-02-12 03:40:15 -05:00
a decent speedup over straight division. First a $ \mu $ value must be precomputed with the following function.
2004-04-11 16:46:22 -04:00
\index { mp\_ reduce\_ setup}
\begin { alltt}
int mp_ reduce_ setup(mp_ int *a, mp_ int *b);
\end { alltt}
2005-02-12 03:40:15 -05:00
Given a modulus in $ b $ this produces the required $ \mu $ value in $ a $ . For any given modulus this only has to
2004-04-11 16:46:22 -04:00
be computed once. Modular reduction can now be performed with the following.
\index { mp\_ reduce}
\begin { alltt}
int mp_ reduce(mp_ int *a, mp_ int *b, mp_ int *c);
\end { alltt}
2005-02-12 03:40:15 -05:00
This will reduce $ a $ in place modulo $ b $ with the precomputed $ \mu $ value in $ c $ . $ a $ must be in the range
2004-04-11 16:46:22 -04:00
$ 0 \le a < b ^ 2 $ .
\begin { alltt}
int main(void)
\{
mp_ int a, b, c, mu;
int result;
2014-10-12 12:48:26 -04:00
/* initialize a,b to desired values, mp_ init mu,
* c and set c to 1...we want to compute a^ 3 mod b
2004-04-11 16:46:22 -04:00
*/
/* get mu value */
if ((result = mp_ reduce_ setup(& mu, b)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error getting mu. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* square a to get c = a^ 2 */
if ((result = mp_ sqr(& a, & c)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error squaring. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* now reduce `c' modulo b */
if ((result = mp_ reduce(& c, & b, & mu)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2004-04-11 16:46:22 -04:00
/* multiply a to get c = a^ 3 */
if ((result = mp_ mul(& a, & c, & c)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* now reduce `c' modulo b */
if ((result = mp_ reduce(& c, & b, & mu)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2004-04-11 16:46:22 -04:00
/* c now equals a^ 3 mod b */
return EXIT_ SUCCESS;
\}
2014-10-12 12:48:26 -04:00
\end { alltt}
2004-04-11 16:46:22 -04:00
2014-10-12 12:48:26 -04:00
This program will calculate $ a ^ 3 \mbox { mod } b $ if all the functions succeed.
2004-04-11 16:46:22 -04:00
2003-12-24 13:59:22 -05:00
\section { Montgomery Reduction}
2004-04-11 16:46:22 -04:00
Montgomery is a specialized reduction algorithm for any odd moduli. Like Barrett reduction a pre--computation
step is required. This is accomplished with the following.
\index { mp\_ montgomery\_ setup}
\begin { alltt}
int mp_ montgomery_ setup(mp_ int *a, mp_ digit *mp);
\end { alltt}
2014-10-12 12:48:26 -04:00
For the given odd moduli $ a $ the precomputation value is placed in $ mp $ . The reduction is computed with the
2004-04-11 16:46:22 -04:00
following.
\index { mp\_ montgomery\_ reduce}
\begin { alltt}
int mp_ montgomery_ reduce(mp_ int *a, mp_ int *m, mp_ digit mp);
\end { alltt}
This reduces $ a $ in place modulo $ m $ with the pre--computed value $ mp $ . $ a $ must be in the range
$ 0 \le a < b ^ 2 $ .
Montgomery reduction is faster than Barrett reduction for moduli smaller than the ``comba'' limit. With the default
setup for instance, the limit is $ 127 $ digits ($ 3556 $ --bits). Note that this function is not limited to
2014-10-12 12:48:26 -04:00
$ 127 $ digits just that it falls back to a baseline algorithm after that point.
2004-04-11 16:46:22 -04:00
2014-10-12 12:48:26 -04:00
An important observation is that this reduction does not return $ a \mbox { mod } m $ but $ aR ^ { - 1 } \mbox { mod } m $
where $ R = \beta ^ n $ , $ n $ is the n number of digits in $ m $ and $ \beta $ is radix used (default is $ 2 ^ { 28 } $ ).
2004-04-11 16:46:22 -04:00
To quickly calculate $ R $ the following function was provided.
\index { mp\_ montgomery\_ calc\_ normalization}
\begin { alltt}
int mp_ montgomery_ calc_ normalization(mp_ int *a, mp_ int *b);
\end { alltt}
2014-10-12 12:48:26 -04:00
Which calculates $ a = R $ for the odd moduli $ b $ without using multiplication or division.
2004-04-11 16:46:22 -04:00
The normal modus operandi for Montgomery reductions is to normalize the integers before entering the system. For
example, to calculate $ a ^ 3 \mbox { mod } b $ using Montgomery reduction the value of $ a $ can be normalized by
multiplying it by $ R $ . Consider the following code snippet.
\begin { alltt}
int main(void)
\{
mp_ int a, b, c, R;
mp_ digit mp;
int result;
2014-10-12 12:48:26 -04:00
/* initialize a,b to desired values,
* mp_ init R, c and set c to 1....
2004-04-11 16:46:22 -04:00
*/
/* get normalization */
if ((result = mp_ montgomery_ calc_ normalization(& R, b)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error getting norm. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* get mp value */
if ((result = mp_ montgomery_ setup(& c, & mp)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error setting up montgomery. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* normalize `a' so now a is equal to aR */
if ((result = mp_ mulmod(& a, & R, & b, & a)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error computing aR. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* square a to get c = a^ 2R^ 2 */
if ((result = mp_ sqr(& a, & c)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error squaring. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* now reduce `c' back down to c = a^ 2R^ 2 * R^ -1 == a^ 2R */
if ((result = mp_ montgomery_ reduce(& c, & b, mp)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2004-04-11 16:46:22 -04:00
/* multiply a to get c = a^ 3R^ 2 */
if ((result = mp_ mul(& a, & c, & c)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* now reduce `c' back down to c = a^ 3R^ 2 * R^ -1 == a^ 3R */
if ((result = mp_ montgomery_ reduce(& c, & b, mp)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
2014-10-12 12:48:26 -04:00
2004-04-11 16:46:22 -04:00
/* now reduce (again) `c' back down to c = a^ 3R * R^ -1 == a^ 3 */
if ((result = mp_ montgomery_ reduce(& c, & b, mp)) != MP_ OKAY) \{
2014-10-12 12:48:26 -04:00
printf("Error reducing. \% s",
2004-04-11 16:46:22 -04:00
mp_ error_ to_ string(result));
return EXIT_ FAILURE;
\}
/* c now equals a^ 3 mod b */
return EXIT_ SUCCESS;
\}
2014-10-12 12:48:26 -04:00
\end { alltt}
2004-04-11 16:46:22 -04:00
2014-10-12 12:48:26 -04:00
This particular example does not look too efficient but it demonstrates the point of the algorithm. By
2004-04-11 16:46:22 -04:00
normalizing the inputs the reduced results are always of the form $ aR $ for some variable $ a $ . This allows
a single final reduction to correct for the normalization and the fast reduction used within the algorithm.
For more details consider examining the file \textit { bn\_ mp\_ exptmod\_ fast.c} .
2018-05-03 17:45:02 -04:00
\section { Restricted Diminished Radix}
2004-04-11 16:46:22 -04:00
2018-05-03 17:45:02 -04:00
``Diminished Radix'' reduction refers to reduction with respect to moduli that are amenable to simple
2004-04-11 16:46:22 -04:00
digit shifting and small multiplications. In this case the ``restricted'' variant refers to moduli of the
2014-10-12 12:48:26 -04:00
form $ \beta ^ k - p $ for some $ k \ge 0 $ and $ 0 < p < \beta $ where $ \beta $ is the radix (default to $ 2 ^ { 28 } $ ).
2004-04-11 16:46:22 -04:00
As in the case of Montgomery reduction there is a pre--computation phase required for a given modulus.
\index { mp\_ dr\_ setup}
\begin { alltt}
void mp_ dr_ setup(mp_ int *a, mp_ digit *d);
\end { alltt}
This computes the value required for the modulus $ a $ and stores it in $ d $ . This function cannot fail
and does not return any error codes. After the pre--computation a reduction can be performed with the
following.
\index { mp\_ dr\_ reduce}
\begin { alltt}
int mp_ dr_ reduce(mp_ int *a, mp_ int *b, mp_ digit mp);
\end { alltt}
This reduces $ a $ in place modulo $ b $ with the pre--computed value $ mp $ . $ b $ must be of a restricted
2018-05-03 17:45:02 -04:00
diminished radix form and $ a $ must be in the range $ 0 \le a < b ^ 2 $ . Diminished radix reductions are
much faster than both Barrett and Montgomery reductions as they have a much lower asymptotic running time.
2004-04-11 16:46:22 -04:00
Since the moduli are restricted this algorithm is not particularly useful for something like Rabin, RSA or
BBS cryptographic purposes. This reduction algorithm is useful for Diffie-Hellman and ECC where fixed
2014-10-12 12:48:26 -04:00
primes are acceptable.
2004-04-11 16:46:22 -04:00
Note that unlike Montgomery reduction there is no normalization process. The result of this function is
equal to the correct residue.
2018-05-03 17:45:02 -04:00
\section { Unrestricted Diminished Radix}
2003-12-24 13:59:22 -05:00
2014-10-12 12:48:26 -04:00
Unrestricted reductions work much like the restricted counterparts except in this case the moduli is of the
form $ 2 ^ k - p $ for $ 0 < p < \beta $ . In this sense the unrestricted reductions are more flexible as they
can be applied to a wider range of numbers.
2004-04-11 16:46:22 -04:00
\index { mp\_ reduce\_ 2k\_ setup}
\begin { alltt}
int mp_ reduce_ 2k_ setup(mp_ int *a, mp_ digit *d);
\end { alltt}
2014-10-12 12:48:26 -04:00
This will compute the required $ d $ value for the given moduli $ a $ .
2004-04-11 16:46:22 -04:00
\index { mp\_ reduce\_ 2k}
\begin { alltt}
int mp_ reduce_ 2k(mp_ int *a, mp_ int *n, mp_ digit d);
\end { alltt}
2014-10-12 12:48:26 -04:00
This will reduce $ a $ in place modulo $ n $ with the pre--computed value $ d $ . From my experience this routine is
slower than mp\_ dr\_ reduce but faster for most moduli sizes than the Montgomery reduction.
2004-04-11 16:46:22 -04:00
2018-12-09 17:11:38 -05:00
\section { Combined Modular Reduction}
Some of the combinations of an arithmetic operations followed by a modular reduction can be done in a faster way. The ones implemented are:
Addition $ d = ( a + b ) \mod c $
\index { mp\_ addmod}
\begin { alltt}
int mp_ addmod(const mp_ int *a, const mp_ int *b, const mp_ int *c, mp_ int *d);
\end { alltt}
Subtraction $ d = ( a - b ) \mod c $
\begin { alltt}
int mp_ submod(const mp_ int *a, const mp_ int *b, const mp_ int *c, mp_ int *d);
\end { alltt}
Multiplication $ d = ( ab ) \mod c $
\begin { alltt}
int mp_ mulmod(const mp_ int *a, const mp_ int *b, const mp_ int *c, mp_ int *d);
\end { alltt}
Squaring $ d = ( a ^ 2 ) \mod c $
\begin { alltt}
int mp_ sqrmod(const mp_ int *a, const mp_ int *b, const mp_ int *c, mp_ int *d);
\end { alltt}
2003-12-24 13:59:22 -05:00
\chapter { Exponentiation}
\section { Single Digit Exponentiation}
2014-10-10 13:49:40 -04:00
\index { mp\_ expt\_ d\_ ex}
\begin { alltt}
int mp_ expt_ d_ ex (mp_ int * a, mp_ digit b, mp_ int * c, int fast)
\end { alltt}
This function computes $ c = a ^ b $ .
With parameter \textit { fast} set to $ 0 $ the old version of the algorithm is used,
when \textit { fast} is $ 1 $ , a faster but not statically timed version of the algorithm is used.
The old version uses a simple binary left-to-right algorithm.
It is faster than repeated multiplications by $ a $ for all values of $ b $ greater than three.
The new version uses a binary right-to-left algorithm.
The difference between the old and the new version is that the old version always
executes $ DIGIT \_ BIT $ iterations. The new algorithm executes only $ n $ iterations
where $ n $ is equal to the position of the highest bit that is set in $ b $ .
2003-12-24 13:59:22 -05:00
\index { mp\_ expt\_ d}
\begin { alltt}
int mp_ expt_ d (mp_ int * a, mp_ digit b, mp_ int * c)
\end { alltt}
2014-10-10 13:49:40 -04:00
mp\_ expt\_ d(a, b, c) is a wrapper function to mp\_ expt\_ d\_ ex(a, b, c, 0).
2003-12-24 13:59:22 -05:00
\section { Modular Exponentiation}
\index { mp\_ exptmod}
\begin { alltt}
int mp_ exptmod (mp_ int * G, mp_ int * X, mp_ int * P, mp_ int * Y)
\end { alltt}
This computes $ Y \equiv G ^ X \mbox { ( mod } P \mbox { ) } $ using a variable width sliding window algorithm. This function
2014-10-12 12:48:26 -04:00
will automatically detect the fastest modular reduction technique to use during the operation. For negative values of
$ X $ the operation is performed as $ Y \equiv ( G ^ { - 1 } \mbox { mod } P ) ^ { \vert X \vert } \mbox { ( mod } P \mbox { ) } $ provided that
2004-04-11 16:46:22 -04:00
$ gcd ( G, P ) = 1 $ .
This function is actually a shell around the two internal exponentiation functions. This routine will automatically
2018-05-03 17:45:02 -04:00
detect when Barrett, Montgomery, Restricted and Unrestricted Diminished Radix based exponentiation can be used. Generally
moduli of the a ``restricted diminished radix'' form lead to the fastest modular exponentiations. Followed by Montgomery
2004-04-11 16:46:22 -04:00
and the other two algorithms.
2003-12-24 13:59:22 -05:00
2018-12-09 17:11:38 -05:00
\section { Modulus a Power of Two}
\index { mp\_ mod_ 2d}
\begin { alltt}
int mp_ mod_ 2d(const mp_ int *a, int b, mp_ int *c)
\end { alltt}
It calculates $ c = a \mod 2 ^ b $ .
2003-12-24 13:59:22 -05:00
\section { Root Finding}
\index { mp\_ n\_ root}
\begin { alltt}
int mp_ n_ root (mp_ int * a, mp_ digit b, mp_ int * c)
\end { alltt}
2014-10-12 12:48:26 -04:00
This computes $ c = a ^ { 1 / b } $ such that $ c ^ b \le a $ and $ ( c + 1 ) ^ b > a $ . The implementation of this function is not
2003-12-24 13:59:22 -05:00
ideal for values of $ b $ greater than three. It will work but become very slow. So unless you are working with very small
numbers (less than 1000 bits) I'd avoid $ b > 3 $ situations. Will return a positive root only for even roots and return
2014-10-12 12:48:26 -04:00
a root with the sign of the input for odd roots. For example, performing $ 4 ^ { 1 / 2 } $ will return $ 2 $ whereas $ ( - 8 ) ^ { 1 / 3 } $
will return $ - 2 $ .
2003-12-24 13:59:22 -05:00
2004-04-11 16:46:22 -04:00
This algorithm uses the ``Newton Approximation'' method and will converge on the correct root fairly quickly. Since
the algorithm requires raising $ a $ to the power of $ b $ it is not ideal to attempt to find roots for large
values of $ b $ . If particularly large roots are required then a factor method could be used instead. For example,
2014-10-12 12:48:26 -04:00
$ a ^ { 1 / 16 } $ is equivalent to $ \left ( a ^ { 1 / 4 } \right ) ^ { 1 / 4 } $ or simply
2005-02-12 03:40:15 -05:00
$ \left ( \left ( \left ( a ^ { 1 / 2 } \right ) ^ { 1 / 2 } \right ) ^ { 1 / 2 } \right ) ^ { 1 / 2 } $
2004-04-11 16:46:22 -04:00
2018-12-09 17:11:38 -05:00
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.
\index { mp\_ sqrt}
\begin { alltt}
int mp_ sqrt (mp_ int * a, mp_ digit b, mp_ int * c)
\end { alltt}
2003-12-24 13:59:22 -05:00
\chapter { Prime Numbers}
\section { Trial Division}
\index { mp\_ prime\_ is\_ divisible}
\begin { alltt}
int mp_ prime_ is_ divisible (mp_ int * a, int *result)
\end { alltt}
2014-10-12 12:48:26 -04:00
This will attempt to evenly divide $ a $ by a list of primes\footnote { Default is the first 256 primes.} and store the
outcome in ``result''. That is if $ result = 0 $ then $ a $ is not divisible by the primes, otherwise it is. Note that
2003-12-24 13:59:22 -05:00
if the function does not return \textbf { MP\_ OKAY} the value in ``result'' should be considered undefined\footnote { Currently
the default is to set it to zero first.} .
\section { Fermat Test}
\index { mp\_ prime\_ fermat}
\begin { alltt}
int mp_ prime_ fermat (mp_ int * a, mp_ int * b, int *result)
\end { alltt}
Performs a Fermat primality test to the base $ b $ . That is it computes $ b ^ a \mbox { mod } a $ and tests whether the value is
equal to $ b $ or not. If the values are equal then $ a $ is probably prime and $ result $ is set to one. Otherwise $ result $
is set to zero.
\section { Miller-Rabin Test}
\index { mp\_ prime\_ miller\_ rabin}
\begin { alltt}
int mp_ prime_ miller_ rabin (mp_ int * a, mp_ int * b, int *result)
\end { alltt}
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
2014-10-12 12:48:26 -04:00
fool (besides with Carmichael numbers). If $ a $ passes the test (therefore is probably prime) $ result $ is set to one.
Otherwise $ result $ is set to zero.
2003-12-24 13:59:22 -05:00
2014-10-12 12:48:26 -04:00
Note that is suggested that you use the Miller-Rabin test instead of the Fermat test since all of the failures of
2003-12-24 13:59:22 -05:00
Miller-Rabin are a subset of the failures of the Fermat test.
\subsection { Required Number of Tests}
Generally to ensure a number is very likely to be prime you have to perform the Miller-Rabin with at least a half-dozen
or so unique bases. However, it has been proven that the probability of failure goes down as the size of the input goes up.
This is why a simple function has been provided to help out.
\index { mp\_ prime\_ rabin\_ miller\_ trials}
\begin { alltt}
int mp_ prime_ rabin_ miller_ trials(int size)
\end { alltt}
This returns the number of trials required for a $ 2 ^ { - 96 } $ (or lower) 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
2014-10-12 12:48:26 -04:00
require ten tests whereas a 1024-bit number would only require four tests.
2003-12-24 13:59:22 -05:00
You should always still perform a trial division before a Miller-Rabin test though.
2018-05-03 17:45:02 -04:00
\section { Strong Lucas-Selfridge Test}
\index { mp\_ prime\_ strong\_ lucas\_ selfridge}
\begin { alltt}
int mp_ prime_ strong_ lucas_ selfridge(const mp_ int *a, int *result)
\end { alltt}
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 as a compile-time option in \texttt { mp\_ prime\_ is\_ prime} and can be excluded
from the Libtommath build if not needed.
\section { Frobenius (Underwood) Test}
\index { mp\_ prime\_ frobenius\_ underwood}
\begin { alltt}
int mp_ prime_ frobenius_ underwood(const mp_ int *N, int *result)
\end { alltt}
Performs the variant of the Frobenius test as described by Paul Underwood. The single internal use is as a compile-time option in
\texttt { mp\_ prime\_ is\_ prime} and can be excluded from the Libtommath build if not needed.
2003-12-24 13:59:22 -05:00
\section { Primality Testing}
2018-12-09 17:11:38 -05:00
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.
\index { mp\_ is\_ square}
\begin { alltt}
int mp_ is_ square(const mp_ int *arg, int *ret);
\end { alltt}
2003-12-24 13:59:22 -05:00
\index { mp\_ prime\_ is\_ prime}
\begin { alltt}
int mp_ prime_ is_ prime (mp_ int * a, int t, int *result)
\end { alltt}
2018-05-03 17:45:02 -04:00
This will perform a trial division followed by two rounds of Miller-Rabin with bases 2 and 3. It is possible, although only at
the compile time of this library for now, to include a strong Lucas-Selfridge test and/or a Frobenius test. See file
\texttt { bn\_ mp\_ prime\_ is\_ prime.c} for the necessary details. It shall be noted that both functions are much slower than
the Miller-Rabin test.
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.
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. If $ - t > 13 $ than $ - t - 13 $ additional rounds of the
Miller-Rabin test will be performed but note that $ - t $ is bounded by $ 1 \le - t < PRIME \_ SIZE $ where $ PRIME \_ SIZE $ is the number
of primes in the prime number table (by default this is $ 256 $ ) and the first 13 primes have already been used. It will return
\texttt { MP\_ VAL} in case of$ - t > PRIME \_ SIZE $ .
If $ a $ passes all of the tests $ result $ is set to one, otherwise it is set to zero.
2003-12-24 13:59:22 -05:00
\section { Next Prime}
\index { mp\_ prime\_ next\_ prime}
\begin { alltt}
int mp_ prime_ next_ prime(mp_ int *a, int t, int bbs_ style)
\end { alltt}
2018-05-03 17:45:02 -04:00
This finds the next prime after $ a $ that passes mp\_ prime\_ is\_ prime() with $ t $ tests but see the documentation for
mp\_ prime\_ is\_ prime for details regarding the use of the argument $ t $ . Set $ bbs \_ style $ to one if you
2014-10-12 12:48:26 -04:00
want only the next prime congruent to $ 3 \mbox { mod } 4 $ , otherwise set it to zero to find any next prime.
2003-12-24 13:59:22 -05:00
\section { Random Primes}
\index { mp\_ prime\_ random}
\begin { alltt}
2014-10-12 12:48:26 -04:00
int mp_ prime_ random(mp_ int *a, int t, int size, int bbs,
2003-12-24 13:59:22 -05:00
ltm_ prime_ callback cb, void *dat)
\end { alltt}
This will find a prime greater than $ 256 ^ { size } $ which can be ``bbs\_ style'' or not depending on $ bbs $ and must pass
2018-05-03 17:45:02 -04:00
$ t $ rounds of tests but see the documentation for mp\_ prime\_ is\_ prime for details regarding the use of the argument $ t $ .
The ``ltm\_ prime\_ callback'' is a typedef for
2003-12-24 13:59:22 -05:00
\begin { alltt}
typedef int ltm_ prime_ callback(unsigned char *dst, int len, void *dat);
\end { alltt}
Which is a function that must read $ len $ bytes (and return the amount stored) into $ dst $ . The $ dat $ variable is simply
2014-10-12 12:48:26 -04:00
copied from the original input. It can be used to pass RNG context data to the callback. The function
mp\_ prime\_ random() is more suitable for generating primes which must be secret (as in the case of RSA) since there
2004-04-11 16:46:22 -04:00
is no skew on the least significant bits.
2003-12-24 13:59:22 -05:00
2004-04-11 16:46:22 -04:00
\textit { Note:} As of v0.30 of the LibTomMath library this function has been deprecated. It is still available
but users are encouraged to use the new mp\_ prime\_ random\_ ex() function instead.
\subsection { Extended Generation}
\index { mp\_ prime\_ random\_ ex}
\begin { alltt}
2014-10-12 12:48:26 -04:00
int mp_ prime_ random_ ex(mp_ int *a, int t,
int size, int flags,
2004-04-11 16:46:22 -04:00
ltm_ prime_ callback cb, void *dat);
\end { alltt}
This will generate a prime in $ a $ using $ t $ tests of the primality testing algorithms. The variable $ size $
specifies the bit length of the prime desired. The variable $ flags $ specifies one of several options available
2014-10-12 12:48:26 -04:00
(see fig. \ref { fig:primeopts} ) which can be OR'ed together. The callback parameters are used as in
2004-04-11 16:46:22 -04:00
mp\_ prime\_ random().
2017-08-25 07:00:05 -04:00
\begin { figure} [h]
2004-04-11 16:46:22 -04:00
\begin { center}
\begin { small}
\begin { tabular} { |r|l|}
\hline \textbf { Flag} & \textbf { Meaning} \\
\hline LTM\_ PRIME\_ BBS & Make the prime congruent to $ 3 $ modulo $ 4 $ \\
\hline LTM\_ PRIME\_ SAFE & Make a prime $ p $ such that $ ( p - 1 ) / 2 $ is also prime. \\
& This option implies LTM\_ PRIME\_ BBS as well. \\
\hline LTM\_ PRIME\_ 2MSB\_ OFF & Makes sure that the bit adjacent to the most significant bit \\
& Is forced to zero. \\
\hline LTM\_ PRIME\_ 2MSB\_ ON & Makes sure that the bit adjacent to the most significant bit \\
& Is forced to one. \\
\hline
\end { tabular}
\end { small}
\end { center}
\caption { Primality Generation Options}
\label { fig:primeopts}
\end { figure}
2003-12-24 13:59:22 -05:00
2018-12-09 17:11:38 -05:00
\chapter { Random Number Generation}
\section { PRNG}
\index { mp\_ rand}
\begin { alltt}
int mp_ rand(mp_ int *a, int digits)
\end { alltt}
The function generates a random number of \texttt { digits} bits.
This random number 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, and \texttt { \dev \urandom } on all operating systems that have it.
2003-12-24 13:59:22 -05:00
\chapter { Input and Output}
\section { ASCII Conversions}
2004-01-25 12:40:21 -05:00
\subsection { To ASCII}
\index { mp\_ toradix}
\begin { alltt}
int mp_ toradix (mp_ int * a, char *str, int radix);
\end { alltt}
2004-04-11 16:46:22 -04:00
This still store $ a $ in ``str'' as a base-``radix'' string of ASCII chars. This function appends a NUL character
2004-01-25 12:40:21 -05:00
to terminate the string. Valid values of ``radix'' line in the range $ [ 2 , 64 ] $ . To determine the size (exact) required
by the conversion before storing any data use the following function.
2018-12-09 17:11:38 -05:00
\index { mp\_ toradix\_ n}
\begin { alltt}
int mp_ toradix_ n (mp_ int * a, char *str, int radix, int maxlen);
\end { alltt}
Like \texttt { mp\_ toradix} but stores upto maxlen-1 chars and always a NULL byte.
2004-01-25 12:40:21 -05:00
\index { mp\_ radix\_ size}
\begin { alltt}
int mp_ radix_ size (mp_ int * a, int radix, int *size)
\end { alltt}
2014-10-12 12:48:26 -04:00
This stores in ``size'' the number of characters (including space for the NUL terminator) required. Upon error this
function returns an error code and ``size'' will be zero.
2004-01-25 12:40:21 -05:00
2018-12-09 17:11:38 -05:00
If \texttt { LTM\_ NO\_ FILE} is not defined a function to write to a file is also available.
\index { mp\_ fwrite}
\begin { alltt}
int mp_ fwrite(const mp_ int *a, int radix, FILE *stream);
\end { alltt}
2004-01-25 12:40:21 -05:00
\subsection { From ASCII}
\index { mp\_ read\_ radix}
\begin { alltt}
int mp_ read_ radix (mp_ int * a, char *str, int radix);
\end { alltt}
2004-04-11 16:46:22 -04:00
This will read the base-``radix'' NUL terminated string from ``str'' into $ a $ . It will stop reading when it reads a
2004-01-25 12:40:21 -05:00
character it does not recognize (which happens to include th NUL char... imagine that...). A single leading $ - $ sign
can be used to denote a negative number.
2018-12-09 17:11:38 -05:00
If \texttt { LTM\_ NO\_ FILE} is not defined a function to read from a file is also available.
\index { mp\_ fread}
\begin { alltt}
int mp_ fread(mp_ int *a, int radix, FILE *stream);
\end { alltt}
2003-12-24 13:59:22 -05:00
\section { Binary Conversions}
2004-04-11 16:46:22 -04:00
Converting an mp\_ int to and from binary is another keen idea.
\index { mp\_ unsigned\_ bin\_ size}
\begin { alltt}
int mp_ unsigned_ bin_ size(mp_ int *a);
\end { alltt}
This will return the number of bytes (octets) required to store the unsigned copy of the integer $ a $ .
\index { mp\_ to\_ unsigned\_ bin}
\begin { alltt}
int mp_ to_ unsigned_ bin(mp_ int *a, unsigned char *b);
\end { alltt}
This will store $ a $ into the buffer $ b $ in big--endian format. Fortunately this is exactly what DER (or is it ASN?)
requires. It does not store the sign of the integer.
2018-12-09 17:11:38 -05:00
\index { mp\_ to\_ unsigned\_ bin\_ n}
\begin { alltt}
int mp_ to_ unsigned_ bin_ n(const mp_ int *a, unsigned char *b, unsigned long *outlen)
\end { alltt}
Like \texttt { mp\_ to\_ unsigned\_ bin} but checks if the value at \texttt { *outlen} is larger than or equal to the output of \texttt { mp\_ unsigned\_ bin\_ size(a)} and sets \texttt { *outlen} to the output of \texttt { mp\_ unsigned\_ bin\_ size(a)} or returns \texttt { MP\_ VAL} if the test failed.
2004-04-11 16:46:22 -04:00
\index { mp\_ read\_ unsigned\_ bin}
\begin { alltt}
int mp_ read_ unsigned_ bin(mp_ int *a, unsigned char *b, int c);
\end { alltt}
This will read in an unsigned big--endian array of bytes (octets) from $ b $ of length $ c $ into $ a $ . The resulting
integer $ a $ will always be positive.
For those who acknowledge the existence of negative numbers (heretic!) there are ``signed'' versions of the
previous functions.
2018-12-09 17:11:38 -05:00
\index { mp\_ signed\_ bin\_ size} \index { mp\_ to\_ signed\_ bin} \index { mp\_ read\_ signed\_ bin}
2004-04-11 16:46:22 -04:00
\begin { alltt}
int mp_ signed_ bin_ size(mp_ int *a);
int mp_ read_ signed_ bin(mp_ int *a, unsigned char *b, int c);
int mp_ to_ signed_ bin(mp_ int *a, unsigned char *b);
\end { alltt}
They operate essentially the same as the unsigned copies except they prefix the data with zero or non--zero
byte depending on the sign. If the sign is zpos (e.g. not negative) the prefix is zero, otherwise the prefix
2014-10-12 12:48:26 -04:00
is non--zero.
2003-12-24 13:59:22 -05:00
2018-12-09 17:11:38 -05:00
The two functions \texttt { mp\_ import} and \texttt { mp\_ export} implement the corresponding GMP functions as described at \url { http://gmplib.org/manual/Integer-Import-and-Export.html} .
\index { mp\_ import} \index { mp\_ export}
\begin { alltt}
int mp_ import(mp_ int *rop, size_ t count, int order, size_ t size, int endian, size_ t nails, const void *op);
int mp_ export(void *rop, size_ t *countp, int order, size_ t size, int endian, size_ t nails, const mp_ int *op);
\end { alltt}
2003-12-24 13:59:22 -05:00
\chapter { Algebraic Functions}
2004-01-25 12:40:21 -05:00
\section { Extended Euclidean Algorithm}
\index { mp\_ exteuclid}
\begin { alltt}
2014-10-12 12:48:26 -04:00
int mp_ exteuclid(mp_ int *a, mp_ int *b,
2004-01-25 12:40:21 -05:00
mp_ int *U1, mp_ int *U2, mp_ int *U3);
\end { alltt}
This finds the triple U1/U2/U3 using the Extended Euclidean algorithm such that the following equation holds.
\begin { equation}
a \cdot U1 + b \cdot U2 = U3
\end { equation}
2018-05-03 17:45:02 -04:00
Any of the U1/U2/U3 parameters can be set to \textbf { NULL} if they are not desired.
2004-04-11 16:46:22 -04:00
2003-12-24 13:59:22 -05:00
\section { Greatest Common Divisor}
\index { mp\_ gcd}
\begin { alltt}
int mp_ gcd (mp_ int * a, mp_ int * b, mp_ int * c)
\end { alltt}
This will compute the greatest common divisor of $ a $ and $ b $ and store it in $ c $ .
\section { Least Common Multiple}
\index { mp\_ lcm}
\begin { alltt}
int mp_ lcm (mp_ int * a, mp_ int * b, mp_ int * c)
\end { alltt}
This will compute the least common multiple of $ a $ and $ b $ and store it in $ c $ .
\section { Jacobi Symbol}
\index { mp\_ jacobi}
\begin { alltt}
int mp_ jacobi (mp_ int * a, mp_ int * p, int *c)
\end { alltt}
This will compute the Jacobi symbol for $ a $ with respect to $ p $ . If $ p $ is prime this essentially computes the Legendre
symbol. The result is stored in $ c $ and can take on one of three values $ \lbrace - 1 , 0 , 1 \rbrace $ . If $ p $ is prime
then the result will be $ - 1 $ when $ a $ is not a quadratic residue modulo $ p $ . The result will be $ 0 $ if $ a $ divides $ p $
2014-10-12 12:48:26 -04:00
and the result will be $ 1 $ if $ a $ is a quadratic residue modulo $ p $ .
2003-12-24 13:59:22 -05:00
2018-05-03 17:45:02 -04:00
\section { Kronecker Symbol}
\index { mp\_ kronecker}
\begin { alltt}
int mp_ kronecker (mp_ int * a, mp_ int * p, int *c)
\end { alltt}
Extension of the Jacoby symbol to all $ \lbrace a, p \rbrace \in \mathbb { Z } $ .
2015-04-25 16:47:23 -04:00
\section { Modular square root}
\index { mp\_ sqrtmod\_ prime}
\begin { alltt}
int mp_ sqrtmod_ prime(mp_ int *n, mp_ int *p, mp_ int *r)
\end { alltt}
This will solve the modular equatioon $ r ^ 2 = n \mod p $ where $ p $ is a prime number greater than 2 (odd prime).
The result is returned in the third argument $ r $ , the function returns \textbf { MP\_ OKAY} on success,
other return values indicate failure.
The implementation is split for two different cases:
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
$ r = n ^ { ( p + 1 ) / 4 } \mod p $
2. otherwise we use \href { https://en.wikipedia.org/wiki/Tonelli-Shanks_ algorithm} { Tonelli-Shanks algorithm}
The function does not check the primality of parameter $ p $ thus it is up to the caller to assure that this parameter
is a prime number. When $ p $ is a composite the function behaviour is undefined, it may even return a false-positive
\textbf { MP\_ OKAY} .
2003-12-24 13:59:22 -05:00
\section { Modular Inverse}
\index { mp\_ invmod}
\begin { alltt}
int mp_ invmod (mp_ int * a, mp_ int * b, mp_ int * c)
\end { alltt}
Computes the multiplicative inverse of $ a $ modulo $ b $ and stores the result in $ c $ such that $ ac \equiv 1 \mbox { ( mod } b \mbox { ) } $ .
2004-04-11 16:46:22 -04:00
\section { Single Digit Functions}
2003-12-24 13:59:22 -05:00
2004-04-11 16:46:22 -04:00
For those using small numbers (\textit { snicker snicker} ) there are several ``helper'' functions
2003-12-24 13:59:22 -05:00
2004-04-11 16:46:22 -04:00
\index { mp\_ add\_ d} \index { mp\_ sub\_ d} \index { mp\_ mul\_ d} \index { mp\_ div\_ d} \index { mp\_ mod\_ d}
\begin { alltt}
int mp_ add_ d(mp_ int *a, mp_ digit b, mp_ int *c);
int mp_ sub_ d(mp_ int *a, mp_ digit b, mp_ int *c);
int mp_ mul_ d(mp_ int *a, mp_ digit b, mp_ int *c);
int mp_ div_ d(mp_ int *a, mp_ digit b, mp_ int *c, mp_ digit *d);
int mp_ mod_ d(mp_ int *a, mp_ digit b, mp_ digit *c);
\end { alltt}
These work like the full mp\_ int capable variants except the second parameter $ b $ is a mp\_ digit. These
functions fairly handy if you have to work with relatively small numbers since you will not have to allocate
an entire mp\_ int to store a number like $ 1 $ or $ 2 $ .
2003-12-24 13:59:22 -05:00
2018-05-03 17:45:02 -04:00
\index { mp\_ mul\_ si}
\begin { alltt}
int mp_ mul_ si(mp_ int *a, long b, mp_ int *c);
\end { alltt}
Just like the functions above but with the ability to use a signed input as the small number.
2018-12-09 17:11:38 -05:00
The division by three can be made faster by replacing the division with a multiplication by the multiplicative inverse of three.
\index { mp\_ div\_ 3}
\begin { alltt}
int mp_ div_ 3(const mp_ int *a, mp_ int *c, mp_ digit *d);
\end { alltt}
\chapter { Little Helpers}
It is never wrong to have some useful little shortcuts at hand.
\section { Function Macros}
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.
\index { mp\_ iseven}
\begin { alltt}
int mp_ iseven(mp_ int *a)
\end { alltt}
Checks if $ a = 0 mod 2 $
\index { mp\_ isodd}
\begin { alltt}
int mp_ isodd(mp_ int *a)
\end { alltt}
Checks if $ a = 1 mod 2 $
\index { mp\_ isneg}
\begin { alltt}
int mp_ isneg(mp_ int *a)
\end { alltt}
Checks if $ a < 0 $
\index { mp\_ iszero}
\begin { alltt}
int mp_ iszero(mp_ int *a)
\end { alltt}
Checks if $ a = 0 $ . It does not check if the amount of memory allocated for $ a $ is also minimal.
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!
\subsection { Renamings}
\index { mp\_ mag\_ size}
\begin { alltt}
#define mp_ mag_ size(mp) mp_ unsigned_ bin_ size(mp)
\end { alltt}
\index { mp\_ raw\_ size}
\begin { alltt}
#define mp_ raw_ size(mp) mp_ signed_ bin_ size(mp)
\end { alltt}
\index { mp\_ read\_ mag}
\begin { alltt}
#define mp_ read_ mag(mp, str, len) mp_ read_ unsigned_ bin((mp), (str), (len))
\end { alltt}
\index { mp\_ read\_ raw}
\begin { alltt}
#define mp_ read_ raw(mp, str, len) mp_ read_ signed_ bin((mp), (str), (len))
\end { alltt}
\index { mp\_ tomag}
\begin { alltt}
#define mp_ tomag(mp, str) mp_ to_ unsigned_ bin((mp), (str))
\end { alltt}
\index { mp\_ toraw}
\begin { alltt}
#define mp_ toraw(mp, str) mp_ to_ signed_ bin((mp), (str))
\end { alltt}
\subsection { Shortcuts}
\index { mp\_ tobinary}
\begin { alltt}
#define mp_ tobinary(M, S) mp_ toradix((M), (S), 2)
\end { alltt}
\index { mp\_ tooctal}
\begin { alltt}
#define mp_ tooctal(M, S) mp_ toradix((M), (S), 8)
\end { alltt}
\index { mp\_ todecimal}
\begin { alltt}
#define mp_ todecimal(M, S) mp_ toradix((M), (S), 10)
\end { alltt}
\index { mp\_ tohex}
\begin { alltt}
#define mp_ tohex(M, S) mp_ toradix((M), (S), 16)
\end { alltt}
2003-12-24 13:59:22 -05:00
\input { bn.ind}
2003-02-28 11:07:58 -05:00
\end { document}